Thumb2 asm aliases for wide bitwise w/ immediate 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 #define DEBUG_TYPE "arm-isel"
16 #include "ARM.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSubtarget.h"
24 #include "ARMTargetMachine.h"
25 #include "ARMTargetObjectFile.h"
26 #include "MCTargetDesc/ARMAddressingModes.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/Function.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/Instruction.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Type.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/IntrinsicLowering.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineModuleInfo.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <sstream>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57
58 // This option should go away when tail calls fully work.
59 static cl::opt<bool>
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
62   cl::init(false));
63
64 cl::opt<bool>
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66   cl::desc("Generate calls via indirect call instructions"),
67   cl::init(false));
68
69 static cl::opt<bool>
70 ARMInterworking("arm-interworking", cl::Hidden,
71   cl::desc("Enable / disable ARM interworking (for debugging only)"),
72   cl::init(true));
73
74 namespace {
75   class ARMCCState : public CCState {
76   public:
77     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
79                LLVMContext &C, ParmContext PC)
80         : CCState(CC, isVarArg, MF, TM, locs, C) {
81       assert(((PC == Call) || (PC == Prologue)) &&
82              "ARMCCState users must specify whether their context is call"
83              "or prologue generation.");
84       CallOrPrologue = PC;
85     }
86   };
87 }
88
89 // The APCS parameter registers.
90 static const unsigned GPRArgRegs[] = {
91   ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 };
93
94 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
95                                        EVT PromotedBitwiseVT) {
96   if (VT != PromotedLdStVT) {
97     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
98     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
99                        PromotedLdStVT.getSimpleVT());
100
101     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
102     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
103                        PromotedLdStVT.getSimpleVT());
104   }
105
106   EVT ElemTy = VT.getVectorElementType();
107   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
108     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
109   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
110   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
111   if (ElemTy == MVT::i32) {
112     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
113     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
114     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
115     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
116   } else {
117     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
118     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
119     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
120     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
121   }
122   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
123   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
124   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
125   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
126   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
127   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
129   if (VT.isInteger()) {
130     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
131     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
132     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
133   }
134
135   // Promote all bit-wise operations.
136   if (VT.isInteger() && VT != PromotedBitwiseVT) {
137     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
138     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
139                        PromotedBitwiseVT.getSimpleVT());
140     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
141     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
142                        PromotedBitwiseVT.getSimpleVT());
143     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
144     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
145                        PromotedBitwiseVT.getSimpleVT());
146   }
147
148   // Neon does not support vector divide/remainder operations.
149   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
150   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
153   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
154   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
155 }
156
157 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
158   addRegisterClass(VT, ARM::DPRRegisterClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161
162 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
163   addRegisterClass(VT, ARM::QPRRegisterClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166
167 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
168   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
169     return new TargetLoweringObjectFileMachO();
170
171   return new ARMElfTargetObjectFile();
172 }
173
174 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
175     : TargetLowering(TM, createTLOF(TM)) {
176   Subtarget = &TM.getSubtarget<ARMSubtarget>();
177   RegInfo = TM.getRegisterInfo();
178   Itins = TM.getInstrItineraryData();
179
180   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
181
182   if (Subtarget->isTargetDarwin()) {
183     // Uses VFP for Thumb libfuncs if available.
184     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
185       // Single-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
187       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
188       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
189       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
190
191       // Double-precision floating-point arithmetic.
192       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
193       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
194       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
195       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
196
197       // Single-precision comparisons.
198       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
199       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
200       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
201       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
202       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
203       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
204       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
205       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
206
207       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
214       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
215
216       // Double-precision comparisons.
217       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
218       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
219       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
220       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
221       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
222       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
223       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
224       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
225
226       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
231       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
232       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
233       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
234
235       // Floating-point to integer conversions.
236       // i64 conversions are done via library routines even when generating VFP
237       // instructions, so use the same ones.
238       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
239       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
240       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
241       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
242
243       // Conversions between floating types.
244       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
245       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
246
247       // Integer to floating-point conversions.
248       // i64 conversions are done via library routines even when generating VFP
249       // instructions, so use the same ones.
250       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
251       // e.g., __floatunsidf vs. __floatunssidfvfp.
252       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
253       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
254       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
255       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
256     }
257   }
258
259   // These libcalls are not available in 32-bit.
260   setLibcallName(RTLIB::SHL_I128, 0);
261   setLibcallName(RTLIB::SRL_I128, 0);
262   setLibcallName(RTLIB::SRA_I128, 0);
263
264   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
265     // Double-precision floating-point arithmetic helper functions
266     // RTABI chapter 4.1.2, Table 2
267     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
268     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
269     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
270     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
271     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
273     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
274     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
275
276     // Double-precision floating-point comparison helper functions
277     // RTABI chapter 4.1.2, Table 3
278     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
279     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
280     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
281     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
282     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
283     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
285     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
286     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
287     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
288     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
289     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
290     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
291     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
292     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
293     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
294     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
301     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
302
303     // Single-precision floating-point arithmetic helper functions
304     // RTABI chapter 4.1.2, Table 4
305     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
306     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
307     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
308     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
309     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
311     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
312     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
313
314     // Single-precision floating-point comparison helper functions
315     // RTABI chapter 4.1.2, Table 5
316     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
317     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
318     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
319     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
320     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
321     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
323     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
324     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
325     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
326     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
327     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
328     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
329     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
330     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
331     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
332     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
338     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
339     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
340
341     // Floating-point to integer conversions.
342     // RTABI chapter 4.1.2, Table 6
343     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
344     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
345     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
346     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
347     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
348     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
349     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
350     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
351     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
358     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
359
360     // Conversions between floating types.
361     // RTABI chapter 4.1.2, Table 7
362     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
363     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
364     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
365     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
366
367     // Integer to floating-point conversions.
368     // RTABI chapter 4.1.2, Table 8
369     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
370     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
371     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
372     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
373     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
374     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
375     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
376     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
377     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
385
386     // Long long helper functions
387     // RTABI chapter 4.2, Table 9
388     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
389     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
390     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
391     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
392     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
398
399     // Integer division functions
400     // RTABI chapter 4.3.1
401     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
402     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
403     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
404     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
405     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
406     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
407     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
408     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
409     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
415     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
416     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
417
418     // Memory operations
419     // RTABI chapter 4.3.4
420     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
421     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
422     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
423     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
424     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
425     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
426   }
427
428   // Use divmod compiler-rt calls for iOS 5.0 and later.
429   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
430       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
431     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
432     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
433   }
434
435   if (Subtarget->isThumb1Only())
436     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
437   else
438     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
439   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
440       !Subtarget->isThumb1Only()) {
441     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
442     if (!Subtarget->isFPOnlySP())
443       addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
444
445     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
446   }
447
448   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
450     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
452       setTruncStoreAction((MVT::SimpleValueType)VT,
453                           (MVT::SimpleValueType)InnerVT, Expand);
454     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
455     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
456     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
457   }
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510     
511     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setTargetDAGCombine(ISD::INTRINSIC_VOID);
545     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
546     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
547     setTargetDAGCombine(ISD::SHL);
548     setTargetDAGCombine(ISD::SRL);
549     setTargetDAGCombine(ISD::SRA);
550     setTargetDAGCombine(ISD::SIGN_EXTEND);
551     setTargetDAGCombine(ISD::ZERO_EXTEND);
552     setTargetDAGCombine(ISD::ANY_EXTEND);
553     setTargetDAGCombine(ISD::SELECT_CC);
554     setTargetDAGCombine(ISD::BUILD_VECTOR);
555     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
556     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
557     setTargetDAGCombine(ISD::STORE);
558     setTargetDAGCombine(ISD::FP_TO_SINT);
559     setTargetDAGCombine(ISD::FP_TO_UINT);
560     setTargetDAGCombine(ISD::FDIV);
561
562     // It is legal to extload from v4i8 to v4i16 or v4i32.
563     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
564                   MVT::v4i16, MVT::v2i16,
565                   MVT::v2i32};
566     for (unsigned i = 0; i < 6; ++i) {
567       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
568       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
569       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
570     }
571   }
572
573   computeRegisterProperties();
574
575   // ARM does not have f32 extending load.
576   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
577
578   // ARM does not have i1 sign extending load.
579   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
580
581   // ARM supports all 4 flavors of integer indexed load / store.
582   if (!Subtarget->isThumb1Only()) {
583     for (unsigned im = (unsigned)ISD::PRE_INC;
584          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
585       setIndexedLoadAction(im,  MVT::i1,  Legal);
586       setIndexedLoadAction(im,  MVT::i8,  Legal);
587       setIndexedLoadAction(im,  MVT::i16, Legal);
588       setIndexedLoadAction(im,  MVT::i32, Legal);
589       setIndexedStoreAction(im, MVT::i1,  Legal);
590       setIndexedStoreAction(im, MVT::i8,  Legal);
591       setIndexedStoreAction(im, MVT::i16, Legal);
592       setIndexedStoreAction(im, MVT::i32, Legal);
593     }
594   }
595
596   // i64 operation support.
597   setOperationAction(ISD::MUL,     MVT::i64, Expand);
598   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
599   if (Subtarget->isThumb1Only()) {
600     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
601     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
602   }
603   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
604       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
605     setOperationAction(ISD::MULHS, MVT::i32, Expand);
606
607   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
608   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
609   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
610   setOperationAction(ISD::SRL,       MVT::i64, Custom);
611   setOperationAction(ISD::SRA,       MVT::i64, Custom);
612
613   if (!Subtarget->isThumb1Only()) {
614     // FIXME: We should do this for Thumb1 as well.
615     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
616     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
617     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
618     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
619   }
620
621   // ARM does not have ROTL.
622   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
623   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
624   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
625   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
626     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
627
628   // These just redirect to CTTZ and CTLZ on ARM.
629   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
630   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
631
632   // Only ARMv6 has BSWAP.
633   if (!Subtarget->hasV6Ops())
634     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
635
636   // These are expanded into libcalls.
637   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
638     // v7M has a hardware divider
639     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
640     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
641   }
642   setOperationAction(ISD::SREM,  MVT::i32, Expand);
643   setOperationAction(ISD::UREM,  MVT::i32, Expand);
644   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
645   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
646
647   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
648   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
649   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
650   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
651   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
652
653   setOperationAction(ISD::TRAP, MVT::Other, Legal);
654
655   // Use the default implementation.
656   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
657   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
658   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
659   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
660   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
661   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
662
663   if (!Subtarget->isTargetDarwin()) {
664     // Non-Darwin platforms may return values in these registers via the
665     // personality function.
666     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
667     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
668     setExceptionPointerRegister(ARM::R0);
669     setExceptionSelectorRegister(ARM::R1);
670   }
671
672   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
673   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
674   // the default expansion.
675   // FIXME: This should be checking for v6k, not just v6.
676   if (Subtarget->hasDataBarrier() ||
677       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
678     // membarrier needs custom lowering; the rest are legal and handled
679     // normally.
680     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
681     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
682     // Custom lowering for 64-bit ops
683     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
684     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
685     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
686     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
690     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
691     setInsertFencesForAtomic(true);
692   } else {
693     // Set them all for expansion, which will force libcalls.
694     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
695     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
696     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
697     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
698     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
708     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
709     // Unordered/Monotonic case.
710     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
711     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
712     // Since the libcalls include locking, fold in the fences
713     setShouldFoldAtomicFences(true);
714   }
715
716   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
717
718   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
719   if (!Subtarget->hasV6Ops()) {
720     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
721     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
722   }
723   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
724
725   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
726       !Subtarget->isThumb1Only()) {
727     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
728     // iff target supports vfp2.
729     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
730     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
731   }
732
733   // We want to custom lower some of our intrinsics.
734   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
735   if (Subtarget->isTargetDarwin()) {
736     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
737     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
738     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
739   }
740
741   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
742   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
743   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
744   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
745   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
746   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
747   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
748   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
749   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
750
751   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
752   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
753   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
754   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
755   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
756
757   // We don't support sin/cos/fmod/copysign/pow
758   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
759   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
760   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
761   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
762   setOperationAction(ISD::FREM,      MVT::f64, Expand);
763   setOperationAction(ISD::FREM,      MVT::f32, Expand);
764   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
765       !Subtarget->isThumb1Only()) {
766     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
767     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
768   }
769   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
770   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
771
772   setOperationAction(ISD::FMA, MVT::f64, Expand);
773   setOperationAction(ISD::FMA, MVT::f32, Expand);
774
775   // Various VFP goodness
776   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
777     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
778     if (Subtarget->hasVFP2()) {
779       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
780       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
781       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
782       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
783     }
784     // Special handling for half-precision FP.
785     if (!Subtarget->hasFP16()) {
786       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
787       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
788     }
789   }
790
791   // We have target-specific dag combine patterns for the following nodes:
792   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
793   setTargetDAGCombine(ISD::ADD);
794   setTargetDAGCombine(ISD::SUB);
795   setTargetDAGCombine(ISD::MUL);
796
797   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
798     setTargetDAGCombine(ISD::AND);
799     setTargetDAGCombine(ISD::OR);
800     setTargetDAGCombine(ISD::XOR);
801   }
802
803   if (Subtarget->hasV6Ops())
804     setTargetDAGCombine(ISD::SRL);
805
806   setStackPointerRegisterToSaveRestore(ARM::SP);
807
808   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
809       !Subtarget->hasVFP2())
810     setSchedulingPreference(Sched::RegPressure);
811   else
812     setSchedulingPreference(Sched::Hybrid);
813
814   //// temporary - rewrite interface to use type
815   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
816   maxStoresPerMemset = 16;
817   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
818
819   // On ARM arguments smaller than 4 bytes are extended, so all arguments
820   // are at least 4 bytes aligned.
821   setMinStackArgumentAlignment(4);
822
823   benefitFromCodePlacementOpt = true;
824
825   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
826 }
827
828 // FIXME: It might make sense to define the representative register class as the
829 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
830 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
831 // SPR's representative would be DPR_VFP2. This should work well if register
832 // pressure tracking were modified such that a register use would increment the
833 // pressure of the register class's representative and all of it's super
834 // classes' representatives transitively. We have not implemented this because
835 // of the difficulty prior to coalescing of modeling operand register classes
836 // due to the common occurrence of cross class copies and subregister insertions
837 // and extractions.
838 std::pair<const TargetRegisterClass*, uint8_t>
839 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
840   const TargetRegisterClass *RRC = 0;
841   uint8_t Cost = 1;
842   switch (VT.getSimpleVT().SimpleTy) {
843   default:
844     return TargetLowering::findRepresentativeClass(VT);
845   // Use DPR as representative register class for all floating point
846   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
847   // the cost is 1 for both f32 and f64.
848   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
849   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
850     RRC = ARM::DPRRegisterClass;
851     // When NEON is used for SP, only half of the register file is available
852     // because operations that define both SP and DP results will be constrained
853     // to the VFP2 class (D0-D15). We currently model this constraint prior to
854     // coalescing by double-counting the SP regs. See the FIXME above.
855     if (Subtarget->useNEONForSinglePrecisionFP())
856       Cost = 2;
857     break;
858   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
859   case MVT::v4f32: case MVT::v2f64:
860     RRC = ARM::DPRRegisterClass;
861     Cost = 2;
862     break;
863   case MVT::v4i64:
864     RRC = ARM::DPRRegisterClass;
865     Cost = 4;
866     break;
867   case MVT::v8i64:
868     RRC = ARM::DPRRegisterClass;
869     Cost = 8;
870     break;
871   }
872   return std::make_pair(RRC, Cost);
873 }
874
875 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
876   switch (Opcode) {
877   default: return 0;
878   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
879   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
880   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
881   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
882   case ARMISD::CALL:          return "ARMISD::CALL";
883   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
884   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
885   case ARMISD::tCALL:         return "ARMISD::tCALL";
886   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
887   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
888   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
889   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
890   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
891   case ARMISD::CMP:           return "ARMISD::CMP";
892   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
893   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
894   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
895   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
896   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
897
898   case ARMISD::CMOV:          return "ARMISD::CMOV";
899   case ARMISD::CAND:          return "ARMISD::CAND";
900   case ARMISD::COR:           return "ARMISD::COR";
901   case ARMISD::CXOR:          return "ARMISD::CXOR";
902
903   case ARMISD::RBIT:          return "ARMISD::RBIT";
904
905   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
906   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
907   case ARMISD::SITOF:         return "ARMISD::SITOF";
908   case ARMISD::UITOF:         return "ARMISD::UITOF";
909
910   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
911   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
912   case ARMISD::RRX:           return "ARMISD::RRX";
913
914   case ARMISD::ADDC:          return "ARMISD::ADDC";
915   case ARMISD::ADDE:          return "ARMISD::ADDE";
916   case ARMISD::SUBC:          return "ARMISD::SUBC";
917   case ARMISD::SUBE:          return "ARMISD::SUBE";
918
919   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
920   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
921
922   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
923   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
924
925   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
926
927   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
928
929   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
930
931   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
932   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
933
934   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
935
936   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
937   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
938   case ARMISD::VCGE:          return "ARMISD::VCGE";
939   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
940   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
941   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
942   case ARMISD::VCGT:          return "ARMISD::VCGT";
943   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
944   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
945   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
946   case ARMISD::VTST:          return "ARMISD::VTST";
947
948   case ARMISD::VSHL:          return "ARMISD::VSHL";
949   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
950   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
951   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
952   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
953   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
954   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
955   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
956   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
957   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
958   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
959   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
960   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
961   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
962   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
963   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
964   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
965   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
966   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
967   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
968   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
969   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
970   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
971   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
972   case ARMISD::VDUP:          return "ARMISD::VDUP";
973   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
974   case ARMISD::VEXT:          return "ARMISD::VEXT";
975   case ARMISD::VREV64:        return "ARMISD::VREV64";
976   case ARMISD::VREV32:        return "ARMISD::VREV32";
977   case ARMISD::VREV16:        return "ARMISD::VREV16";
978   case ARMISD::VZIP:          return "ARMISD::VZIP";
979   case ARMISD::VUZP:          return "ARMISD::VUZP";
980   case ARMISD::VTRN:          return "ARMISD::VTRN";
981   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
982   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
983   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
984   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
985   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
986   case ARMISD::FMAX:          return "ARMISD::FMAX";
987   case ARMISD::FMIN:          return "ARMISD::FMIN";
988   case ARMISD::BFI:           return "ARMISD::BFI";
989   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
990   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
991   case ARMISD::VBSL:          return "ARMISD::VBSL";
992   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
993   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
994   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
995   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
996   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
997   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
998   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
999   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1000   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1001   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1002   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1003   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1004   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1005   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1006   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1007   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1008   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1009   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1010   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1011   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1012   }
1013 }
1014
1015 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1016   if (!VT.isVector()) return getPointerTy();
1017   return VT.changeVectorElementTypeToInteger();
1018 }
1019
1020 /// getRegClassFor - Return the register class that should be used for the
1021 /// specified value type.
1022 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1023   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1024   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1025   // load / store 4 to 8 consecutive D registers.
1026   if (Subtarget->hasNEON()) {
1027     if (VT == MVT::v4i64)
1028       return ARM::QQPRRegisterClass;
1029     else if (VT == MVT::v8i64)
1030       return ARM::QQQQPRRegisterClass;
1031   }
1032   return TargetLowering::getRegClassFor(VT);
1033 }
1034
1035 // Create a fast isel object.
1036 FastISel *
1037 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1038   return ARM::createFastISel(funcInfo);
1039 }
1040
1041 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1042 /// be used for loads / stores from the global.
1043 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1044   return (Subtarget->isThumb1Only() ? 127 : 4095);
1045 }
1046
1047 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1048   unsigned NumVals = N->getNumValues();
1049   if (!NumVals)
1050     return Sched::RegPressure;
1051
1052   for (unsigned i = 0; i != NumVals; ++i) {
1053     EVT VT = N->getValueType(i);
1054     if (VT == MVT::Glue || VT == MVT::Other)
1055       continue;
1056     if (VT.isFloatingPoint() || VT.isVector())
1057       return Sched::ILP;
1058   }
1059
1060   if (!N->isMachineOpcode())
1061     return Sched::RegPressure;
1062
1063   // Load are scheduled for latency even if there instruction itinerary
1064   // is not available.
1065   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1066   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1067
1068   if (MCID.getNumDefs() == 0)
1069     return Sched::RegPressure;
1070   if (!Itins->isEmpty() &&
1071       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1072     return Sched::ILP;
1073
1074   return Sched::RegPressure;
1075 }
1076
1077 //===----------------------------------------------------------------------===//
1078 // Lowering Code
1079 //===----------------------------------------------------------------------===//
1080
1081 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1082 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1083   switch (CC) {
1084   default: llvm_unreachable("Unknown condition code!");
1085   case ISD::SETNE:  return ARMCC::NE;
1086   case ISD::SETEQ:  return ARMCC::EQ;
1087   case ISD::SETGT:  return ARMCC::GT;
1088   case ISD::SETGE:  return ARMCC::GE;
1089   case ISD::SETLT:  return ARMCC::LT;
1090   case ISD::SETLE:  return ARMCC::LE;
1091   case ISD::SETUGT: return ARMCC::HI;
1092   case ISD::SETUGE: return ARMCC::HS;
1093   case ISD::SETULT: return ARMCC::LO;
1094   case ISD::SETULE: return ARMCC::LS;
1095   }
1096 }
1097
1098 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1099 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1100                         ARMCC::CondCodes &CondCode2) {
1101   CondCode2 = ARMCC::AL;
1102   switch (CC) {
1103   default: llvm_unreachable("Unknown FP condition!");
1104   case ISD::SETEQ:
1105   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1106   case ISD::SETGT:
1107   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1108   case ISD::SETGE:
1109   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1110   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1111   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1112   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1113   case ISD::SETO:   CondCode = ARMCC::VC; break;
1114   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1115   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1116   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1117   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1118   case ISD::SETLT:
1119   case ISD::SETULT: CondCode = ARMCC::LT; break;
1120   case ISD::SETLE:
1121   case ISD::SETULE: CondCode = ARMCC::LE; break;
1122   case ISD::SETNE:
1123   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1124   }
1125 }
1126
1127 //===----------------------------------------------------------------------===//
1128 //                      Calling Convention Implementation
1129 //===----------------------------------------------------------------------===//
1130
1131 #include "ARMGenCallingConv.inc"
1132
1133 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1134 /// given CallingConvention value.
1135 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1136                                                  bool Return,
1137                                                  bool isVarArg) const {
1138   switch (CC) {
1139   default:
1140     llvm_unreachable("Unsupported calling convention");
1141   case CallingConv::Fast:
1142     if (Subtarget->hasVFP2() && !isVarArg) {
1143       if (!Subtarget->isAAPCS_ABI())
1144         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1145       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1146       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1147     }
1148     // Fallthrough
1149   case CallingConv::C: {
1150     // Use target triple & subtarget features to do actual dispatch.
1151     if (!Subtarget->isAAPCS_ABI())
1152       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1153     else if (Subtarget->hasVFP2() &&
1154              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1155              !isVarArg)
1156       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1157     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1158   }
1159   case CallingConv::ARM_AAPCS_VFP:
1160     if (!isVarArg)
1161       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1162     // Fallthrough
1163   case CallingConv::ARM_AAPCS:
1164     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1165   case CallingConv::ARM_APCS:
1166     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1167   }
1168 }
1169
1170 /// LowerCallResult - Lower the result values of a call into the
1171 /// appropriate copies out of appropriate physical registers.
1172 SDValue
1173 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1174                                    CallingConv::ID CallConv, bool isVarArg,
1175                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1176                                    DebugLoc dl, SelectionDAG &DAG,
1177                                    SmallVectorImpl<SDValue> &InVals) const {
1178
1179   // Assign locations to each value returned by this call.
1180   SmallVector<CCValAssign, 16> RVLocs;
1181   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1182                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1183   CCInfo.AnalyzeCallResult(Ins,
1184                            CCAssignFnForNode(CallConv, /* Return*/ true,
1185                                              isVarArg));
1186
1187   // Copy all of the result registers out of their specified physreg.
1188   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1189     CCValAssign VA = RVLocs[i];
1190
1191     SDValue Val;
1192     if (VA.needsCustom()) {
1193       // Handle f64 or half of a v2f64.
1194       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1195                                       InFlag);
1196       Chain = Lo.getValue(1);
1197       InFlag = Lo.getValue(2);
1198       VA = RVLocs[++i]; // skip ahead to next loc
1199       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1200                                       InFlag);
1201       Chain = Hi.getValue(1);
1202       InFlag = Hi.getValue(2);
1203       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1204
1205       if (VA.getLocVT() == MVT::v2f64) {
1206         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1207         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1208                           DAG.getConstant(0, MVT::i32));
1209
1210         VA = RVLocs[++i]; // skip ahead to next loc
1211         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1212         Chain = Lo.getValue(1);
1213         InFlag = Lo.getValue(2);
1214         VA = RVLocs[++i]; // skip ahead to next loc
1215         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1216         Chain = Hi.getValue(1);
1217         InFlag = Hi.getValue(2);
1218         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1219         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1220                           DAG.getConstant(1, MVT::i32));
1221       }
1222     } else {
1223       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1224                                InFlag);
1225       Chain = Val.getValue(1);
1226       InFlag = Val.getValue(2);
1227     }
1228
1229     switch (VA.getLocInfo()) {
1230     default: llvm_unreachable("Unknown loc info!");
1231     case CCValAssign::Full: break;
1232     case CCValAssign::BCvt:
1233       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1234       break;
1235     }
1236
1237     InVals.push_back(Val);
1238   }
1239
1240   return Chain;
1241 }
1242
1243 /// LowerMemOpCallTo - Store the argument to the stack.
1244 SDValue
1245 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1246                                     SDValue StackPtr, SDValue Arg,
1247                                     DebugLoc dl, SelectionDAG &DAG,
1248                                     const CCValAssign &VA,
1249                                     ISD::ArgFlagsTy Flags) const {
1250   unsigned LocMemOffset = VA.getLocMemOffset();
1251   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1252   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1253   return DAG.getStore(Chain, dl, Arg, PtrOff,
1254                       MachinePointerInfo::getStack(LocMemOffset),
1255                       false, false, 0);
1256 }
1257
1258 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1259                                          SDValue Chain, SDValue &Arg,
1260                                          RegsToPassVector &RegsToPass,
1261                                          CCValAssign &VA, CCValAssign &NextVA,
1262                                          SDValue &StackPtr,
1263                                          SmallVector<SDValue, 8> &MemOpChains,
1264                                          ISD::ArgFlagsTy Flags) const {
1265
1266   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1267                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1268   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1269
1270   if (NextVA.isRegLoc())
1271     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1272   else {
1273     assert(NextVA.isMemLoc());
1274     if (StackPtr.getNode() == 0)
1275       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1276
1277     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1278                                            dl, DAG, NextVA,
1279                                            Flags));
1280   }
1281 }
1282
1283 /// LowerCall - Lowering a call into a callseq_start <-
1284 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1285 /// nodes.
1286 SDValue
1287 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1288                              CallingConv::ID CallConv, bool isVarArg,
1289                              bool &isTailCall,
1290                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1291                              const SmallVectorImpl<SDValue> &OutVals,
1292                              const SmallVectorImpl<ISD::InputArg> &Ins,
1293                              DebugLoc dl, SelectionDAG &DAG,
1294                              SmallVectorImpl<SDValue> &InVals) const {
1295   MachineFunction &MF = DAG.getMachineFunction();
1296   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1297   bool IsSibCall = false;
1298   // Disable tail calls if they're not supported.
1299   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1300     isTailCall = false;
1301   if (isTailCall) {
1302     // Check if it's really possible to do a tail call.
1303     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1304                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1305                                                    Outs, OutVals, Ins, DAG);
1306     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1307     // detected sibcalls.
1308     if (isTailCall) {
1309       ++NumTailCalls;
1310       IsSibCall = true;
1311     }
1312   }
1313
1314   // Analyze operands of the call, assigning locations to each operand.
1315   SmallVector<CCValAssign, 16> ArgLocs;
1316   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1317                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1318   CCInfo.AnalyzeCallOperands(Outs,
1319                              CCAssignFnForNode(CallConv, /* Return*/ false,
1320                                                isVarArg));
1321
1322   // Get a count of how many bytes are to be pushed on the stack.
1323   unsigned NumBytes = CCInfo.getNextStackOffset();
1324
1325   // For tail calls, memory operands are available in our caller's stack.
1326   if (IsSibCall)
1327     NumBytes = 0;
1328
1329   // Adjust the stack pointer for the new arguments...
1330   // These operations are automatically eliminated by the prolog/epilog pass
1331   if (!IsSibCall)
1332     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1333
1334   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1335
1336   RegsToPassVector RegsToPass;
1337   SmallVector<SDValue, 8> MemOpChains;
1338
1339   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1340   // of tail call optimization, arguments are handled later.
1341   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1342        i != e;
1343        ++i, ++realArgIdx) {
1344     CCValAssign &VA = ArgLocs[i];
1345     SDValue Arg = OutVals[realArgIdx];
1346     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1347     bool isByVal = Flags.isByVal();
1348
1349     // Promote the value if needed.
1350     switch (VA.getLocInfo()) {
1351     default: llvm_unreachable("Unknown loc info!");
1352     case CCValAssign::Full: break;
1353     case CCValAssign::SExt:
1354       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1355       break;
1356     case CCValAssign::ZExt:
1357       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1358       break;
1359     case CCValAssign::AExt:
1360       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1361       break;
1362     case CCValAssign::BCvt:
1363       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1364       break;
1365     }
1366
1367     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1368     if (VA.needsCustom()) {
1369       if (VA.getLocVT() == MVT::v2f64) {
1370         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1371                                   DAG.getConstant(0, MVT::i32));
1372         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1373                                   DAG.getConstant(1, MVT::i32));
1374
1375         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1376                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1377
1378         VA = ArgLocs[++i]; // skip ahead to next loc
1379         if (VA.isRegLoc()) {
1380           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1381                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1382         } else {
1383           assert(VA.isMemLoc());
1384
1385           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1386                                                  dl, DAG, VA, Flags));
1387         }
1388       } else {
1389         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1390                          StackPtr, MemOpChains, Flags);
1391       }
1392     } else if (VA.isRegLoc()) {
1393       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1394     } else if (isByVal) {
1395       assert(VA.isMemLoc());
1396       unsigned offset = 0;
1397
1398       // True if this byval aggregate will be split between registers
1399       // and memory.
1400       if (CCInfo.isFirstByValRegValid()) {
1401         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1402         unsigned int i, j;
1403         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1404           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1405           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1406           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1407                                      MachinePointerInfo(),
1408                                      false, false, false, 0);
1409           MemOpChains.push_back(Load.getValue(1));
1410           RegsToPass.push_back(std::make_pair(j, Load));
1411         }
1412         offset = ARM::R4 - CCInfo.getFirstByValReg();
1413         CCInfo.clearFirstByValReg();
1414       }
1415
1416       unsigned LocMemOffset = VA.getLocMemOffset();
1417       SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418       SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1419                                 StkPtrOff);
1420       SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1421       SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1422       SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1423                                          MVT::i32);
1424       MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1425                                           Flags.getByValAlign(),
1426                                           /*isVolatile=*/false,
1427                                           /*AlwaysInline=*/false,
1428                                           MachinePointerInfo(0),
1429                                           MachinePointerInfo(0)));
1430
1431     } else if (!IsSibCall) {
1432       assert(VA.isMemLoc());
1433
1434       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1435                                              dl, DAG, VA, Flags));
1436     }
1437   }
1438
1439   if (!MemOpChains.empty())
1440     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1441                         &MemOpChains[0], MemOpChains.size());
1442
1443   // Build a sequence of copy-to-reg nodes chained together with token chain
1444   // and flag operands which copy the outgoing args into the appropriate regs.
1445   SDValue InFlag;
1446   // Tail call byval lowering might overwrite argument registers so in case of
1447   // tail call optimization the copies to registers are lowered later.
1448   if (!isTailCall)
1449     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1450       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1451                                RegsToPass[i].second, InFlag);
1452       InFlag = Chain.getValue(1);
1453     }
1454
1455   // For tail calls lower the arguments to the 'real' stack slot.
1456   if (isTailCall) {
1457     // Force all the incoming stack arguments to be loaded from the stack
1458     // before any new outgoing arguments are stored to the stack, because the
1459     // outgoing stack slots may alias the incoming argument stack slots, and
1460     // the alias isn't otherwise explicit. This is slightly more conservative
1461     // than necessary, because it means that each store effectively depends
1462     // on every argument instead of just those arguments it would clobber.
1463
1464     // Do not flag preceding copytoreg stuff together with the following stuff.
1465     InFlag = SDValue();
1466     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1467       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1468                                RegsToPass[i].second, InFlag);
1469       InFlag = Chain.getValue(1);
1470     }
1471     InFlag =SDValue();
1472   }
1473
1474   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1475   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1476   // node so that legalize doesn't hack it.
1477   bool isDirect = false;
1478   bool isARMFunc = false;
1479   bool isLocalARMFunc = false;
1480   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1481
1482   if (EnableARMLongCalls) {
1483     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1484             && "long-calls with non-static relocation model!");
1485     // Handle a global address or an external symbol. If it's not one of
1486     // those, the target's already in a register, so we don't need to do
1487     // anything extra.
1488     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1489       const GlobalValue *GV = G->getGlobal();
1490       // Create a constant pool entry for the callee address
1491       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1492       ARMConstantPoolValue *CPV =
1493         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1494
1495       // Get the address of the callee into a register
1496       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1497       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1498       Callee = DAG.getLoad(getPointerTy(), dl,
1499                            DAG.getEntryNode(), CPAddr,
1500                            MachinePointerInfo::getConstantPool(),
1501                            false, false, false, 0);
1502     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1503       const char *Sym = S->getSymbol();
1504
1505       // Create a constant pool entry for the callee address
1506       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1507       ARMConstantPoolValue *CPV =
1508         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1509                                       ARMPCLabelIndex, 0);
1510       // Get the address of the callee into a register
1511       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1512       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1513       Callee = DAG.getLoad(getPointerTy(), dl,
1514                            DAG.getEntryNode(), CPAddr,
1515                            MachinePointerInfo::getConstantPool(),
1516                            false, false, false, 0);
1517     }
1518   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1519     const GlobalValue *GV = G->getGlobal();
1520     isDirect = true;
1521     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1522     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1523                    getTargetMachine().getRelocationModel() != Reloc::Static;
1524     isARMFunc = !Subtarget->isThumb() || isStub;
1525     // ARM call to a local ARM function is predicable.
1526     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1527     // tBX takes a register source operand.
1528     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1529       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1530       ARMConstantPoolValue *CPV =
1531         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1532       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1533       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1534       Callee = DAG.getLoad(getPointerTy(), dl,
1535                            DAG.getEntryNode(), CPAddr,
1536                            MachinePointerInfo::getConstantPool(),
1537                            false, false, false, 0);
1538       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1539       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1540                            getPointerTy(), Callee, PICLabel);
1541     } else {
1542       // On ELF targets for PIC code, direct calls should go through the PLT
1543       unsigned OpFlags = 0;
1544       if (Subtarget->isTargetELF() &&
1545                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1546         OpFlags = ARMII::MO_PLT;
1547       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1548     }
1549   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1550     isDirect = true;
1551     bool isStub = Subtarget->isTargetDarwin() &&
1552                   getTargetMachine().getRelocationModel() != Reloc::Static;
1553     isARMFunc = !Subtarget->isThumb() || isStub;
1554     // tBX takes a register source operand.
1555     const char *Sym = S->getSymbol();
1556     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1557       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1558       ARMConstantPoolValue *CPV =
1559         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1560                                       ARMPCLabelIndex, 4);
1561       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1562       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1563       Callee = DAG.getLoad(getPointerTy(), dl,
1564                            DAG.getEntryNode(), CPAddr,
1565                            MachinePointerInfo::getConstantPool(),
1566                            false, false, false, 0);
1567       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1568       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1569                            getPointerTy(), Callee, PICLabel);
1570     } else {
1571       unsigned OpFlags = 0;
1572       // On ELF targets for PIC code, direct calls should go through the PLT
1573       if (Subtarget->isTargetELF() &&
1574                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1575         OpFlags = ARMII::MO_PLT;
1576       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1577     }
1578   }
1579
1580   // FIXME: handle tail calls differently.
1581   unsigned CallOpc;
1582   if (Subtarget->isThumb()) {
1583     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1584       CallOpc = ARMISD::CALL_NOLINK;
1585     else
1586       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1587   } else {
1588     CallOpc = (isDirect || Subtarget->hasV5TOps())
1589       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1590       : ARMISD::CALL_NOLINK;
1591   }
1592
1593   std::vector<SDValue> Ops;
1594   Ops.push_back(Chain);
1595   Ops.push_back(Callee);
1596
1597   // Add argument registers to the end of the list so that they are known live
1598   // into the call.
1599   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1600     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1601                                   RegsToPass[i].second.getValueType()));
1602
1603   // Add a register mask operand representing the call-preserved registers.
1604   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1605   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1606   assert(Mask && "Missing call preserved mask for calling convention");
1607   Ops.push_back(DAG.getRegisterMask(Mask));
1608
1609   if (InFlag.getNode())
1610     Ops.push_back(InFlag);
1611
1612   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1613   if (isTailCall)
1614     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1615
1616   // Returns a chain and a flag for retval copy to use.
1617   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1618   InFlag = Chain.getValue(1);
1619
1620   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1621                              DAG.getIntPtrConstant(0, true), InFlag);
1622   if (!Ins.empty())
1623     InFlag = Chain.getValue(1);
1624
1625   // Handle result values, copying them out of physregs into vregs that we
1626   // return.
1627   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1628                          dl, DAG, InVals);
1629 }
1630
1631 /// HandleByVal - Every parameter *after* a byval parameter is passed
1632 /// on the stack.  Remember the next parameter register to allocate,
1633 /// and then confiscate the rest of the parameter registers to insure
1634 /// this.
1635 void
1636 llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1637   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1638   assert((State->getCallOrPrologue() == Prologue ||
1639           State->getCallOrPrologue() == Call) &&
1640          "unhandled ParmContext");
1641   if ((!State->isFirstByValRegValid()) &&
1642       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1643     State->setFirstByValReg(reg);
1644     // At a call site, a byval parameter that is split between
1645     // registers and memory needs its size truncated here.  In a
1646     // function prologue, such byval parameters are reassembled in
1647     // memory, and are not truncated.
1648     if (State->getCallOrPrologue() == Call) {
1649       unsigned excess = 4 * (ARM::R4 - reg);
1650       assert(size >= excess && "expected larger existing stack allocation");
1651       size -= excess;
1652     }
1653   }
1654   // Confiscate any remaining parameter registers to preclude their
1655   // assignment to subsequent parameters.
1656   while (State->AllocateReg(GPRArgRegs, 4))
1657     ;
1658 }
1659
1660 /// MatchingStackOffset - Return true if the given stack call argument is
1661 /// already available in the same position (relatively) of the caller's
1662 /// incoming argument stack.
1663 static
1664 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1665                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1666                          const ARMInstrInfo *TII) {
1667   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1668   int FI = INT_MAX;
1669   if (Arg.getOpcode() == ISD::CopyFromReg) {
1670     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1671     if (!TargetRegisterInfo::isVirtualRegister(VR))
1672       return false;
1673     MachineInstr *Def = MRI->getVRegDef(VR);
1674     if (!Def)
1675       return false;
1676     if (!Flags.isByVal()) {
1677       if (!TII->isLoadFromStackSlot(Def, FI))
1678         return false;
1679     } else {
1680       return false;
1681     }
1682   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1683     if (Flags.isByVal())
1684       // ByVal argument is passed in as a pointer but it's now being
1685       // dereferenced. e.g.
1686       // define @foo(%struct.X* %A) {
1687       //   tail call @bar(%struct.X* byval %A)
1688       // }
1689       return false;
1690     SDValue Ptr = Ld->getBasePtr();
1691     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1692     if (!FINode)
1693       return false;
1694     FI = FINode->getIndex();
1695   } else
1696     return false;
1697
1698   assert(FI != INT_MAX);
1699   if (!MFI->isFixedObjectIndex(FI))
1700     return false;
1701   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1702 }
1703
1704 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1705 /// for tail call optimization. Targets which want to do tail call
1706 /// optimization should implement this function.
1707 bool
1708 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1709                                                      CallingConv::ID CalleeCC,
1710                                                      bool isVarArg,
1711                                                      bool isCalleeStructRet,
1712                                                      bool isCallerStructRet,
1713                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1714                                     const SmallVectorImpl<SDValue> &OutVals,
1715                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1716                                                      SelectionDAG& DAG) const {
1717   const Function *CallerF = DAG.getMachineFunction().getFunction();
1718   CallingConv::ID CallerCC = CallerF->getCallingConv();
1719   bool CCMatch = CallerCC == CalleeCC;
1720
1721   // Look for obvious safe cases to perform tail call optimization that do not
1722   // require ABI changes. This is what gcc calls sibcall.
1723
1724   // Do not sibcall optimize vararg calls unless the call site is not passing
1725   // any arguments.
1726   if (isVarArg && !Outs.empty())
1727     return false;
1728
1729   // Also avoid sibcall optimization if either caller or callee uses struct
1730   // return semantics.
1731   if (isCalleeStructRet || isCallerStructRet)
1732     return false;
1733
1734   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1735   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1736   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1737   // support in the assembler and linker to be used. This would need to be
1738   // fixed to fully support tail calls in Thumb1.
1739   //
1740   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1741   // LR.  This means if we need to reload LR, it takes an extra instructions,
1742   // which outweighs the value of the tail call; but here we don't know yet
1743   // whether LR is going to be used.  Probably the right approach is to
1744   // generate the tail call here and turn it back into CALL/RET in
1745   // emitEpilogue if LR is used.
1746
1747   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1748   // but we need to make sure there are enough registers; the only valid
1749   // registers are the 4 used for parameters.  We don't currently do this
1750   // case.
1751   if (Subtarget->isThumb1Only())
1752     return false;
1753
1754   // If the calling conventions do not match, then we'd better make sure the
1755   // results are returned in the same way as what the caller expects.
1756   if (!CCMatch) {
1757     SmallVector<CCValAssign, 16> RVLocs1;
1758     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1759                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1760     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1761
1762     SmallVector<CCValAssign, 16> RVLocs2;
1763     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1764                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1765     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1766
1767     if (RVLocs1.size() != RVLocs2.size())
1768       return false;
1769     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1770       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1771         return false;
1772       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1773         return false;
1774       if (RVLocs1[i].isRegLoc()) {
1775         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1776           return false;
1777       } else {
1778         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1779           return false;
1780       }
1781     }
1782   }
1783
1784   // If the callee takes no arguments then go on to check the results of the
1785   // call.
1786   if (!Outs.empty()) {
1787     // Check if stack adjustment is needed. For now, do not do this if any
1788     // argument is passed on the stack.
1789     SmallVector<CCValAssign, 16> ArgLocs;
1790     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1791                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1792     CCInfo.AnalyzeCallOperands(Outs,
1793                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1794     if (CCInfo.getNextStackOffset()) {
1795       MachineFunction &MF = DAG.getMachineFunction();
1796
1797       // Check if the arguments are already laid out in the right way as
1798       // the caller's fixed stack objects.
1799       MachineFrameInfo *MFI = MF.getFrameInfo();
1800       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1801       const ARMInstrInfo *TII =
1802         ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1803       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1804            i != e;
1805            ++i, ++realArgIdx) {
1806         CCValAssign &VA = ArgLocs[i];
1807         EVT RegVT = VA.getLocVT();
1808         SDValue Arg = OutVals[realArgIdx];
1809         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1810         if (VA.getLocInfo() == CCValAssign::Indirect)
1811           return false;
1812         if (VA.needsCustom()) {
1813           // f64 and vector types are split into multiple registers or
1814           // register/stack-slot combinations.  The types will not match
1815           // the registers; give up on memory f64 refs until we figure
1816           // out what to do about this.
1817           if (!VA.isRegLoc())
1818             return false;
1819           if (!ArgLocs[++i].isRegLoc())
1820             return false;
1821           if (RegVT == MVT::v2f64) {
1822             if (!ArgLocs[++i].isRegLoc())
1823               return false;
1824             if (!ArgLocs[++i].isRegLoc())
1825               return false;
1826           }
1827         } else if (!VA.isRegLoc()) {
1828           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1829                                    MFI, MRI, TII))
1830             return false;
1831         }
1832       }
1833     }
1834   }
1835
1836   return true;
1837 }
1838
1839 SDValue
1840 ARMTargetLowering::LowerReturn(SDValue Chain,
1841                                CallingConv::ID CallConv, bool isVarArg,
1842                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1843                                const SmallVectorImpl<SDValue> &OutVals,
1844                                DebugLoc dl, SelectionDAG &DAG) const {
1845
1846   // CCValAssign - represent the assignment of the return value to a location.
1847   SmallVector<CCValAssign, 16> RVLocs;
1848
1849   // CCState - Info about the registers and stack slots.
1850   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1851                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1852
1853   // Analyze outgoing return values.
1854   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1855                                                isVarArg));
1856
1857   // If this is the first return lowered for this function, add
1858   // the regs to the liveout set for the function.
1859   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1860     for (unsigned i = 0; i != RVLocs.size(); ++i)
1861       if (RVLocs[i].isRegLoc())
1862         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1863   }
1864
1865   SDValue Flag;
1866
1867   // Copy the result values into the output registers.
1868   for (unsigned i = 0, realRVLocIdx = 0;
1869        i != RVLocs.size();
1870        ++i, ++realRVLocIdx) {
1871     CCValAssign &VA = RVLocs[i];
1872     assert(VA.isRegLoc() && "Can only return in registers!");
1873
1874     SDValue Arg = OutVals[realRVLocIdx];
1875
1876     switch (VA.getLocInfo()) {
1877     default: llvm_unreachable("Unknown loc info!");
1878     case CCValAssign::Full: break;
1879     case CCValAssign::BCvt:
1880       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1881       break;
1882     }
1883
1884     if (VA.needsCustom()) {
1885       if (VA.getLocVT() == MVT::v2f64) {
1886         // Extract the first half and return it in two registers.
1887         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1888                                    DAG.getConstant(0, MVT::i32));
1889         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1890                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1891
1892         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1893         Flag = Chain.getValue(1);
1894         VA = RVLocs[++i]; // skip ahead to next loc
1895         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1896                                  HalfGPRs.getValue(1), Flag);
1897         Flag = Chain.getValue(1);
1898         VA = RVLocs[++i]; // skip ahead to next loc
1899
1900         // Extract the 2nd half and fall through to handle it as an f64 value.
1901         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1902                           DAG.getConstant(1, MVT::i32));
1903       }
1904       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1905       // available.
1906       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1907                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1908       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1909       Flag = Chain.getValue(1);
1910       VA = RVLocs[++i]; // skip ahead to next loc
1911       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1912                                Flag);
1913     } else
1914       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1915
1916     // Guarantee that all emitted copies are
1917     // stuck together, avoiding something bad.
1918     Flag = Chain.getValue(1);
1919   }
1920
1921   SDValue result;
1922   if (Flag.getNode())
1923     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1924   else // Return Void
1925     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1926
1927   return result;
1928 }
1929
1930 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1931   if (N->getNumValues() != 1)
1932     return false;
1933   if (!N->hasNUsesOfValue(1, 0))
1934     return false;
1935
1936   unsigned NumCopies = 0;
1937   SDNode* Copies[2] = { 0, 0 };
1938   SDNode *Use = *N->use_begin();
1939   if (Use->getOpcode() == ISD::CopyToReg) {
1940     Copies[NumCopies++] = Use;
1941   } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1942     // f64 returned in a pair of GPRs.
1943     for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1944          UI != UE; ++UI) {
1945       if (UI->getOpcode() != ISD::CopyToReg)
1946         return false;
1947       Copies[UI.getUse().getResNo()] = *UI;
1948       ++NumCopies;
1949     }
1950   } else if (Use->getOpcode() == ISD::BITCAST) {
1951     // f32 returned in a single GPR.
1952     if (!Use->hasNUsesOfValue(1, 0))
1953       return false;
1954     Use = *Use->use_begin();
1955     if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1956       return false;
1957     Copies[NumCopies++] = Use;
1958   } else {
1959     return false;
1960   }
1961
1962   if (NumCopies != 1 && NumCopies != 2)
1963     return false;
1964
1965   bool HasRet = false;
1966   for (unsigned i = 0; i < NumCopies; ++i) {
1967     SDNode *Copy = Copies[i];
1968     for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1969          UI != UE; ++UI) {
1970       if (UI->getOpcode() == ISD::CopyToReg) {
1971         SDNode *Use = *UI;
1972         if (Use == Copies[0] || ((NumCopies == 2) && (Use == Copies[1])))
1973           continue;
1974         return false;
1975       }
1976       if (UI->getOpcode() != ARMISD::RET_FLAG)
1977         return false;
1978       HasRet = true;
1979     }
1980   }
1981
1982   return HasRet;
1983 }
1984
1985 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1986   if (!EnableARMTailCalls)
1987     return false;
1988
1989   if (!CI->isTailCall())
1990     return false;
1991
1992   return !Subtarget->isThumb1Only();
1993 }
1994
1995 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1996 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1997 // one of the above mentioned nodes. It has to be wrapped because otherwise
1998 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1999 // be used to form addressing mode. These wrapped nodes will be selected
2000 // into MOVi.
2001 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2002   EVT PtrVT = Op.getValueType();
2003   // FIXME there is no actual debug info here
2004   DebugLoc dl = Op.getDebugLoc();
2005   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2006   SDValue Res;
2007   if (CP->isMachineConstantPoolEntry())
2008     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2009                                     CP->getAlignment());
2010   else
2011     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2012                                     CP->getAlignment());
2013   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2014 }
2015
2016 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2017   return MachineJumpTableInfo::EK_Inline;
2018 }
2019
2020 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2021                                              SelectionDAG &DAG) const {
2022   MachineFunction &MF = DAG.getMachineFunction();
2023   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2024   unsigned ARMPCLabelIndex = 0;
2025   DebugLoc DL = Op.getDebugLoc();
2026   EVT PtrVT = getPointerTy();
2027   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2028   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2029   SDValue CPAddr;
2030   if (RelocM == Reloc::Static) {
2031     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2032   } else {
2033     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2034     ARMPCLabelIndex = AFI->createPICLabelUId();
2035     ARMConstantPoolValue *CPV =
2036       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2037                                       ARMCP::CPBlockAddress, PCAdj);
2038     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2039   }
2040   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2041   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2042                                MachinePointerInfo::getConstantPool(),
2043                                false, false, false, 0);
2044   if (RelocM == Reloc::Static)
2045     return Result;
2046   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2047   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2048 }
2049
2050 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2051 SDValue
2052 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2053                                                  SelectionDAG &DAG) const {
2054   DebugLoc dl = GA->getDebugLoc();
2055   EVT PtrVT = getPointerTy();
2056   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2057   MachineFunction &MF = DAG.getMachineFunction();
2058   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2059   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2060   ARMConstantPoolValue *CPV =
2061     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2062                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2063   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2064   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2065   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2066                          MachinePointerInfo::getConstantPool(),
2067                          false, false, false, 0);
2068   SDValue Chain = Argument.getValue(1);
2069
2070   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2071   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2072
2073   // call __tls_get_addr.
2074   ArgListTy Args;
2075   ArgListEntry Entry;
2076   Entry.Node = Argument;
2077   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2078   Args.push_back(Entry);
2079   // FIXME: is there useful debug info available here?
2080   std::pair<SDValue, SDValue> CallResult =
2081     LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
2082                 false, false, false, false,
2083                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
2084                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2085   return CallResult.first;
2086 }
2087
2088 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2089 // "local exec" model.
2090 SDValue
2091 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2092                                         SelectionDAG &DAG) const {
2093   const GlobalValue *GV = GA->getGlobal();
2094   DebugLoc dl = GA->getDebugLoc();
2095   SDValue Offset;
2096   SDValue Chain = DAG.getEntryNode();
2097   EVT PtrVT = getPointerTy();
2098   // Get the Thread Pointer
2099   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2100
2101   if (GV->isDeclaration()) {
2102     MachineFunction &MF = DAG.getMachineFunction();
2103     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2104     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2105     // Initial exec model.
2106     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2107     ARMConstantPoolValue *CPV =
2108       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2109                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2110                                       true);
2111     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2112     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2113     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2114                          MachinePointerInfo::getConstantPool(),
2115                          false, false, false, 0);
2116     Chain = Offset.getValue(1);
2117
2118     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2119     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2120
2121     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2122                          MachinePointerInfo::getConstantPool(),
2123                          false, false, false, 0);
2124   } else {
2125     // local exec model
2126     ARMConstantPoolValue *CPV =
2127       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2128     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2129     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2130     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2131                          MachinePointerInfo::getConstantPool(),
2132                          false, false, false, 0);
2133   }
2134
2135   // The address of the thread local variable is the add of the thread
2136   // pointer with the offset of the variable.
2137   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2138 }
2139
2140 SDValue
2141 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2142   // TODO: implement the "local dynamic" model
2143   assert(Subtarget->isTargetELF() &&
2144          "TLS not implemented for non-ELF targets");
2145   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2146   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
2147   // otherwise use the "Local Exec" TLS Model
2148   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
2149     return LowerToTLSGeneralDynamicModel(GA, DAG);
2150   else
2151     return LowerToTLSExecModels(GA, DAG);
2152 }
2153
2154 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2155                                                  SelectionDAG &DAG) const {
2156   EVT PtrVT = getPointerTy();
2157   DebugLoc dl = Op.getDebugLoc();
2158   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2159   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2160   if (RelocM == Reloc::PIC_) {
2161     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2162     ARMConstantPoolValue *CPV =
2163       ARMConstantPoolConstant::Create(GV,
2164                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2165     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2166     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2167     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2168                                  CPAddr,
2169                                  MachinePointerInfo::getConstantPool(),
2170                                  false, false, false, 0);
2171     SDValue Chain = Result.getValue(1);
2172     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2173     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2174     if (!UseGOTOFF)
2175       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2176                            MachinePointerInfo::getGOT(),
2177                            false, false, false, 0);
2178     return Result;
2179   }
2180
2181   // If we have T2 ops, we can materialize the address directly via movt/movw
2182   // pair. This is always cheaper.
2183   if (Subtarget->useMovt()) {
2184     ++NumMovwMovt;
2185     // FIXME: Once remat is capable of dealing with instructions with register
2186     // operands, expand this into two nodes.
2187     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2188                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2189   } else {
2190     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2191     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2192     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2193                        MachinePointerInfo::getConstantPool(),
2194                        false, false, false, 0);
2195   }
2196 }
2197
2198 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2199                                                     SelectionDAG &DAG) const {
2200   EVT PtrVT = getPointerTy();
2201   DebugLoc dl = Op.getDebugLoc();
2202   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2203   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2204   MachineFunction &MF = DAG.getMachineFunction();
2205   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2206
2207   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2208   // update ARMFastISel::ARMMaterializeGV.
2209   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2210     ++NumMovwMovt;
2211     // FIXME: Once remat is capable of dealing with instructions with register
2212     // operands, expand this into two nodes.
2213     if (RelocM == Reloc::Static)
2214       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2215                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2216
2217     unsigned Wrapper = (RelocM == Reloc::PIC_)
2218       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2219     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2220                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2221     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2222       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2223                            MachinePointerInfo::getGOT(),
2224                            false, false, false, 0);
2225     return Result;
2226   }
2227
2228   unsigned ARMPCLabelIndex = 0;
2229   SDValue CPAddr;
2230   if (RelocM == Reloc::Static) {
2231     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2232   } else {
2233     ARMPCLabelIndex = AFI->createPICLabelUId();
2234     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2235     ARMConstantPoolValue *CPV =
2236       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2237                                       PCAdj);
2238     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2239   }
2240   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2241
2242   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2243                                MachinePointerInfo::getConstantPool(),
2244                                false, false, false, 0);
2245   SDValue Chain = Result.getValue(1);
2246
2247   if (RelocM == Reloc::PIC_) {
2248     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2249     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2250   }
2251
2252   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2253     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2254                          false, false, false, 0);
2255
2256   return Result;
2257 }
2258
2259 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2260                                                     SelectionDAG &DAG) const {
2261   assert(Subtarget->isTargetELF() &&
2262          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2263   MachineFunction &MF = DAG.getMachineFunction();
2264   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2265   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2266   EVT PtrVT = getPointerTy();
2267   DebugLoc dl = Op.getDebugLoc();
2268   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2269   ARMConstantPoolValue *CPV =
2270     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2271                                   ARMPCLabelIndex, PCAdj);
2272   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2273   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2274   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2275                                MachinePointerInfo::getConstantPool(),
2276                                false, false, false, 0);
2277   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2278   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2279 }
2280
2281 SDValue
2282 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2283   DebugLoc dl = Op.getDebugLoc();
2284   SDValue Val = DAG.getConstant(0, MVT::i32);
2285   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2286                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2287                      Op.getOperand(1), Val);
2288 }
2289
2290 SDValue
2291 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2292   DebugLoc dl = Op.getDebugLoc();
2293   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2294                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2295 }
2296
2297 SDValue
2298 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2299                                           const ARMSubtarget *Subtarget) const {
2300   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2301   DebugLoc dl = Op.getDebugLoc();
2302   switch (IntNo) {
2303   default: return SDValue();    // Don't custom lower most intrinsics.
2304   case Intrinsic::arm_thread_pointer: {
2305     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2306     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2307   }
2308   case Intrinsic::eh_sjlj_lsda: {
2309     MachineFunction &MF = DAG.getMachineFunction();
2310     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2311     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2312     EVT PtrVT = getPointerTy();
2313     DebugLoc dl = Op.getDebugLoc();
2314     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2315     SDValue CPAddr;
2316     unsigned PCAdj = (RelocM != Reloc::PIC_)
2317       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2318     ARMConstantPoolValue *CPV =
2319       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2320                                       ARMCP::CPLSDA, PCAdj);
2321     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2322     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2323     SDValue Result =
2324       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2325                   MachinePointerInfo::getConstantPool(),
2326                   false, false, false, 0);
2327
2328     if (RelocM == Reloc::PIC_) {
2329       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2330       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2331     }
2332     return Result;
2333   }
2334   case Intrinsic::arm_neon_vmulls:
2335   case Intrinsic::arm_neon_vmullu: {
2336     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2337       ? ARMISD::VMULLs : ARMISD::VMULLu;
2338     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2339                        Op.getOperand(1), Op.getOperand(2));
2340   }
2341   }
2342 }
2343
2344 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2345                                const ARMSubtarget *Subtarget) {
2346   DebugLoc dl = Op.getDebugLoc();
2347   if (!Subtarget->hasDataBarrier()) {
2348     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2349     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2350     // here.
2351     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2352            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2353     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2354                        DAG.getConstant(0, MVT::i32));
2355   }
2356
2357   SDValue Op5 = Op.getOperand(5);
2358   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2359   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2360   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2361   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2362
2363   ARM_MB::MemBOpt DMBOpt;
2364   if (isDeviceBarrier)
2365     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2366   else
2367     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2368   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2369                      DAG.getConstant(DMBOpt, MVT::i32));
2370 }
2371
2372
2373 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2374                                  const ARMSubtarget *Subtarget) {
2375   // FIXME: handle "fence singlethread" more efficiently.
2376   DebugLoc dl = Op.getDebugLoc();
2377   if (!Subtarget->hasDataBarrier()) {
2378     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2379     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2380     // here.
2381     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2382            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2383     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2384                        DAG.getConstant(0, MVT::i32));
2385   }
2386
2387   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2388                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2389 }
2390
2391 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2392                              const ARMSubtarget *Subtarget) {
2393   // ARM pre v5TE and Thumb1 does not have preload instructions.
2394   if (!(Subtarget->isThumb2() ||
2395         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2396     // Just preserve the chain.
2397     return Op.getOperand(0);
2398
2399   DebugLoc dl = Op.getDebugLoc();
2400   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2401   if (!isRead &&
2402       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2403     // ARMv7 with MP extension has PLDW.
2404     return Op.getOperand(0);
2405
2406   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2407   if (Subtarget->isThumb()) {
2408     // Invert the bits.
2409     isRead = ~isRead & 1;
2410     isData = ~isData & 1;
2411   }
2412
2413   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2414                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2415                      DAG.getConstant(isData, MVT::i32));
2416 }
2417
2418 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2419   MachineFunction &MF = DAG.getMachineFunction();
2420   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2421
2422   // vastart just stores the address of the VarArgsFrameIndex slot into the
2423   // memory location argument.
2424   DebugLoc dl = Op.getDebugLoc();
2425   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2426   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2427   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2428   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2429                       MachinePointerInfo(SV), false, false, 0);
2430 }
2431
2432 SDValue
2433 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2434                                         SDValue &Root, SelectionDAG &DAG,
2435                                         DebugLoc dl) const {
2436   MachineFunction &MF = DAG.getMachineFunction();
2437   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2438
2439   const TargetRegisterClass *RC;
2440   if (AFI->isThumb1OnlyFunction())
2441     RC = ARM::tGPRRegisterClass;
2442   else
2443     RC = ARM::GPRRegisterClass;
2444
2445   // Transform the arguments stored in physical registers into virtual ones.
2446   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2447   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2448
2449   SDValue ArgValue2;
2450   if (NextVA.isMemLoc()) {
2451     MachineFrameInfo *MFI = MF.getFrameInfo();
2452     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2453
2454     // Create load node to retrieve arguments from the stack.
2455     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2456     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2457                             MachinePointerInfo::getFixedStack(FI),
2458                             false, false, false, 0);
2459   } else {
2460     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2461     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2462   }
2463
2464   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2465 }
2466
2467 void
2468 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2469                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2470   const {
2471   unsigned NumGPRs;
2472   if (CCInfo.isFirstByValRegValid())
2473     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2474   else {
2475     unsigned int firstUnalloced;
2476     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2477                                                 sizeof(GPRArgRegs) /
2478                                                 sizeof(GPRArgRegs[0]));
2479     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2480   }
2481
2482   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2483   VARegSize = NumGPRs * 4;
2484   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2485 }
2486
2487 // The remaining GPRs hold either the beginning of variable-argument
2488 // data, or the beginning of an aggregate passed by value (usuall
2489 // byval).  Either way, we allocate stack slots adjacent to the data
2490 // provided by our caller, and store the unallocated registers there.
2491 // If this is a variadic function, the va_list pointer will begin with
2492 // these values; otherwise, this reassembles a (byval) structure that
2493 // was split between registers and memory.
2494 void
2495 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2496                                         DebugLoc dl, SDValue &Chain,
2497                                         unsigned ArgOffset) const {
2498   MachineFunction &MF = DAG.getMachineFunction();
2499   MachineFrameInfo *MFI = MF.getFrameInfo();
2500   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2501   unsigned firstRegToSaveIndex;
2502   if (CCInfo.isFirstByValRegValid())
2503     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2504   else {
2505     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2506       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2507   }
2508
2509   unsigned VARegSize, VARegSaveSize;
2510   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2511   if (VARegSaveSize) {
2512     // If this function is vararg, store any remaining integer argument regs
2513     // to their spots on the stack so that they may be loaded by deferencing
2514     // the result of va_next.
2515     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2516     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2517                                                      ArgOffset + VARegSaveSize
2518                                                      - VARegSize,
2519                                                      false));
2520     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2521                                     getPointerTy());
2522
2523     SmallVector<SDValue, 4> MemOps;
2524     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2525       const TargetRegisterClass *RC;
2526       if (AFI->isThumb1OnlyFunction())
2527         RC = ARM::tGPRRegisterClass;
2528       else
2529         RC = ARM::GPRRegisterClass;
2530
2531       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2532       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2533       SDValue Store =
2534         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2535                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2536                      false, false, 0);
2537       MemOps.push_back(Store);
2538       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2539                         DAG.getConstant(4, getPointerTy()));
2540     }
2541     if (!MemOps.empty())
2542       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2543                           &MemOps[0], MemOps.size());
2544   } else
2545     // This will point to the next argument passed via stack.
2546     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2547 }
2548
2549 SDValue
2550 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2551                                         CallingConv::ID CallConv, bool isVarArg,
2552                                         const SmallVectorImpl<ISD::InputArg>
2553                                           &Ins,
2554                                         DebugLoc dl, SelectionDAG &DAG,
2555                                         SmallVectorImpl<SDValue> &InVals)
2556                                           const {
2557   MachineFunction &MF = DAG.getMachineFunction();
2558   MachineFrameInfo *MFI = MF.getFrameInfo();
2559
2560   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2561
2562   // Assign locations to all of the incoming arguments.
2563   SmallVector<CCValAssign, 16> ArgLocs;
2564   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2565                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2566   CCInfo.AnalyzeFormalArguments(Ins,
2567                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2568                                                   isVarArg));
2569
2570   SmallVector<SDValue, 16> ArgValues;
2571   int lastInsIndex = -1;
2572
2573   SDValue ArgValue;
2574   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2575     CCValAssign &VA = ArgLocs[i];
2576
2577     // Arguments stored in registers.
2578     if (VA.isRegLoc()) {
2579       EVT RegVT = VA.getLocVT();
2580
2581       if (VA.needsCustom()) {
2582         // f64 and vector types are split up into multiple registers or
2583         // combinations of registers and stack slots.
2584         if (VA.getLocVT() == MVT::v2f64) {
2585           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2586                                                    Chain, DAG, dl);
2587           VA = ArgLocs[++i]; // skip ahead to next loc
2588           SDValue ArgValue2;
2589           if (VA.isMemLoc()) {
2590             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2591             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2592             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2593                                     MachinePointerInfo::getFixedStack(FI),
2594                                     false, false, false, 0);
2595           } else {
2596             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2597                                              Chain, DAG, dl);
2598           }
2599           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2600           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2601                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2602           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2603                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2604         } else
2605           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2606
2607       } else {
2608         const TargetRegisterClass *RC;
2609
2610         if (RegVT == MVT::f32)
2611           RC = ARM::SPRRegisterClass;
2612         else if (RegVT == MVT::f64)
2613           RC = ARM::DPRRegisterClass;
2614         else if (RegVT == MVT::v2f64)
2615           RC = ARM::QPRRegisterClass;
2616         else if (RegVT == MVT::i32)
2617           RC = (AFI->isThumb1OnlyFunction() ?
2618                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2619         else
2620           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2621
2622         // Transform the arguments in physical registers into virtual ones.
2623         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2624         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2625       }
2626
2627       // If this is an 8 or 16-bit value, it is really passed promoted
2628       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2629       // truncate to the right size.
2630       switch (VA.getLocInfo()) {
2631       default: llvm_unreachable("Unknown loc info!");
2632       case CCValAssign::Full: break;
2633       case CCValAssign::BCvt:
2634         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2635         break;
2636       case CCValAssign::SExt:
2637         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2638                                DAG.getValueType(VA.getValVT()));
2639         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2640         break;
2641       case CCValAssign::ZExt:
2642         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2643                                DAG.getValueType(VA.getValVT()));
2644         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2645         break;
2646       }
2647
2648       InVals.push_back(ArgValue);
2649
2650     } else { // VA.isRegLoc()
2651
2652       // sanity check
2653       assert(VA.isMemLoc());
2654       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2655
2656       int index = ArgLocs[i].getValNo();
2657
2658       // Some Ins[] entries become multiple ArgLoc[] entries.
2659       // Process them only once.
2660       if (index != lastInsIndex)
2661         {
2662           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2663           // FIXME: For now, all byval parameter objects are marked mutable.
2664           // This can be changed with more analysis.
2665           // In case of tail call optimization mark all arguments mutable.
2666           // Since they could be overwritten by lowering of arguments in case of
2667           // a tail call.
2668           if (Flags.isByVal()) {
2669             unsigned VARegSize, VARegSaveSize;
2670             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2671             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2672             unsigned Bytes = Flags.getByValSize() - VARegSize;
2673             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2674             int FI = MFI->CreateFixedObject(Bytes,
2675                                             VA.getLocMemOffset(), false);
2676             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2677           } else {
2678             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2679                                             VA.getLocMemOffset(), true);
2680
2681             // Create load nodes to retrieve arguments from the stack.
2682             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2683             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2684                                          MachinePointerInfo::getFixedStack(FI),
2685                                          false, false, false, 0));
2686           }
2687           lastInsIndex = index;
2688         }
2689     }
2690   }
2691
2692   // varargs
2693   if (isVarArg)
2694     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2695
2696   return Chain;
2697 }
2698
2699 /// isFloatingPointZero - Return true if this is +0.0.
2700 static bool isFloatingPointZero(SDValue Op) {
2701   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2702     return CFP->getValueAPF().isPosZero();
2703   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2704     // Maybe this has already been legalized into the constant pool?
2705     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2706       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2707       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2708         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2709           return CFP->getValueAPF().isPosZero();
2710     }
2711   }
2712   return false;
2713 }
2714
2715 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2716 /// the given operands.
2717 SDValue
2718 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2719                              SDValue &ARMcc, SelectionDAG &DAG,
2720                              DebugLoc dl) const {
2721   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2722     unsigned C = RHSC->getZExtValue();
2723     if (!isLegalICmpImmediate(C)) {
2724       // Constant does not fit, try adjusting it by one?
2725       switch (CC) {
2726       default: break;
2727       case ISD::SETLT:
2728       case ISD::SETGE:
2729         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2730           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2731           RHS = DAG.getConstant(C-1, MVT::i32);
2732         }
2733         break;
2734       case ISD::SETULT:
2735       case ISD::SETUGE:
2736         if (C != 0 && isLegalICmpImmediate(C-1)) {
2737           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2738           RHS = DAG.getConstant(C-1, MVT::i32);
2739         }
2740         break;
2741       case ISD::SETLE:
2742       case ISD::SETGT:
2743         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2744           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2745           RHS = DAG.getConstant(C+1, MVT::i32);
2746         }
2747         break;
2748       case ISD::SETULE:
2749       case ISD::SETUGT:
2750         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2751           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2752           RHS = DAG.getConstant(C+1, MVT::i32);
2753         }
2754         break;
2755       }
2756     }
2757   }
2758
2759   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2760   ARMISD::NodeType CompareType;
2761   switch (CondCode) {
2762   default:
2763     CompareType = ARMISD::CMP;
2764     break;
2765   case ARMCC::EQ:
2766   case ARMCC::NE:
2767     // Uses only Z Flag
2768     CompareType = ARMISD::CMPZ;
2769     break;
2770   }
2771   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2772   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2773 }
2774
2775 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2776 SDValue
2777 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2778                              DebugLoc dl) const {
2779   SDValue Cmp;
2780   if (!isFloatingPointZero(RHS))
2781     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2782   else
2783     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2784   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2785 }
2786
2787 /// duplicateCmp - Glue values can have only one use, so this function
2788 /// duplicates a comparison node.
2789 SDValue
2790 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2791   unsigned Opc = Cmp.getOpcode();
2792   DebugLoc DL = Cmp.getDebugLoc();
2793   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2794     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2795
2796   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2797   Cmp = Cmp.getOperand(0);
2798   Opc = Cmp.getOpcode();
2799   if (Opc == ARMISD::CMPFP)
2800     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2801   else {
2802     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2803     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2804   }
2805   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2806 }
2807
2808 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2809   SDValue Cond = Op.getOperand(0);
2810   SDValue SelectTrue = Op.getOperand(1);
2811   SDValue SelectFalse = Op.getOperand(2);
2812   DebugLoc dl = Op.getDebugLoc();
2813
2814   // Convert:
2815   //
2816   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2817   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2818   //
2819   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2820     const ConstantSDNode *CMOVTrue =
2821       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2822     const ConstantSDNode *CMOVFalse =
2823       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2824
2825     if (CMOVTrue && CMOVFalse) {
2826       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2827       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2828
2829       SDValue True;
2830       SDValue False;
2831       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2832         True = SelectTrue;
2833         False = SelectFalse;
2834       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2835         True = SelectFalse;
2836         False = SelectTrue;
2837       }
2838
2839       if (True.getNode() && False.getNode()) {
2840         EVT VT = Op.getValueType();
2841         SDValue ARMcc = Cond.getOperand(2);
2842         SDValue CCR = Cond.getOperand(3);
2843         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2844         assert(True.getValueType() == VT);
2845         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2846       }
2847     }
2848   }
2849
2850   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2851   // undefined bits before doing a full-word comparison with zero.
2852   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2853                      DAG.getConstant(1, Cond.getValueType()));
2854
2855   return DAG.getSelectCC(dl, Cond,
2856                          DAG.getConstant(0, Cond.getValueType()),
2857                          SelectTrue, SelectFalse, ISD::SETNE);
2858 }
2859
2860 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2861   EVT VT = Op.getValueType();
2862   SDValue LHS = Op.getOperand(0);
2863   SDValue RHS = Op.getOperand(1);
2864   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2865   SDValue TrueVal = Op.getOperand(2);
2866   SDValue FalseVal = Op.getOperand(3);
2867   DebugLoc dl = Op.getDebugLoc();
2868
2869   if (LHS.getValueType() == MVT::i32) {
2870     SDValue ARMcc;
2871     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2872     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2873     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2874   }
2875
2876   ARMCC::CondCodes CondCode, CondCode2;
2877   FPCCToARMCC(CC, CondCode, CondCode2);
2878
2879   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2880   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2881   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2882   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2883                                ARMcc, CCR, Cmp);
2884   if (CondCode2 != ARMCC::AL) {
2885     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2886     // FIXME: Needs another CMP because flag can have but one use.
2887     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2888     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2889                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2890   }
2891   return Result;
2892 }
2893
2894 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2895 /// to morph to an integer compare sequence.
2896 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2897                            const ARMSubtarget *Subtarget) {
2898   SDNode *N = Op.getNode();
2899   if (!N->hasOneUse())
2900     // Otherwise it requires moving the value from fp to integer registers.
2901     return false;
2902   if (!N->getNumValues())
2903     return false;
2904   EVT VT = Op.getValueType();
2905   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2906     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2907     // vmrs are very slow, e.g. cortex-a8.
2908     return false;
2909
2910   if (isFloatingPointZero(Op)) {
2911     SeenZero = true;
2912     return true;
2913   }
2914   return ISD::isNormalLoad(N);
2915 }
2916
2917 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2918   if (isFloatingPointZero(Op))
2919     return DAG.getConstant(0, MVT::i32);
2920
2921   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2922     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2923                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2924                        Ld->isVolatile(), Ld->isNonTemporal(),
2925                        Ld->isInvariant(), Ld->getAlignment());
2926
2927   llvm_unreachable("Unknown VFP cmp argument!");
2928 }
2929
2930 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2931                            SDValue &RetVal1, SDValue &RetVal2) {
2932   if (isFloatingPointZero(Op)) {
2933     RetVal1 = DAG.getConstant(0, MVT::i32);
2934     RetVal2 = DAG.getConstant(0, MVT::i32);
2935     return;
2936   }
2937
2938   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2939     SDValue Ptr = Ld->getBasePtr();
2940     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2941                           Ld->getChain(), Ptr,
2942                           Ld->getPointerInfo(),
2943                           Ld->isVolatile(), Ld->isNonTemporal(),
2944                           Ld->isInvariant(), Ld->getAlignment());
2945
2946     EVT PtrType = Ptr.getValueType();
2947     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2948     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2949                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2950     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2951                           Ld->getChain(), NewPtr,
2952                           Ld->getPointerInfo().getWithOffset(4),
2953                           Ld->isVolatile(), Ld->isNonTemporal(),
2954                           Ld->isInvariant(), NewAlign);
2955     return;
2956   }
2957
2958   llvm_unreachable("Unknown VFP cmp argument!");
2959 }
2960
2961 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2962 /// f32 and even f64 comparisons to integer ones.
2963 SDValue
2964 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2965   SDValue Chain = Op.getOperand(0);
2966   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2967   SDValue LHS = Op.getOperand(2);
2968   SDValue RHS = Op.getOperand(3);
2969   SDValue Dest = Op.getOperand(4);
2970   DebugLoc dl = Op.getDebugLoc();
2971
2972   bool SeenZero = false;
2973   if (canChangeToInt(LHS, SeenZero, Subtarget) &&
2974       canChangeToInt(RHS, SeenZero, Subtarget) &&
2975       // If one of the operand is zero, it's safe to ignore the NaN case since
2976       // we only care about equality comparisons.
2977       (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))) {
2978     // If unsafe fp math optimization is enabled and there are no other uses of
2979     // the CMP operands, and the condition code is EQ or NE, we can optimize it
2980     // to an integer comparison.
2981     if (CC == ISD::SETOEQ)
2982       CC = ISD::SETEQ;
2983     else if (CC == ISD::SETUNE)
2984       CC = ISD::SETNE;
2985
2986     SDValue ARMcc;
2987     if (LHS.getValueType() == MVT::f32) {
2988       LHS = bitcastf32Toi32(LHS, DAG);
2989       RHS = bitcastf32Toi32(RHS, DAG);
2990       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2991       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2992       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
2993                          Chain, Dest, ARMcc, CCR, Cmp);
2994     }
2995
2996     SDValue LHS1, LHS2;
2997     SDValue RHS1, RHS2;
2998     expandf64Toi32(LHS, DAG, LHS1, LHS2);
2999     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3000     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3001     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3002     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3003     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3004     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3005   }
3006
3007   return SDValue();
3008 }
3009
3010 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3011   SDValue Chain = Op.getOperand(0);
3012   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3013   SDValue LHS = Op.getOperand(2);
3014   SDValue RHS = Op.getOperand(3);
3015   SDValue Dest = Op.getOperand(4);
3016   DebugLoc dl = Op.getDebugLoc();
3017
3018   if (LHS.getValueType() == MVT::i32) {
3019     SDValue ARMcc;
3020     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3021     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3022     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3023                        Chain, Dest, ARMcc, CCR, Cmp);
3024   }
3025
3026   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3027
3028   if (getTargetMachine().Options.UnsafeFPMath &&
3029       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3030        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3031     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3032     if (Result.getNode())
3033       return Result;
3034   }
3035
3036   ARMCC::CondCodes CondCode, CondCode2;
3037   FPCCToARMCC(CC, CondCode, CondCode2);
3038
3039   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3040   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3041   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3042   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3043   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3044   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3045   if (CondCode2 != ARMCC::AL) {
3046     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3047     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3048     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3049   }
3050   return Res;
3051 }
3052
3053 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3054   SDValue Chain = Op.getOperand(0);
3055   SDValue Table = Op.getOperand(1);
3056   SDValue Index = Op.getOperand(2);
3057   DebugLoc dl = Op.getDebugLoc();
3058
3059   EVT PTy = getPointerTy();
3060   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3061   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3062   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3063   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3064   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3065   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3066   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3067   if (Subtarget->isThumb2()) {
3068     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3069     // which does another jump to the destination. This also makes it easier
3070     // to translate it to TBB / TBH later.
3071     // FIXME: This might not work if the function is extremely large.
3072     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3073                        Addr, Op.getOperand(2), JTI, UId);
3074   }
3075   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3076     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3077                        MachinePointerInfo::getJumpTable(),
3078                        false, false, false, 0);
3079     Chain = Addr.getValue(1);
3080     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3081     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3082   } else {
3083     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3084                        MachinePointerInfo::getJumpTable(),
3085                        false, false, false, 0);
3086     Chain = Addr.getValue(1);
3087     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3088   }
3089 }
3090
3091 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3092   EVT VT = Op.getValueType();
3093   DebugLoc dl = Op.getDebugLoc();
3094
3095   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3096     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3097       return Op;
3098     return DAG.UnrollVectorOp(Op.getNode());
3099   }
3100
3101   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3102          "Invalid type for custom lowering!");
3103   if (VT != MVT::v4i16)
3104     return DAG.UnrollVectorOp(Op.getNode());
3105
3106   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3107   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3108 }
3109
3110 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3111   EVT VT = Op.getValueType();
3112   if (VT.isVector())
3113     return LowerVectorFP_TO_INT(Op, DAG);
3114
3115   DebugLoc dl = Op.getDebugLoc();
3116   unsigned Opc;
3117
3118   switch (Op.getOpcode()) {
3119   default: llvm_unreachable("Invalid opcode!");
3120   case ISD::FP_TO_SINT:
3121     Opc = ARMISD::FTOSI;
3122     break;
3123   case ISD::FP_TO_UINT:
3124     Opc = ARMISD::FTOUI;
3125     break;
3126   }
3127   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3128   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3129 }
3130
3131 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3132   EVT VT = Op.getValueType();
3133   DebugLoc dl = Op.getDebugLoc();
3134
3135   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3136     if (VT.getVectorElementType() == MVT::f32)
3137       return Op;
3138     return DAG.UnrollVectorOp(Op.getNode());
3139   }
3140
3141   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3142          "Invalid type for custom lowering!");
3143   if (VT != MVT::v4f32)
3144     return DAG.UnrollVectorOp(Op.getNode());
3145
3146   unsigned CastOpc;
3147   unsigned Opc;
3148   switch (Op.getOpcode()) {
3149   default: llvm_unreachable("Invalid opcode!");
3150   case ISD::SINT_TO_FP:
3151     CastOpc = ISD::SIGN_EXTEND;
3152     Opc = ISD::SINT_TO_FP;
3153     break;
3154   case ISD::UINT_TO_FP:
3155     CastOpc = ISD::ZERO_EXTEND;
3156     Opc = ISD::UINT_TO_FP;
3157     break;
3158   }
3159
3160   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3161   return DAG.getNode(Opc, dl, VT, Op);
3162 }
3163
3164 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3165   EVT VT = Op.getValueType();
3166   if (VT.isVector())
3167     return LowerVectorINT_TO_FP(Op, DAG);
3168
3169   DebugLoc dl = Op.getDebugLoc();
3170   unsigned Opc;
3171
3172   switch (Op.getOpcode()) {
3173   default: llvm_unreachable("Invalid opcode!");
3174   case ISD::SINT_TO_FP:
3175     Opc = ARMISD::SITOF;
3176     break;
3177   case ISD::UINT_TO_FP:
3178     Opc = ARMISD::UITOF;
3179     break;
3180   }
3181
3182   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3183   return DAG.getNode(Opc, dl, VT, Op);
3184 }
3185
3186 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3187   // Implement fcopysign with a fabs and a conditional fneg.
3188   SDValue Tmp0 = Op.getOperand(0);
3189   SDValue Tmp1 = Op.getOperand(1);
3190   DebugLoc dl = Op.getDebugLoc();
3191   EVT VT = Op.getValueType();
3192   EVT SrcVT = Tmp1.getValueType();
3193   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3194     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3195   bool UseNEON = !InGPR && Subtarget->hasNEON();
3196
3197   if (UseNEON) {
3198     // Use VBSL to copy the sign bit.
3199     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3200     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3201                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3202     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3203     if (VT == MVT::f64)
3204       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3205                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3206                          DAG.getConstant(32, MVT::i32));
3207     else /*if (VT == MVT::f32)*/
3208       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3209     if (SrcVT == MVT::f32) {
3210       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3211       if (VT == MVT::f64)
3212         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3213                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3214                            DAG.getConstant(32, MVT::i32));
3215     } else if (VT == MVT::f32)
3216       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3217                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3218                          DAG.getConstant(32, MVT::i32));
3219     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3220     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3221
3222     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3223                                             MVT::i32);
3224     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3225     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3226                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3227
3228     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3229                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3230                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3231     if (VT == MVT::f32) {
3232       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3233       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3234                         DAG.getConstant(0, MVT::i32));
3235     } else {
3236       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3237     }
3238
3239     return Res;
3240   }
3241
3242   // Bitcast operand 1 to i32.
3243   if (SrcVT == MVT::f64)
3244     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3245                        &Tmp1, 1).getValue(1);
3246   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3247
3248   // Or in the signbit with integer operations.
3249   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3250   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3251   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3252   if (VT == MVT::f32) {
3253     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3254                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3255     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3256                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3257   }
3258
3259   // f64: Or the high part with signbit and then combine two parts.
3260   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3261                      &Tmp0, 1);
3262   SDValue Lo = Tmp0.getValue(0);
3263   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3264   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3265   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3266 }
3267
3268 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3269   MachineFunction &MF = DAG.getMachineFunction();
3270   MachineFrameInfo *MFI = MF.getFrameInfo();
3271   MFI->setReturnAddressIsTaken(true);
3272
3273   EVT VT = Op.getValueType();
3274   DebugLoc dl = Op.getDebugLoc();
3275   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3276   if (Depth) {
3277     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3278     SDValue Offset = DAG.getConstant(4, MVT::i32);
3279     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3280                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3281                        MachinePointerInfo(), false, false, false, 0);
3282   }
3283
3284   // Return LR, which contains the return address. Mark it an implicit live-in.
3285   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3286   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3287 }
3288
3289 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3290   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3291   MFI->setFrameAddressIsTaken(true);
3292
3293   EVT VT = Op.getValueType();
3294   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3295   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3296   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3297     ? ARM::R7 : ARM::R11;
3298   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3299   while (Depth--)
3300     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3301                             MachinePointerInfo(),
3302                             false, false, false, 0);
3303   return FrameAddr;
3304 }
3305
3306 /// ExpandBITCAST - If the target supports VFP, this function is called to
3307 /// expand a bit convert where either the source or destination type is i64 to
3308 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3309 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3310 /// vectors), since the legalizer won't know what to do with that.
3311 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3313   DebugLoc dl = N->getDebugLoc();
3314   SDValue Op = N->getOperand(0);
3315
3316   // This function is only supposed to be called for i64 types, either as the
3317   // source or destination of the bit convert.
3318   EVT SrcVT = Op.getValueType();
3319   EVT DstVT = N->getValueType(0);
3320   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3321          "ExpandBITCAST called for non-i64 type");
3322
3323   // Turn i64->f64 into VMOVDRR.
3324   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3325     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3326                              DAG.getConstant(0, MVT::i32));
3327     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3328                              DAG.getConstant(1, MVT::i32));
3329     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3330                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3331   }
3332
3333   // Turn f64->i64 into VMOVRRD.
3334   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3335     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3336                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3337     // Merge the pieces into a single i64 value.
3338     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3339   }
3340
3341   return SDValue();
3342 }
3343
3344 /// getZeroVector - Returns a vector of specified type with all zero elements.
3345 /// Zero vectors are used to represent vector negation and in those cases
3346 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3347 /// not support i64 elements, so sometimes the zero vectors will need to be
3348 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3349 /// zero vector.
3350 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3351   assert(VT.isVector() && "Expected a vector type");
3352   // The canonical modified immediate encoding of a zero vector is....0!
3353   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3354   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3355   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3356   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3357 }
3358
3359 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3360 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3361 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3362                                                 SelectionDAG &DAG) const {
3363   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3364   EVT VT = Op.getValueType();
3365   unsigned VTBits = VT.getSizeInBits();
3366   DebugLoc dl = Op.getDebugLoc();
3367   SDValue ShOpLo = Op.getOperand(0);
3368   SDValue ShOpHi = Op.getOperand(1);
3369   SDValue ShAmt  = Op.getOperand(2);
3370   SDValue ARMcc;
3371   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3372
3373   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3374
3375   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3376                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3377   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3378   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3379                                    DAG.getConstant(VTBits, MVT::i32));
3380   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3381   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3382   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3383
3384   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3385   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3386                           ARMcc, DAG, dl);
3387   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3388   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3389                            CCR, Cmp);
3390
3391   SDValue Ops[2] = { Lo, Hi };
3392   return DAG.getMergeValues(Ops, 2, dl);
3393 }
3394
3395 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3396 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3397 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3398                                                SelectionDAG &DAG) const {
3399   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3400   EVT VT = Op.getValueType();
3401   unsigned VTBits = VT.getSizeInBits();
3402   DebugLoc dl = Op.getDebugLoc();
3403   SDValue ShOpLo = Op.getOperand(0);
3404   SDValue ShOpHi = Op.getOperand(1);
3405   SDValue ShAmt  = Op.getOperand(2);
3406   SDValue ARMcc;
3407
3408   assert(Op.getOpcode() == ISD::SHL_PARTS);
3409   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3410                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3411   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3412   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3413                                    DAG.getConstant(VTBits, MVT::i32));
3414   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3415   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3416
3417   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3418   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3419   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3420                           ARMcc, DAG, dl);
3421   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3422   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3423                            CCR, Cmp);
3424
3425   SDValue Ops[2] = { Lo, Hi };
3426   return DAG.getMergeValues(Ops, 2, dl);
3427 }
3428
3429 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3430                                             SelectionDAG &DAG) const {
3431   // The rounding mode is in bits 23:22 of the FPSCR.
3432   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3433   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3434   // so that the shift + and get folded into a bitfield extract.
3435   DebugLoc dl = Op.getDebugLoc();
3436   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3437                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3438                                               MVT::i32));
3439   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3440                                   DAG.getConstant(1U << 22, MVT::i32));
3441   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3442                               DAG.getConstant(22, MVT::i32));
3443   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3444                      DAG.getConstant(3, MVT::i32));
3445 }
3446
3447 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3448                          const ARMSubtarget *ST) {
3449   EVT VT = N->getValueType(0);
3450   DebugLoc dl = N->getDebugLoc();
3451
3452   if (!ST->hasV6T2Ops())
3453     return SDValue();
3454
3455   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3456   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3457 }
3458
3459 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3460                           const ARMSubtarget *ST) {
3461   EVT VT = N->getValueType(0);
3462   DebugLoc dl = N->getDebugLoc();
3463
3464   if (!VT.isVector())
3465     return SDValue();
3466
3467   // Lower vector shifts on NEON to use VSHL.
3468   assert(ST->hasNEON() && "unexpected vector shift");
3469
3470   // Left shifts translate directly to the vshiftu intrinsic.
3471   if (N->getOpcode() == ISD::SHL)
3472     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3473                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3474                        N->getOperand(0), N->getOperand(1));
3475
3476   assert((N->getOpcode() == ISD::SRA ||
3477           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3478
3479   // NEON uses the same intrinsics for both left and right shifts.  For
3480   // right shifts, the shift amounts are negative, so negate the vector of
3481   // shift amounts.
3482   EVT ShiftVT = N->getOperand(1).getValueType();
3483   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3484                                      getZeroVector(ShiftVT, DAG, dl),
3485                                      N->getOperand(1));
3486   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3487                              Intrinsic::arm_neon_vshifts :
3488                              Intrinsic::arm_neon_vshiftu);
3489   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3490                      DAG.getConstant(vshiftInt, MVT::i32),
3491                      N->getOperand(0), NegatedCount);
3492 }
3493
3494 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3495                                 const ARMSubtarget *ST) {
3496   EVT VT = N->getValueType(0);
3497   DebugLoc dl = N->getDebugLoc();
3498
3499   // We can get here for a node like i32 = ISD::SHL i32, i64
3500   if (VT != MVT::i64)
3501     return SDValue();
3502
3503   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3504          "Unknown shift to lower!");
3505
3506   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3507   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3508       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3509     return SDValue();
3510
3511   // If we are in thumb mode, we don't have RRX.
3512   if (ST->isThumb1Only()) return SDValue();
3513
3514   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3515   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3516                            DAG.getConstant(0, MVT::i32));
3517   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3518                            DAG.getConstant(1, MVT::i32));
3519
3520   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3521   // captures the result into a carry flag.
3522   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3523   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3524
3525   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3526   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3527
3528   // Merge the pieces into a single i64 value.
3529  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3530 }
3531
3532 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3533   SDValue TmpOp0, TmpOp1;
3534   bool Invert = false;
3535   bool Swap = false;
3536   unsigned Opc = 0;
3537
3538   SDValue Op0 = Op.getOperand(0);
3539   SDValue Op1 = Op.getOperand(1);
3540   SDValue CC = Op.getOperand(2);
3541   EVT VT = Op.getValueType();
3542   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3543   DebugLoc dl = Op.getDebugLoc();
3544
3545   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3546     switch (SetCCOpcode) {
3547     default: llvm_unreachable("Illegal FP comparison");
3548     case ISD::SETUNE:
3549     case ISD::SETNE:  Invert = true; // Fallthrough
3550     case ISD::SETOEQ:
3551     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3552     case ISD::SETOLT:
3553     case ISD::SETLT: Swap = true; // Fallthrough
3554     case ISD::SETOGT:
3555     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3556     case ISD::SETOLE:
3557     case ISD::SETLE:  Swap = true; // Fallthrough
3558     case ISD::SETOGE:
3559     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3560     case ISD::SETUGE: Swap = true; // Fallthrough
3561     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3562     case ISD::SETUGT: Swap = true; // Fallthrough
3563     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3564     case ISD::SETUEQ: Invert = true; // Fallthrough
3565     case ISD::SETONE:
3566       // Expand this to (OLT | OGT).
3567       TmpOp0 = Op0;
3568       TmpOp1 = Op1;
3569       Opc = ISD::OR;
3570       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3571       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3572       break;
3573     case ISD::SETUO: Invert = true; // Fallthrough
3574     case ISD::SETO:
3575       // Expand this to (OLT | OGE).
3576       TmpOp0 = Op0;
3577       TmpOp1 = Op1;
3578       Opc = ISD::OR;
3579       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3580       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3581       break;
3582     }
3583   } else {
3584     // Integer comparisons.
3585     switch (SetCCOpcode) {
3586     default: llvm_unreachable("Illegal integer comparison");
3587     case ISD::SETNE:  Invert = true;
3588     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3589     case ISD::SETLT:  Swap = true;
3590     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3591     case ISD::SETLE:  Swap = true;
3592     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3593     case ISD::SETULT: Swap = true;
3594     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3595     case ISD::SETULE: Swap = true;
3596     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3597     }
3598
3599     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3600     if (Opc == ARMISD::VCEQ) {
3601
3602       SDValue AndOp;
3603       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3604         AndOp = Op0;
3605       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3606         AndOp = Op1;
3607
3608       // Ignore bitconvert.
3609       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3610         AndOp = AndOp.getOperand(0);
3611
3612       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3613         Opc = ARMISD::VTST;
3614         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3615         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3616         Invert = !Invert;
3617       }
3618     }
3619   }
3620
3621   if (Swap)
3622     std::swap(Op0, Op1);
3623
3624   // If one of the operands is a constant vector zero, attempt to fold the
3625   // comparison to a specialized compare-against-zero form.
3626   SDValue SingleOp;
3627   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3628     SingleOp = Op0;
3629   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3630     if (Opc == ARMISD::VCGE)
3631       Opc = ARMISD::VCLEZ;
3632     else if (Opc == ARMISD::VCGT)
3633       Opc = ARMISD::VCLTZ;
3634     SingleOp = Op1;
3635   }
3636
3637   SDValue Result;
3638   if (SingleOp.getNode()) {
3639     switch (Opc) {
3640     case ARMISD::VCEQ:
3641       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3642     case ARMISD::VCGE:
3643       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3644     case ARMISD::VCLEZ:
3645       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3646     case ARMISD::VCGT:
3647       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3648     case ARMISD::VCLTZ:
3649       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3650     default:
3651       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3652     }
3653   } else {
3654      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3655   }
3656
3657   if (Invert)
3658     Result = DAG.getNOT(dl, Result, VT);
3659
3660   return Result;
3661 }
3662
3663 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3664 /// valid vector constant for a NEON instruction with a "modified immediate"
3665 /// operand (e.g., VMOV).  If so, return the encoded value.
3666 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3667                                  unsigned SplatBitSize, SelectionDAG &DAG,
3668                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3669   unsigned OpCmode, Imm;
3670
3671   // SplatBitSize is set to the smallest size that splats the vector, so a
3672   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3673   // immediate instructions others than VMOV do not support the 8-bit encoding
3674   // of a zero vector, and the default encoding of zero is supposed to be the
3675   // 32-bit version.
3676   if (SplatBits == 0)
3677     SplatBitSize = 32;
3678
3679   switch (SplatBitSize) {
3680   case 8:
3681     if (type != VMOVModImm)
3682       return SDValue();
3683     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3684     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3685     OpCmode = 0xe;
3686     Imm = SplatBits;
3687     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3688     break;
3689
3690   case 16:
3691     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3692     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3693     if ((SplatBits & ~0xff) == 0) {
3694       // Value = 0x00nn: Op=x, Cmode=100x.
3695       OpCmode = 0x8;
3696       Imm = SplatBits;
3697       break;
3698     }
3699     if ((SplatBits & ~0xff00) == 0) {
3700       // Value = 0xnn00: Op=x, Cmode=101x.
3701       OpCmode = 0xa;
3702       Imm = SplatBits >> 8;
3703       break;
3704     }
3705     return SDValue();
3706
3707   case 32:
3708     // NEON's 32-bit VMOV supports splat values where:
3709     // * only one byte is nonzero, or
3710     // * the least significant byte is 0xff and the second byte is nonzero, or
3711     // * the least significant 2 bytes are 0xff and the third is nonzero.
3712     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3713     if ((SplatBits & ~0xff) == 0) {
3714       // Value = 0x000000nn: Op=x, Cmode=000x.
3715       OpCmode = 0;
3716       Imm = SplatBits;
3717       break;
3718     }
3719     if ((SplatBits & ~0xff00) == 0) {
3720       // Value = 0x0000nn00: Op=x, Cmode=001x.
3721       OpCmode = 0x2;
3722       Imm = SplatBits >> 8;
3723       break;
3724     }
3725     if ((SplatBits & ~0xff0000) == 0) {
3726       // Value = 0x00nn0000: Op=x, Cmode=010x.
3727       OpCmode = 0x4;
3728       Imm = SplatBits >> 16;
3729       break;
3730     }
3731     if ((SplatBits & ~0xff000000) == 0) {
3732       // Value = 0xnn000000: Op=x, Cmode=011x.
3733       OpCmode = 0x6;
3734       Imm = SplatBits >> 24;
3735       break;
3736     }
3737
3738     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3739     if (type == OtherModImm) return SDValue();
3740
3741     if ((SplatBits & ~0xffff) == 0 &&
3742         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3743       // Value = 0x0000nnff: Op=x, Cmode=1100.
3744       OpCmode = 0xc;
3745       Imm = SplatBits >> 8;
3746       SplatBits |= 0xff;
3747       break;
3748     }
3749
3750     if ((SplatBits & ~0xffffff) == 0 &&
3751         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3752       // Value = 0x00nnffff: Op=x, Cmode=1101.
3753       OpCmode = 0xd;
3754       Imm = SplatBits >> 16;
3755       SplatBits |= 0xffff;
3756       break;
3757     }
3758
3759     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3760     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3761     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3762     // and fall through here to test for a valid 64-bit splat.  But, then the
3763     // caller would also need to check and handle the change in size.
3764     return SDValue();
3765
3766   case 64: {
3767     if (type != VMOVModImm)
3768       return SDValue();
3769     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3770     uint64_t BitMask = 0xff;
3771     uint64_t Val = 0;
3772     unsigned ImmMask = 1;
3773     Imm = 0;
3774     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3775       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3776         Val |= BitMask;
3777         Imm |= ImmMask;
3778       } else if ((SplatBits & BitMask) != 0) {
3779         return SDValue();
3780       }
3781       BitMask <<= 8;
3782       ImmMask <<= 1;
3783     }
3784     // Op=1, Cmode=1110.
3785     OpCmode = 0x1e;
3786     SplatBits = Val;
3787     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3788     break;
3789   }
3790
3791   default:
3792     llvm_unreachable("unexpected size for isNEONModifiedImm");
3793   }
3794
3795   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3796   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3797 }
3798
3799 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3800                        bool &ReverseVEXT, unsigned &Imm) {
3801   unsigned NumElts = VT.getVectorNumElements();
3802   ReverseVEXT = false;
3803
3804   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3805   if (M[0] < 0)
3806     return false;
3807
3808   Imm = M[0];
3809
3810   // If this is a VEXT shuffle, the immediate value is the index of the first
3811   // element.  The other shuffle indices must be the successive elements after
3812   // the first one.
3813   unsigned ExpectedElt = Imm;
3814   for (unsigned i = 1; i < NumElts; ++i) {
3815     // Increment the expected index.  If it wraps around, it may still be
3816     // a VEXT but the source vectors must be swapped.
3817     ExpectedElt += 1;
3818     if (ExpectedElt == NumElts * 2) {
3819       ExpectedElt = 0;
3820       ReverseVEXT = true;
3821     }
3822
3823     if (M[i] < 0) continue; // ignore UNDEF indices
3824     if (ExpectedElt != static_cast<unsigned>(M[i]))
3825       return false;
3826   }
3827
3828   // Adjust the index value if the source operands will be swapped.
3829   if (ReverseVEXT)
3830     Imm -= NumElts;
3831
3832   return true;
3833 }
3834
3835 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3836 /// instruction with the specified blocksize.  (The order of the elements
3837 /// within each block of the vector is reversed.)
3838 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3839   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3840          "Only possible block sizes for VREV are: 16, 32, 64");
3841
3842   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3843   if (EltSz == 64)
3844     return false;
3845
3846   unsigned NumElts = VT.getVectorNumElements();
3847   unsigned BlockElts = M[0] + 1;
3848   // If the first shuffle index is UNDEF, be optimistic.
3849   if (M[0] < 0)
3850     BlockElts = BlockSize / EltSz;
3851
3852   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3853     return false;
3854
3855   for (unsigned i = 0; i < NumElts; ++i) {
3856     if (M[i] < 0) continue; // ignore UNDEF indices
3857     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3858       return false;
3859   }
3860
3861   return true;
3862 }
3863
3864 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3865   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3866   // range, then 0 is placed into the resulting vector. So pretty much any mask
3867   // of 8 elements can work here.
3868   return VT == MVT::v8i8 && M.size() == 8;
3869 }
3870
3871 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3872   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3873   if (EltSz == 64)
3874     return false;
3875
3876   unsigned NumElts = VT.getVectorNumElements();
3877   WhichResult = (M[0] == 0 ? 0 : 1);
3878   for (unsigned i = 0; i < NumElts; i += 2) {
3879     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3880         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3881       return false;
3882   }
3883   return true;
3884 }
3885
3886 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3887 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3888 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3889 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3890   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3891   if (EltSz == 64)
3892     return false;
3893
3894   unsigned NumElts = VT.getVectorNumElements();
3895   WhichResult = (M[0] == 0 ? 0 : 1);
3896   for (unsigned i = 0; i < NumElts; i += 2) {
3897     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3898         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3899       return false;
3900   }
3901   return true;
3902 }
3903
3904 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3905   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3906   if (EltSz == 64)
3907     return false;
3908
3909   unsigned NumElts = VT.getVectorNumElements();
3910   WhichResult = (M[0] == 0 ? 0 : 1);
3911   for (unsigned i = 0; i != NumElts; ++i) {
3912     if (M[i] < 0) continue; // ignore UNDEF indices
3913     if ((unsigned) M[i] != 2 * i + WhichResult)
3914       return false;
3915   }
3916
3917   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3918   if (VT.is64BitVector() && EltSz == 32)
3919     return false;
3920
3921   return true;
3922 }
3923
3924 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3925 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3926 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3927 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3928   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3929   if (EltSz == 64)
3930     return false;
3931
3932   unsigned Half = VT.getVectorNumElements() / 2;
3933   WhichResult = (M[0] == 0 ? 0 : 1);
3934   for (unsigned j = 0; j != 2; ++j) {
3935     unsigned Idx = WhichResult;
3936     for (unsigned i = 0; i != Half; ++i) {
3937       int MIdx = M[i + j * Half];
3938       if (MIdx >= 0 && (unsigned) MIdx != Idx)
3939         return false;
3940       Idx += 2;
3941     }
3942   }
3943
3944   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3945   if (VT.is64BitVector() && EltSz == 32)
3946     return false;
3947
3948   return true;
3949 }
3950
3951 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3952   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3953   if (EltSz == 64)
3954     return false;
3955
3956   unsigned NumElts = VT.getVectorNumElements();
3957   WhichResult = (M[0] == 0 ? 0 : 1);
3958   unsigned Idx = WhichResult * NumElts / 2;
3959   for (unsigned i = 0; i != NumElts; i += 2) {
3960     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3961         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3962       return false;
3963     Idx += 1;
3964   }
3965
3966   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3967   if (VT.is64BitVector() && EltSz == 32)
3968     return false;
3969
3970   return true;
3971 }
3972
3973 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3974 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3975 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3976 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3977   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3978   if (EltSz == 64)
3979     return false;
3980
3981   unsigned NumElts = VT.getVectorNumElements();
3982   WhichResult = (M[0] == 0 ? 0 : 1);
3983   unsigned Idx = WhichResult * NumElts / 2;
3984   for (unsigned i = 0; i != NumElts; i += 2) {
3985     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3986         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
3987       return false;
3988     Idx += 1;
3989   }
3990
3991   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3992   if (VT.is64BitVector() && EltSz == 32)
3993     return false;
3994
3995   return true;
3996 }
3997
3998 // If N is an integer constant that can be moved into a register in one
3999 // instruction, return an SDValue of such a constant (will become a MOV
4000 // instruction).  Otherwise return null.
4001 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4002                                      const ARMSubtarget *ST, DebugLoc dl) {
4003   uint64_t Val;
4004   if (!isa<ConstantSDNode>(N))
4005     return SDValue();
4006   Val = cast<ConstantSDNode>(N)->getZExtValue();
4007
4008   if (ST->isThumb1Only()) {
4009     if (Val <= 255 || ~Val <= 255)
4010       return DAG.getConstant(Val, MVT::i32);
4011   } else {
4012     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4013       return DAG.getConstant(Val, MVT::i32);
4014   }
4015   return SDValue();
4016 }
4017
4018 // If this is a case we can't handle, return null and let the default
4019 // expansion code take care of it.
4020 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4021                                              const ARMSubtarget *ST) const {
4022   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4023   DebugLoc dl = Op.getDebugLoc();
4024   EVT VT = Op.getValueType();
4025
4026   APInt SplatBits, SplatUndef;
4027   unsigned SplatBitSize;
4028   bool HasAnyUndefs;
4029   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4030     if (SplatBitSize <= 64) {
4031       // Check if an immediate VMOV works.
4032       EVT VmovVT;
4033       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4034                                       SplatUndef.getZExtValue(), SplatBitSize,
4035                                       DAG, VmovVT, VT.is128BitVector(),
4036                                       VMOVModImm);
4037       if (Val.getNode()) {
4038         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4039         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4040       }
4041
4042       // Try an immediate VMVN.
4043       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4044       Val = isNEONModifiedImm(NegatedImm,
4045                                       SplatUndef.getZExtValue(), SplatBitSize,
4046                                       DAG, VmovVT, VT.is128BitVector(),
4047                                       VMVNModImm);
4048       if (Val.getNode()) {
4049         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4050         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4051       }
4052
4053       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4054       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4055         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4056         if (ImmVal != -1) {
4057           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4058           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4059         }
4060       }
4061     }
4062   }
4063
4064   // Scan through the operands to see if only one value is used.
4065   unsigned NumElts = VT.getVectorNumElements();
4066   bool isOnlyLowElement = true;
4067   bool usesOnlyOneValue = true;
4068   bool isConstant = true;
4069   SDValue Value;
4070   for (unsigned i = 0; i < NumElts; ++i) {
4071     SDValue V = Op.getOperand(i);
4072     if (V.getOpcode() == ISD::UNDEF)
4073       continue;
4074     if (i > 0)
4075       isOnlyLowElement = false;
4076     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4077       isConstant = false;
4078
4079     if (!Value.getNode())
4080       Value = V;
4081     else if (V != Value)
4082       usesOnlyOneValue = false;
4083   }
4084
4085   if (!Value.getNode())
4086     return DAG.getUNDEF(VT);
4087
4088   if (isOnlyLowElement)
4089     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4090
4091   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4092
4093   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4094   // i32 and try again.
4095   if (usesOnlyOneValue && EltSize <= 32) {
4096     if (!isConstant)
4097       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4098     if (VT.getVectorElementType().isFloatingPoint()) {
4099       SmallVector<SDValue, 8> Ops;
4100       for (unsigned i = 0; i < NumElts; ++i)
4101         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4102                                   Op.getOperand(i)));
4103       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4104       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4105       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4106       if (Val.getNode())
4107         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4108     }
4109     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4110     if (Val.getNode())
4111       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4112   }
4113
4114   // If all elements are constants and the case above didn't get hit, fall back
4115   // to the default expansion, which will generate a load from the constant
4116   // pool.
4117   if (isConstant)
4118     return SDValue();
4119
4120   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4121   if (NumElts >= 4) {
4122     SDValue shuffle = ReconstructShuffle(Op, DAG);
4123     if (shuffle != SDValue())
4124       return shuffle;
4125   }
4126
4127   // Vectors with 32- or 64-bit elements can be built by directly assigning
4128   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4129   // will be legalized.
4130   if (EltSize >= 32) {
4131     // Do the expansion with floating-point types, since that is what the VFP
4132     // registers are defined to use, and since i64 is not legal.
4133     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4134     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4135     SmallVector<SDValue, 8> Ops;
4136     for (unsigned i = 0; i < NumElts; ++i)
4137       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4138     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4139     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4140   }
4141
4142   return SDValue();
4143 }
4144
4145 // Gather data to see if the operation can be modelled as a
4146 // shuffle in combination with VEXTs.
4147 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4148                                               SelectionDAG &DAG) const {
4149   DebugLoc dl = Op.getDebugLoc();
4150   EVT VT = Op.getValueType();
4151   unsigned NumElts = VT.getVectorNumElements();
4152
4153   SmallVector<SDValue, 2> SourceVecs;
4154   SmallVector<unsigned, 2> MinElts;
4155   SmallVector<unsigned, 2> MaxElts;
4156
4157   for (unsigned i = 0; i < NumElts; ++i) {
4158     SDValue V = Op.getOperand(i);
4159     if (V.getOpcode() == ISD::UNDEF)
4160       continue;
4161     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4162       // A shuffle can only come from building a vector from various
4163       // elements of other vectors.
4164       return SDValue();
4165     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4166                VT.getVectorElementType()) {
4167       // This code doesn't know how to handle shuffles where the vector
4168       // element types do not match (this happens because type legalization
4169       // promotes the return type of EXTRACT_VECTOR_ELT).
4170       // FIXME: It might be appropriate to extend this code to handle
4171       // mismatched types.
4172       return SDValue();
4173     }
4174
4175     // Record this extraction against the appropriate vector if possible...
4176     SDValue SourceVec = V.getOperand(0);
4177     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4178     bool FoundSource = false;
4179     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4180       if (SourceVecs[j] == SourceVec) {
4181         if (MinElts[j] > EltNo)
4182           MinElts[j] = EltNo;
4183         if (MaxElts[j] < EltNo)
4184           MaxElts[j] = EltNo;
4185         FoundSource = true;
4186         break;
4187       }
4188     }
4189
4190     // Or record a new source if not...
4191     if (!FoundSource) {
4192       SourceVecs.push_back(SourceVec);
4193       MinElts.push_back(EltNo);
4194       MaxElts.push_back(EltNo);
4195     }
4196   }
4197
4198   // Currently only do something sane when at most two source vectors
4199   // involved.
4200   if (SourceVecs.size() > 2)
4201     return SDValue();
4202
4203   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4204   int VEXTOffsets[2] = {0, 0};
4205
4206   // This loop extracts the usage patterns of the source vectors
4207   // and prepares appropriate SDValues for a shuffle if possible.
4208   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4209     if (SourceVecs[i].getValueType() == VT) {
4210       // No VEXT necessary
4211       ShuffleSrcs[i] = SourceVecs[i];
4212       VEXTOffsets[i] = 0;
4213       continue;
4214     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4215       // It probably isn't worth padding out a smaller vector just to
4216       // break it down again in a shuffle.
4217       return SDValue();
4218     }
4219
4220     // Since only 64-bit and 128-bit vectors are legal on ARM and
4221     // we've eliminated the other cases...
4222     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4223            "unexpected vector sizes in ReconstructShuffle");
4224
4225     if (MaxElts[i] - MinElts[i] >= NumElts) {
4226       // Span too large for a VEXT to cope
4227       return SDValue();
4228     }
4229
4230     if (MinElts[i] >= NumElts) {
4231       // The extraction can just take the second half
4232       VEXTOffsets[i] = NumElts;
4233       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4234                                    SourceVecs[i],
4235                                    DAG.getIntPtrConstant(NumElts));
4236     } else if (MaxElts[i] < NumElts) {
4237       // The extraction can just take the first half
4238       VEXTOffsets[i] = 0;
4239       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4240                                    SourceVecs[i],
4241                                    DAG.getIntPtrConstant(0));
4242     } else {
4243       // An actual VEXT is needed
4244       VEXTOffsets[i] = MinElts[i];
4245       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4246                                      SourceVecs[i],
4247                                      DAG.getIntPtrConstant(0));
4248       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4249                                      SourceVecs[i],
4250                                      DAG.getIntPtrConstant(NumElts));
4251       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4252                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4253     }
4254   }
4255
4256   SmallVector<int, 8> Mask;
4257
4258   for (unsigned i = 0; i < NumElts; ++i) {
4259     SDValue Entry = Op.getOperand(i);
4260     if (Entry.getOpcode() == ISD::UNDEF) {
4261       Mask.push_back(-1);
4262       continue;
4263     }
4264
4265     SDValue ExtractVec = Entry.getOperand(0);
4266     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4267                                           .getOperand(1))->getSExtValue();
4268     if (ExtractVec == SourceVecs[0]) {
4269       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4270     } else {
4271       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4272     }
4273   }
4274
4275   // Final check before we try to produce nonsense...
4276   if (isShuffleMaskLegal(Mask, VT))
4277     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4278                                 &Mask[0]);
4279
4280   return SDValue();
4281 }
4282
4283 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4284 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4285 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4286 /// are assumed to be legal.
4287 bool
4288 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4289                                       EVT VT) const {
4290   if (VT.getVectorNumElements() == 4 &&
4291       (VT.is128BitVector() || VT.is64BitVector())) {
4292     unsigned PFIndexes[4];
4293     for (unsigned i = 0; i != 4; ++i) {
4294       if (M[i] < 0)
4295         PFIndexes[i] = 8;
4296       else
4297         PFIndexes[i] = M[i];
4298     }
4299
4300     // Compute the index in the perfect shuffle table.
4301     unsigned PFTableIndex =
4302       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4303     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4304     unsigned Cost = (PFEntry >> 30);
4305
4306     if (Cost <= 4)
4307       return true;
4308   }
4309
4310   bool ReverseVEXT;
4311   unsigned Imm, WhichResult;
4312
4313   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4314   return (EltSize >= 32 ||
4315           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4316           isVREVMask(M, VT, 64) ||
4317           isVREVMask(M, VT, 32) ||
4318           isVREVMask(M, VT, 16) ||
4319           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4320           isVTBLMask(M, VT) ||
4321           isVTRNMask(M, VT, WhichResult) ||
4322           isVUZPMask(M, VT, WhichResult) ||
4323           isVZIPMask(M, VT, WhichResult) ||
4324           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4325           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4326           isVZIP_v_undef_Mask(M, VT, WhichResult));
4327 }
4328
4329 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4330 /// the specified operations to build the shuffle.
4331 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4332                                       SDValue RHS, SelectionDAG &DAG,
4333                                       DebugLoc dl) {
4334   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4335   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4336   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4337
4338   enum {
4339     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4340     OP_VREV,
4341     OP_VDUP0,
4342     OP_VDUP1,
4343     OP_VDUP2,
4344     OP_VDUP3,
4345     OP_VEXT1,
4346     OP_VEXT2,
4347     OP_VEXT3,
4348     OP_VUZPL, // VUZP, left result
4349     OP_VUZPR, // VUZP, right result
4350     OP_VZIPL, // VZIP, left result
4351     OP_VZIPR, // VZIP, right result
4352     OP_VTRNL, // VTRN, left result
4353     OP_VTRNR  // VTRN, right result
4354   };
4355
4356   if (OpNum == OP_COPY) {
4357     if (LHSID == (1*9+2)*9+3) return LHS;
4358     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4359     return RHS;
4360   }
4361
4362   SDValue OpLHS, OpRHS;
4363   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4364   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4365   EVT VT = OpLHS.getValueType();
4366
4367   switch (OpNum) {
4368   default: llvm_unreachable("Unknown shuffle opcode!");
4369   case OP_VREV:
4370     // VREV divides the vector in half and swaps within the half.
4371     if (VT.getVectorElementType() == MVT::i32 ||
4372         VT.getVectorElementType() == MVT::f32)
4373       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4374     // vrev <4 x i16> -> VREV32
4375     if (VT.getVectorElementType() == MVT::i16)
4376       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4377     // vrev <4 x i8> -> VREV16
4378     assert(VT.getVectorElementType() == MVT::i8);
4379     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4380   case OP_VDUP0:
4381   case OP_VDUP1:
4382   case OP_VDUP2:
4383   case OP_VDUP3:
4384     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4385                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4386   case OP_VEXT1:
4387   case OP_VEXT2:
4388   case OP_VEXT3:
4389     return DAG.getNode(ARMISD::VEXT, dl, VT,
4390                        OpLHS, OpRHS,
4391                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4392   case OP_VUZPL:
4393   case OP_VUZPR:
4394     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4395                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4396   case OP_VZIPL:
4397   case OP_VZIPR:
4398     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4399                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4400   case OP_VTRNL:
4401   case OP_VTRNR:
4402     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4403                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4404   }
4405 }
4406
4407 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4408                                        ArrayRef<int> ShuffleMask,
4409                                        SelectionDAG &DAG) {
4410   // Check to see if we can use the VTBL instruction.
4411   SDValue V1 = Op.getOperand(0);
4412   SDValue V2 = Op.getOperand(1);
4413   DebugLoc DL = Op.getDebugLoc();
4414
4415   SmallVector<SDValue, 8> VTBLMask;
4416   for (ArrayRef<int>::iterator
4417          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4418     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4419
4420   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4421     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4422                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4423                                    &VTBLMask[0], 8));
4424
4425   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4426                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4427                                  &VTBLMask[0], 8));
4428 }
4429
4430 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4431   SDValue V1 = Op.getOperand(0);
4432   SDValue V2 = Op.getOperand(1);
4433   DebugLoc dl = Op.getDebugLoc();
4434   EVT VT = Op.getValueType();
4435   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4436
4437   // Convert shuffles that are directly supported on NEON to target-specific
4438   // DAG nodes, instead of keeping them as shuffles and matching them again
4439   // during code selection.  This is more efficient and avoids the possibility
4440   // of inconsistencies between legalization and selection.
4441   // FIXME: floating-point vectors should be canonicalized to integer vectors
4442   // of the same time so that they get CSEd properly.
4443   ArrayRef<int> ShuffleMask = SVN->getMask();
4444
4445   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4446   if (EltSize <= 32) {
4447     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4448       int Lane = SVN->getSplatIndex();
4449       // If this is undef splat, generate it via "just" vdup, if possible.
4450       if (Lane == -1) Lane = 0;
4451
4452       // Test if V1 is a SCALAR_TO_VECTOR.
4453       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4454         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4455       }
4456       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4457       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4458       // reaches it).
4459       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4460           !isa<ConstantSDNode>(V1.getOperand(0))) {
4461         bool IsScalarToVector = true;
4462         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4463           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4464             IsScalarToVector = false;
4465             break;
4466           }
4467         if (IsScalarToVector)
4468           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4469       }
4470       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4471                          DAG.getConstant(Lane, MVT::i32));
4472     }
4473
4474     bool ReverseVEXT;
4475     unsigned Imm;
4476     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4477       if (ReverseVEXT)
4478         std::swap(V1, V2);
4479       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4480                          DAG.getConstant(Imm, MVT::i32));
4481     }
4482
4483     if (isVREVMask(ShuffleMask, VT, 64))
4484       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4485     if (isVREVMask(ShuffleMask, VT, 32))
4486       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4487     if (isVREVMask(ShuffleMask, VT, 16))
4488       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4489
4490     // Check for Neon shuffles that modify both input vectors in place.
4491     // If both results are used, i.e., if there are two shuffles with the same
4492     // source operands and with masks corresponding to both results of one of
4493     // these operations, DAG memoization will ensure that a single node is
4494     // used for both shuffles.
4495     unsigned WhichResult;
4496     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4497       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4498                          V1, V2).getValue(WhichResult);
4499     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4500       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4501                          V1, V2).getValue(WhichResult);
4502     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4503       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4504                          V1, V2).getValue(WhichResult);
4505
4506     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4507       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4508                          V1, V1).getValue(WhichResult);
4509     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4510       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4511                          V1, V1).getValue(WhichResult);
4512     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4513       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4514                          V1, V1).getValue(WhichResult);
4515   }
4516
4517   // If the shuffle is not directly supported and it has 4 elements, use
4518   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4519   unsigned NumElts = VT.getVectorNumElements();
4520   if (NumElts == 4) {
4521     unsigned PFIndexes[4];
4522     for (unsigned i = 0; i != 4; ++i) {
4523       if (ShuffleMask[i] < 0)
4524         PFIndexes[i] = 8;
4525       else
4526         PFIndexes[i] = ShuffleMask[i];
4527     }
4528
4529     // Compute the index in the perfect shuffle table.
4530     unsigned PFTableIndex =
4531       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4532     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4533     unsigned Cost = (PFEntry >> 30);
4534
4535     if (Cost <= 4)
4536       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4537   }
4538
4539   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4540   if (EltSize >= 32) {
4541     // Do the expansion with floating-point types, since that is what the VFP
4542     // registers are defined to use, and since i64 is not legal.
4543     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4544     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4545     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4546     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4547     SmallVector<SDValue, 8> Ops;
4548     for (unsigned i = 0; i < NumElts; ++i) {
4549       if (ShuffleMask[i] < 0)
4550         Ops.push_back(DAG.getUNDEF(EltVT));
4551       else
4552         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4553                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4554                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4555                                                   MVT::i32)));
4556     }
4557     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4558     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4559   }
4560
4561   if (VT == MVT::v8i8) {
4562     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4563     if (NewOp.getNode())
4564       return NewOp;
4565   }
4566
4567   return SDValue();
4568 }
4569
4570 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4571   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4572   SDValue Lane = Op.getOperand(2);
4573   if (!isa<ConstantSDNode>(Lane))
4574     return SDValue();
4575
4576   return Op;
4577 }
4578
4579 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4580   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4581   SDValue Lane = Op.getOperand(1);
4582   if (!isa<ConstantSDNode>(Lane))
4583     return SDValue();
4584
4585   SDValue Vec = Op.getOperand(0);
4586   if (Op.getValueType() == MVT::i32 &&
4587       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4588     DebugLoc dl = Op.getDebugLoc();
4589     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4590   }
4591
4592   return Op;
4593 }
4594
4595 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4596   // The only time a CONCAT_VECTORS operation can have legal types is when
4597   // two 64-bit vectors are concatenated to a 128-bit vector.
4598   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4599          "unexpected CONCAT_VECTORS");
4600   DebugLoc dl = Op.getDebugLoc();
4601   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4602   SDValue Op0 = Op.getOperand(0);
4603   SDValue Op1 = Op.getOperand(1);
4604   if (Op0.getOpcode() != ISD::UNDEF)
4605     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4606                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4607                       DAG.getIntPtrConstant(0));
4608   if (Op1.getOpcode() != ISD::UNDEF)
4609     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4610                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4611                       DAG.getIntPtrConstant(1));
4612   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4613 }
4614
4615 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4616 /// element has been zero/sign-extended, depending on the isSigned parameter,
4617 /// from an integer type half its size.
4618 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4619                                    bool isSigned) {
4620   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4621   EVT VT = N->getValueType(0);
4622   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4623     SDNode *BVN = N->getOperand(0).getNode();
4624     if (BVN->getValueType(0) != MVT::v4i32 ||
4625         BVN->getOpcode() != ISD::BUILD_VECTOR)
4626       return false;
4627     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4628     unsigned HiElt = 1 - LoElt;
4629     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4630     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4631     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4632     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4633     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4634       return false;
4635     if (isSigned) {
4636       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4637           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4638         return true;
4639     } else {
4640       if (Hi0->isNullValue() && Hi1->isNullValue())
4641         return true;
4642     }
4643     return false;
4644   }
4645
4646   if (N->getOpcode() != ISD::BUILD_VECTOR)
4647     return false;
4648
4649   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4650     SDNode *Elt = N->getOperand(i).getNode();
4651     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4652       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4653       unsigned HalfSize = EltSize / 2;
4654       if (isSigned) {
4655         if (!isIntN(HalfSize, C->getSExtValue()))
4656           return false;
4657       } else {
4658         if (!isUIntN(HalfSize, C->getZExtValue()))
4659           return false;
4660       }
4661       continue;
4662     }
4663     return false;
4664   }
4665
4666   return true;
4667 }
4668
4669 /// isSignExtended - Check if a node is a vector value that is sign-extended
4670 /// or a constant BUILD_VECTOR with sign-extended elements.
4671 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4672   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4673     return true;
4674   if (isExtendedBUILD_VECTOR(N, DAG, true))
4675     return true;
4676   return false;
4677 }
4678
4679 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4680 /// or a constant BUILD_VECTOR with zero-extended elements.
4681 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4682   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4683     return true;
4684   if (isExtendedBUILD_VECTOR(N, DAG, false))
4685     return true;
4686   return false;
4687 }
4688
4689 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4690 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4691 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4692   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4693     return N->getOperand(0);
4694   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4695     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4696                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4697                        LD->isNonTemporal(), LD->isInvariant(),
4698                        LD->getAlignment());
4699   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4700   // have been legalized as a BITCAST from v4i32.
4701   if (N->getOpcode() == ISD::BITCAST) {
4702     SDNode *BVN = N->getOperand(0).getNode();
4703     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4704            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4705     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4706     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4707                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4708   }
4709   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4710   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4711   EVT VT = N->getValueType(0);
4712   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4713   unsigned NumElts = VT.getVectorNumElements();
4714   MVT TruncVT = MVT::getIntegerVT(EltSize);
4715   SmallVector<SDValue, 8> Ops;
4716   for (unsigned i = 0; i != NumElts; ++i) {
4717     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4718     const APInt &CInt = C->getAPIntValue();
4719     Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4720   }
4721   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4722                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4723 }
4724
4725 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4726   unsigned Opcode = N->getOpcode();
4727   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4728     SDNode *N0 = N->getOperand(0).getNode();
4729     SDNode *N1 = N->getOperand(1).getNode();
4730     return N0->hasOneUse() && N1->hasOneUse() &&
4731       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4732   }
4733   return false;
4734 }
4735
4736 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4737   unsigned Opcode = N->getOpcode();
4738   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4739     SDNode *N0 = N->getOperand(0).getNode();
4740     SDNode *N1 = N->getOperand(1).getNode();
4741     return N0->hasOneUse() && N1->hasOneUse() &&
4742       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4743   }
4744   return false;
4745 }
4746
4747 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4748   // Multiplications are only custom-lowered for 128-bit vectors so that
4749   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4750   EVT VT = Op.getValueType();
4751   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4752   SDNode *N0 = Op.getOperand(0).getNode();
4753   SDNode *N1 = Op.getOperand(1).getNode();
4754   unsigned NewOpc = 0;
4755   bool isMLA = false;
4756   bool isN0SExt = isSignExtended(N0, DAG);
4757   bool isN1SExt = isSignExtended(N1, DAG);
4758   if (isN0SExt && isN1SExt)
4759     NewOpc = ARMISD::VMULLs;
4760   else {
4761     bool isN0ZExt = isZeroExtended(N0, DAG);
4762     bool isN1ZExt = isZeroExtended(N1, DAG);
4763     if (isN0ZExt && isN1ZExt)
4764       NewOpc = ARMISD::VMULLu;
4765     else if (isN1SExt || isN1ZExt) {
4766       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4767       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4768       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4769         NewOpc = ARMISD::VMULLs;
4770         isMLA = true;
4771       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4772         NewOpc = ARMISD::VMULLu;
4773         isMLA = true;
4774       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4775         std::swap(N0, N1);
4776         NewOpc = ARMISD::VMULLu;
4777         isMLA = true;
4778       }
4779     }
4780
4781     if (!NewOpc) {
4782       if (VT == MVT::v2i64)
4783         // Fall through to expand this.  It is not legal.
4784         return SDValue();
4785       else
4786         // Other vector multiplications are legal.
4787         return Op;
4788     }
4789   }
4790
4791   // Legalize to a VMULL instruction.
4792   DebugLoc DL = Op.getDebugLoc();
4793   SDValue Op0;
4794   SDValue Op1 = SkipExtension(N1, DAG);
4795   if (!isMLA) {
4796     Op0 = SkipExtension(N0, DAG);
4797     assert(Op0.getValueType().is64BitVector() &&
4798            Op1.getValueType().is64BitVector() &&
4799            "unexpected types for extended operands to VMULL");
4800     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4801   }
4802
4803   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4804   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4805   //   vmull q0, d4, d6
4806   //   vmlal q0, d5, d6
4807   // is faster than
4808   //   vaddl q0, d4, d5
4809   //   vmovl q1, d6
4810   //   vmul  q0, q0, q1
4811   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4812   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4813   EVT Op1VT = Op1.getValueType();
4814   return DAG.getNode(N0->getOpcode(), DL, VT,
4815                      DAG.getNode(NewOpc, DL, VT,
4816                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4817                      DAG.getNode(NewOpc, DL, VT,
4818                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4819 }
4820
4821 static SDValue
4822 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4823   // Convert to float
4824   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4825   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4826   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4827   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4828   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4829   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4830   // Get reciprocal estimate.
4831   // float4 recip = vrecpeq_f32(yf);
4832   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4833                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4834   // Because char has a smaller range than uchar, we can actually get away
4835   // without any newton steps.  This requires that we use a weird bias
4836   // of 0xb000, however (again, this has been exhaustively tested).
4837   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4838   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4839   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4840   Y = DAG.getConstant(0xb000, MVT::i32);
4841   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4842   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4843   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4844   // Convert back to short.
4845   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4846   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4847   return X;
4848 }
4849
4850 static SDValue
4851 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4852   SDValue N2;
4853   // Convert to float.
4854   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4855   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4856   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4857   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4858   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4859   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4860
4861   // Use reciprocal estimate and one refinement step.
4862   // float4 recip = vrecpeq_f32(yf);
4863   // recip *= vrecpsq_f32(yf, recip);
4864   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4865                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4866   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4867                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4868                    N1, N2);
4869   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4870   // Because short has a smaller range than ushort, we can actually get away
4871   // with only a single newton step.  This requires that we use a weird bias
4872   // of 89, however (again, this has been exhaustively tested).
4873   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4874   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4875   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4876   N1 = DAG.getConstant(0x89, MVT::i32);
4877   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4878   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4879   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4880   // Convert back to integer and return.
4881   // return vmovn_s32(vcvt_s32_f32(result));
4882   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4883   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4884   return N0;
4885 }
4886
4887 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4888   EVT VT = Op.getValueType();
4889   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4890          "unexpected type for custom-lowering ISD::SDIV");
4891
4892   DebugLoc dl = Op.getDebugLoc();
4893   SDValue N0 = Op.getOperand(0);
4894   SDValue N1 = Op.getOperand(1);
4895   SDValue N2, N3;
4896
4897   if (VT == MVT::v8i8) {
4898     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4899     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4900
4901     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4902                      DAG.getIntPtrConstant(4));
4903     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4904                      DAG.getIntPtrConstant(4));
4905     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4906                      DAG.getIntPtrConstant(0));
4907     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4908                      DAG.getIntPtrConstant(0));
4909
4910     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4911     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4912
4913     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4914     N0 = LowerCONCAT_VECTORS(N0, DAG);
4915
4916     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4917     return N0;
4918   }
4919   return LowerSDIV_v4i16(N0, N1, dl, DAG);
4920 }
4921
4922 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4923   EVT VT = Op.getValueType();
4924   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4925          "unexpected type for custom-lowering ISD::UDIV");
4926
4927   DebugLoc dl = Op.getDebugLoc();
4928   SDValue N0 = Op.getOperand(0);
4929   SDValue N1 = Op.getOperand(1);
4930   SDValue N2, N3;
4931
4932   if (VT == MVT::v8i8) {
4933     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4934     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4935
4936     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4937                      DAG.getIntPtrConstant(4));
4938     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4939                      DAG.getIntPtrConstant(4));
4940     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4941                      DAG.getIntPtrConstant(0));
4942     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4943                      DAG.getIntPtrConstant(0));
4944
4945     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4946     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4947
4948     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4949     N0 = LowerCONCAT_VECTORS(N0, DAG);
4950
4951     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4952                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4953                      N0);
4954     return N0;
4955   }
4956
4957   // v4i16 sdiv ... Convert to float.
4958   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4959   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4960   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4961   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4962   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4963   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4964
4965   // Use reciprocal estimate and two refinement steps.
4966   // float4 recip = vrecpeq_f32(yf);
4967   // recip *= vrecpsq_f32(yf, recip);
4968   // recip *= vrecpsq_f32(yf, recip);
4969   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4970                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
4971   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4972                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4973                    BN1, N2);
4974   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4975   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4976                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4977                    BN1, N2);
4978   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4979   // Simply multiplying by the reciprocal estimate can leave us a few ulps
4980   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
4981   // and that it will never cause us to return an answer too large).
4982   // float4 result = as_float4(as_int4(xf*recip) + 2);
4983   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4984   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4985   N1 = DAG.getConstant(2, MVT::i32);
4986   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4987   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4988   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4989   // Convert back to integer and return.
4990   // return vmovn_u32(vcvt_s32_f32(result));
4991   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4992   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4993   return N0;
4994 }
4995
4996 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
4997   EVT VT = Op.getNode()->getValueType(0);
4998   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4999
5000   unsigned Opc;
5001   bool ExtraOp = false;
5002   switch (Op.getOpcode()) {
5003   default: llvm_unreachable("Invalid code");
5004   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5005   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5006   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5007   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5008   }
5009
5010   if (!ExtraOp)
5011     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5012                        Op.getOperand(1));
5013   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5014                      Op.getOperand(1), Op.getOperand(2));
5015 }
5016
5017 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5018   // Monotonic load/store is legal for all targets
5019   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5020     return Op;
5021
5022   // Aquire/Release load/store is not legal for targets without a
5023   // dmb or equivalent available.
5024   return SDValue();
5025 }
5026
5027
5028 static void
5029 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5030                     SelectionDAG &DAG, unsigned NewOp) {
5031   DebugLoc dl = Node->getDebugLoc();
5032   assert (Node->getValueType(0) == MVT::i64 &&
5033           "Only know how to expand i64 atomics");
5034
5035   SmallVector<SDValue, 6> Ops;
5036   Ops.push_back(Node->getOperand(0)); // Chain
5037   Ops.push_back(Node->getOperand(1)); // Ptr
5038   // Low part of Val1
5039   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5040                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5041   // High part of Val1
5042   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5043                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5044   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5045     // High part of Val1
5046     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5047                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5048     // High part of Val2
5049     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5050                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5051   }
5052   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5053   SDValue Result =
5054     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5055                             cast<MemSDNode>(Node)->getMemOperand());
5056   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5057   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5058   Results.push_back(Result.getValue(2));
5059 }
5060
5061 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5062   switch (Op.getOpcode()) {
5063   default: llvm_unreachable("Don't know how to custom lower this!");
5064   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5065   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5066   case ISD::GlobalAddress:
5067     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5068       LowerGlobalAddressELF(Op, DAG);
5069   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5070   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5071   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5072   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5073   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5074   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5075   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5076   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5077   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5078   case ISD::SINT_TO_FP:
5079   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5080   case ISD::FP_TO_SINT:
5081   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5082   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5083   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5084   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5085   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5086   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5087   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5088   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5089                                                                Subtarget);
5090   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5091   case ISD::SHL:
5092   case ISD::SRL:
5093   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5094   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5095   case ISD::SRL_PARTS:
5096   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5097   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5098   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5099   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5100   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5101   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5102   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5103   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5104   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5105   case ISD::MUL:           return LowerMUL(Op, DAG);
5106   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5107   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5108   case ISD::ADDC:
5109   case ISD::ADDE:
5110   case ISD::SUBC:
5111   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5112   case ISD::ATOMIC_LOAD:
5113   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5114   }
5115 }
5116
5117 /// ReplaceNodeResults - Replace the results of node with an illegal result
5118 /// type with new values built out of custom code.
5119 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5120                                            SmallVectorImpl<SDValue>&Results,
5121                                            SelectionDAG &DAG) const {
5122   SDValue Res;
5123   switch (N->getOpcode()) {
5124   default:
5125     llvm_unreachable("Don't know how to custom expand this!");
5126   case ISD::BITCAST:
5127     Res = ExpandBITCAST(N, DAG);
5128     break;
5129   case ISD::SRL:
5130   case ISD::SRA:
5131     Res = Expand64BitShift(N, DAG, Subtarget);
5132     break;
5133   case ISD::ATOMIC_LOAD_ADD:
5134     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5135     return;
5136   case ISD::ATOMIC_LOAD_AND:
5137     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5138     return;
5139   case ISD::ATOMIC_LOAD_NAND:
5140     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5141     return;
5142   case ISD::ATOMIC_LOAD_OR:
5143     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5144     return;
5145   case ISD::ATOMIC_LOAD_SUB:
5146     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5147     return;
5148   case ISD::ATOMIC_LOAD_XOR:
5149     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5150     return;
5151   case ISD::ATOMIC_SWAP:
5152     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5153     return;
5154   case ISD::ATOMIC_CMP_SWAP:
5155     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5156     return;
5157   }
5158   if (Res.getNode())
5159     Results.push_back(Res);
5160 }
5161
5162 //===----------------------------------------------------------------------===//
5163 //                           ARM Scheduler Hooks
5164 //===----------------------------------------------------------------------===//
5165
5166 MachineBasicBlock *
5167 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5168                                      MachineBasicBlock *BB,
5169                                      unsigned Size) const {
5170   unsigned dest    = MI->getOperand(0).getReg();
5171   unsigned ptr     = MI->getOperand(1).getReg();
5172   unsigned oldval  = MI->getOperand(2).getReg();
5173   unsigned newval  = MI->getOperand(3).getReg();
5174   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5175   DebugLoc dl = MI->getDebugLoc();
5176   bool isThumb2 = Subtarget->isThumb2();
5177
5178   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5179   unsigned scratch =
5180     MRI.createVirtualRegister(isThumb2 ? ARM::rGPRRegisterClass
5181                                        : ARM::GPRRegisterClass);
5182
5183   if (isThumb2) {
5184     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5185     MRI.constrainRegClass(oldval, ARM::rGPRRegisterClass);
5186     MRI.constrainRegClass(newval, ARM::rGPRRegisterClass);
5187   }
5188
5189   unsigned ldrOpc, strOpc;
5190   switch (Size) {
5191   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5192   case 1:
5193     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5194     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5195     break;
5196   case 2:
5197     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5198     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5199     break;
5200   case 4:
5201     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5202     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5203     break;
5204   }
5205
5206   MachineFunction *MF = BB->getParent();
5207   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5208   MachineFunction::iterator It = BB;
5209   ++It; // insert the new blocks after the current block
5210
5211   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5212   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5213   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5214   MF->insert(It, loop1MBB);
5215   MF->insert(It, loop2MBB);
5216   MF->insert(It, exitMBB);
5217
5218   // Transfer the remainder of BB and its successor edges to exitMBB.
5219   exitMBB->splice(exitMBB->begin(), BB,
5220                   llvm::next(MachineBasicBlock::iterator(MI)),
5221                   BB->end());
5222   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5223
5224   //  thisMBB:
5225   //   ...
5226   //   fallthrough --> loop1MBB
5227   BB->addSuccessor(loop1MBB);
5228
5229   // loop1MBB:
5230   //   ldrex dest, [ptr]
5231   //   cmp dest, oldval
5232   //   bne exitMBB
5233   BB = loop1MBB;
5234   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5235   if (ldrOpc == ARM::t2LDREX)
5236     MIB.addImm(0);
5237   AddDefaultPred(MIB);
5238   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5239                  .addReg(dest).addReg(oldval));
5240   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5241     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5242   BB->addSuccessor(loop2MBB);
5243   BB->addSuccessor(exitMBB);
5244
5245   // loop2MBB:
5246   //   strex scratch, newval, [ptr]
5247   //   cmp scratch, #0
5248   //   bne loop1MBB
5249   BB = loop2MBB;
5250   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5251   if (strOpc == ARM::t2STREX)
5252     MIB.addImm(0);
5253   AddDefaultPred(MIB);
5254   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5255                  .addReg(scratch).addImm(0));
5256   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5257     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5258   BB->addSuccessor(loop1MBB);
5259   BB->addSuccessor(exitMBB);
5260
5261   //  exitMBB:
5262   //   ...
5263   BB = exitMBB;
5264
5265   MI->eraseFromParent();   // The instruction is gone now.
5266
5267   return BB;
5268 }
5269
5270 MachineBasicBlock *
5271 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5272                                     unsigned Size, unsigned BinOpcode) const {
5273   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5274   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5275
5276   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5277   MachineFunction *MF = BB->getParent();
5278   MachineFunction::iterator It = BB;
5279   ++It;
5280
5281   unsigned dest = MI->getOperand(0).getReg();
5282   unsigned ptr = MI->getOperand(1).getReg();
5283   unsigned incr = MI->getOperand(2).getReg();
5284   DebugLoc dl = MI->getDebugLoc();
5285   bool isThumb2 = Subtarget->isThumb2();
5286
5287   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5288   if (isThumb2) {
5289     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5290     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5291   }
5292
5293   unsigned ldrOpc, strOpc;
5294   switch (Size) {
5295   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5296   case 1:
5297     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5298     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5299     break;
5300   case 2:
5301     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5302     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5303     break;
5304   case 4:
5305     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5306     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5307     break;
5308   }
5309
5310   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5311   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5312   MF->insert(It, loopMBB);
5313   MF->insert(It, exitMBB);
5314
5315   // Transfer the remainder of BB and its successor edges to exitMBB.
5316   exitMBB->splice(exitMBB->begin(), BB,
5317                   llvm::next(MachineBasicBlock::iterator(MI)),
5318                   BB->end());
5319   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5320
5321   const TargetRegisterClass *TRC =
5322     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5323   unsigned scratch = MRI.createVirtualRegister(TRC);
5324   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5325
5326   //  thisMBB:
5327   //   ...
5328   //   fallthrough --> loopMBB
5329   BB->addSuccessor(loopMBB);
5330
5331   //  loopMBB:
5332   //   ldrex dest, ptr
5333   //   <binop> scratch2, dest, incr
5334   //   strex scratch, scratch2, ptr
5335   //   cmp scratch, #0
5336   //   bne- loopMBB
5337   //   fallthrough --> exitMBB
5338   BB = loopMBB;
5339   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5340   if (ldrOpc == ARM::t2LDREX)
5341     MIB.addImm(0);
5342   AddDefaultPred(MIB);
5343   if (BinOpcode) {
5344     // operand order needs to go the other way for NAND
5345     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5346       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5347                      addReg(incr).addReg(dest)).addReg(0);
5348     else
5349       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5350                      addReg(dest).addReg(incr)).addReg(0);
5351   }
5352
5353   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5354   if (strOpc == ARM::t2STREX)
5355     MIB.addImm(0);
5356   AddDefaultPred(MIB);
5357   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5358                  .addReg(scratch).addImm(0));
5359   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5360     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5361
5362   BB->addSuccessor(loopMBB);
5363   BB->addSuccessor(exitMBB);
5364
5365   //  exitMBB:
5366   //   ...
5367   BB = exitMBB;
5368
5369   MI->eraseFromParent();   // The instruction is gone now.
5370
5371   return BB;
5372 }
5373
5374 MachineBasicBlock *
5375 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5376                                           MachineBasicBlock *BB,
5377                                           unsigned Size,
5378                                           bool signExtend,
5379                                           ARMCC::CondCodes Cond) const {
5380   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5381
5382   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5383   MachineFunction *MF = BB->getParent();
5384   MachineFunction::iterator It = BB;
5385   ++It;
5386
5387   unsigned dest = MI->getOperand(0).getReg();
5388   unsigned ptr = MI->getOperand(1).getReg();
5389   unsigned incr = MI->getOperand(2).getReg();
5390   unsigned oldval = dest;
5391   DebugLoc dl = MI->getDebugLoc();
5392   bool isThumb2 = Subtarget->isThumb2();
5393
5394   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5395   if (isThumb2) {
5396     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5397     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5398   }
5399
5400   unsigned ldrOpc, strOpc, extendOpc;
5401   switch (Size) {
5402   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5403   case 1:
5404     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5405     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5406     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5407     break;
5408   case 2:
5409     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5410     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5411     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5412     break;
5413   case 4:
5414     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5415     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5416     extendOpc = 0;
5417     break;
5418   }
5419
5420   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5421   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5422   MF->insert(It, loopMBB);
5423   MF->insert(It, exitMBB);
5424
5425   // Transfer the remainder of BB and its successor edges to exitMBB.
5426   exitMBB->splice(exitMBB->begin(), BB,
5427                   llvm::next(MachineBasicBlock::iterator(MI)),
5428                   BB->end());
5429   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5430
5431   const TargetRegisterClass *TRC =
5432     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5433   unsigned scratch = MRI.createVirtualRegister(TRC);
5434   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5435
5436   //  thisMBB:
5437   //   ...
5438   //   fallthrough --> loopMBB
5439   BB->addSuccessor(loopMBB);
5440
5441   //  loopMBB:
5442   //   ldrex dest, ptr
5443   //   (sign extend dest, if required)
5444   //   cmp dest, incr
5445   //   cmov.cond scratch2, dest, incr
5446   //   strex scratch, scratch2, ptr
5447   //   cmp scratch, #0
5448   //   bne- loopMBB
5449   //   fallthrough --> exitMBB
5450   BB = loopMBB;
5451   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5452   if (ldrOpc == ARM::t2LDREX)
5453     MIB.addImm(0);
5454   AddDefaultPred(MIB);
5455
5456   // Sign extend the value, if necessary.
5457   if (signExtend && extendOpc) {
5458     oldval = MRI.createVirtualRegister(ARM::GPRRegisterClass);
5459     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5460                      .addReg(dest)
5461                      .addImm(0));
5462   }
5463
5464   // Build compare and cmov instructions.
5465   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5466                  .addReg(oldval).addReg(incr));
5467   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5468          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5469
5470   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5471   if (strOpc == ARM::t2STREX)
5472     MIB.addImm(0);
5473   AddDefaultPred(MIB);
5474   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5475                  .addReg(scratch).addImm(0));
5476   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5477     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5478
5479   BB->addSuccessor(loopMBB);
5480   BB->addSuccessor(exitMBB);
5481
5482   //  exitMBB:
5483   //   ...
5484   BB = exitMBB;
5485
5486   MI->eraseFromParent();   // The instruction is gone now.
5487
5488   return BB;
5489 }
5490
5491 MachineBasicBlock *
5492 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5493                                       unsigned Op1, unsigned Op2,
5494                                       bool NeedsCarry, bool IsCmpxchg) const {
5495   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5496   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5497
5498   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5499   MachineFunction *MF = BB->getParent();
5500   MachineFunction::iterator It = BB;
5501   ++It;
5502
5503   unsigned destlo = MI->getOperand(0).getReg();
5504   unsigned desthi = MI->getOperand(1).getReg();
5505   unsigned ptr = MI->getOperand(2).getReg();
5506   unsigned vallo = MI->getOperand(3).getReg();
5507   unsigned valhi = MI->getOperand(4).getReg();
5508   DebugLoc dl = MI->getDebugLoc();
5509   bool isThumb2 = Subtarget->isThumb2();
5510
5511   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5512   if (isThumb2) {
5513     MRI.constrainRegClass(destlo, ARM::rGPRRegisterClass);
5514     MRI.constrainRegClass(desthi, ARM::rGPRRegisterClass);
5515     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5516   }
5517
5518   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5519   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5520
5521   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5522   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5523   if (IsCmpxchg) {
5524     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5525     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5526   }
5527   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5528   MF->insert(It, loopMBB);
5529   if (IsCmpxchg) {
5530     MF->insert(It, contBB);
5531     MF->insert(It, cont2BB);
5532   }
5533   MF->insert(It, exitMBB);
5534
5535   // Transfer the remainder of BB and its successor edges to exitMBB.
5536   exitMBB->splice(exitMBB->begin(), BB,
5537                   llvm::next(MachineBasicBlock::iterator(MI)),
5538                   BB->end());
5539   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5540
5541   const TargetRegisterClass *TRC =
5542     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5543   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5544
5545   //  thisMBB:
5546   //   ...
5547   //   fallthrough --> loopMBB
5548   BB->addSuccessor(loopMBB);
5549
5550   //  loopMBB:
5551   //   ldrexd r2, r3, ptr
5552   //   <binopa> r0, r2, incr
5553   //   <binopb> r1, r3, incr
5554   //   strexd storesuccess, r0, r1, ptr
5555   //   cmp storesuccess, #0
5556   //   bne- loopMBB
5557   //   fallthrough --> exitMBB
5558   //
5559   // Note that the registers are explicitly specified because there is not any
5560   // way to force the register allocator to allocate a register pair.
5561   //
5562   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5563   // need to properly enforce the restriction that the two output registers
5564   // for ldrexd must be different.
5565   BB = loopMBB;
5566   // Load
5567   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5568                  .addReg(ARM::R2, RegState::Define)
5569                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5570   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5571   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5572   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5573
5574   if (IsCmpxchg) {
5575     // Add early exit
5576     for (unsigned i = 0; i < 2; i++) {
5577       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5578                                                          ARM::CMPrr))
5579                      .addReg(i == 0 ? destlo : desthi)
5580                      .addReg(i == 0 ? vallo : valhi));
5581       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5582         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5583       BB->addSuccessor(exitMBB);
5584       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5585       BB = (i == 0 ? contBB : cont2BB);
5586     }
5587
5588     // Copy to physregs for strexd
5589     unsigned setlo = MI->getOperand(5).getReg();
5590     unsigned sethi = MI->getOperand(6).getReg();
5591     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5592     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5593   } else if (Op1) {
5594     // Perform binary operation
5595     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5596                    .addReg(destlo).addReg(vallo))
5597         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5598     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5599                    .addReg(desthi).addReg(valhi)).addReg(0);
5600   } else {
5601     // Copy to physregs for strexd
5602     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5603     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5604   }
5605
5606   // Store
5607   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5608                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5609   // Cmp+jump
5610   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5611                  .addReg(storesuccess).addImm(0));
5612   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5613     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5614
5615   BB->addSuccessor(loopMBB);
5616   BB->addSuccessor(exitMBB);
5617
5618   //  exitMBB:
5619   //   ...
5620   BB = exitMBB;
5621
5622   MI->eraseFromParent();   // The instruction is gone now.
5623
5624   return BB;
5625 }
5626
5627 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5628 /// registers the function context.
5629 void ARMTargetLowering::
5630 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5631                        MachineBasicBlock *DispatchBB, int FI) const {
5632   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5633   DebugLoc dl = MI->getDebugLoc();
5634   MachineFunction *MF = MBB->getParent();
5635   MachineRegisterInfo *MRI = &MF->getRegInfo();
5636   MachineConstantPool *MCP = MF->getConstantPool();
5637   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5638   const Function *F = MF->getFunction();
5639
5640   bool isThumb = Subtarget->isThumb();
5641   bool isThumb2 = Subtarget->isThumb2();
5642
5643   unsigned PCLabelId = AFI->createPICLabelUId();
5644   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5645   ARMConstantPoolValue *CPV =
5646     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5647   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5648
5649   const TargetRegisterClass *TRC =
5650     isThumb ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5651
5652   // Grab constant pool and fixed stack memory operands.
5653   MachineMemOperand *CPMMO =
5654     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5655                              MachineMemOperand::MOLoad, 4, 4);
5656
5657   MachineMemOperand *FIMMOSt =
5658     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5659                              MachineMemOperand::MOStore, 4, 4);
5660
5661   // Load the address of the dispatch MBB into the jump buffer.
5662   if (isThumb2) {
5663     // Incoming value: jbuf
5664     //   ldr.n  r5, LCPI1_1
5665     //   orr    r5, r5, #1
5666     //   add    r5, pc
5667     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5668     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5669     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5670                    .addConstantPoolIndex(CPI)
5671                    .addMemOperand(CPMMO));
5672     // Set the low bit because of thumb mode.
5673     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5674     AddDefaultCC(
5675       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5676                      .addReg(NewVReg1, RegState::Kill)
5677                      .addImm(0x01)));
5678     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5679     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5680       .addReg(NewVReg2, RegState::Kill)
5681       .addImm(PCLabelId);
5682     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5683                    .addReg(NewVReg3, RegState::Kill)
5684                    .addFrameIndex(FI)
5685                    .addImm(36)  // &jbuf[1] :: pc
5686                    .addMemOperand(FIMMOSt));
5687   } else if (isThumb) {
5688     // Incoming value: jbuf
5689     //   ldr.n  r1, LCPI1_4
5690     //   add    r1, pc
5691     //   mov    r2, #1
5692     //   orrs   r1, r2
5693     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5694     //   str    r1, [r2]
5695     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5696     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5697                    .addConstantPoolIndex(CPI)
5698                    .addMemOperand(CPMMO));
5699     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5700     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5701       .addReg(NewVReg1, RegState::Kill)
5702       .addImm(PCLabelId);
5703     // Set the low bit because of thumb mode.
5704     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5705     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5706                    .addReg(ARM::CPSR, RegState::Define)
5707                    .addImm(1));
5708     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5709     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5710                    .addReg(ARM::CPSR, RegState::Define)
5711                    .addReg(NewVReg2, RegState::Kill)
5712                    .addReg(NewVReg3, RegState::Kill));
5713     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5714     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5715                    .addFrameIndex(FI)
5716                    .addImm(36)); // &jbuf[1] :: pc
5717     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5718                    .addReg(NewVReg4, RegState::Kill)
5719                    .addReg(NewVReg5, RegState::Kill)
5720                    .addImm(0)
5721                    .addMemOperand(FIMMOSt));
5722   } else {
5723     // Incoming value: jbuf
5724     //   ldr  r1, LCPI1_1
5725     //   add  r1, pc, r1
5726     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5727     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5728     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5729                    .addConstantPoolIndex(CPI)
5730                    .addImm(0)
5731                    .addMemOperand(CPMMO));
5732     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5733     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5734                    .addReg(NewVReg1, RegState::Kill)
5735                    .addImm(PCLabelId));
5736     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5737                    .addReg(NewVReg2, RegState::Kill)
5738                    .addFrameIndex(FI)
5739                    .addImm(36)  // &jbuf[1] :: pc
5740                    .addMemOperand(FIMMOSt));
5741   }
5742 }
5743
5744 MachineBasicBlock *ARMTargetLowering::
5745 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5746   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5747   DebugLoc dl = MI->getDebugLoc();
5748   MachineFunction *MF = MBB->getParent();
5749   MachineRegisterInfo *MRI = &MF->getRegInfo();
5750   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5751   MachineFrameInfo *MFI = MF->getFrameInfo();
5752   int FI = MFI->getFunctionContextIndex();
5753
5754   const TargetRegisterClass *TRC =
5755     Subtarget->isThumb() ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5756
5757   // Get a mapping of the call site numbers to all of the landing pads they're
5758   // associated with.
5759   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5760   unsigned MaxCSNum = 0;
5761   MachineModuleInfo &MMI = MF->getMMI();
5762   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; ++BB) {
5763     if (!BB->isLandingPad()) continue;
5764
5765     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5766     // pad.
5767     for (MachineBasicBlock::iterator
5768            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5769       if (!II->isEHLabel()) continue;
5770
5771       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5772       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5773
5774       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5775       for (SmallVectorImpl<unsigned>::iterator
5776              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5777            CSI != CSE; ++CSI) {
5778         CallSiteNumToLPad[*CSI].push_back(BB);
5779         MaxCSNum = std::max(MaxCSNum, *CSI);
5780       }
5781       break;
5782     }
5783   }
5784
5785   // Get an ordered list of the machine basic blocks for the jump table.
5786   std::vector<MachineBasicBlock*> LPadList;
5787   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5788   LPadList.reserve(CallSiteNumToLPad.size());
5789   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5790     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5791     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5792            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5793       LPadList.push_back(*II);
5794       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5795     }
5796   }
5797
5798   assert(!LPadList.empty() &&
5799          "No landing pad destinations for the dispatch jump table!");
5800
5801   // Create the jump table and associated information.
5802   MachineJumpTableInfo *JTI =
5803     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5804   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5805   unsigned UId = AFI->createJumpTableUId();
5806
5807   // Create the MBBs for the dispatch code.
5808
5809   // Shove the dispatch's address into the return slot in the function context.
5810   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5811   DispatchBB->setIsLandingPad();
5812
5813   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5814   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5815   DispatchBB->addSuccessor(TrapBB);
5816
5817   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5818   DispatchBB->addSuccessor(DispContBB);
5819
5820   // Insert and MBBs.
5821   MF->insert(MF->end(), DispatchBB);
5822   MF->insert(MF->end(), DispContBB);
5823   MF->insert(MF->end(), TrapBB);
5824
5825   // Insert code into the entry block that creates and registers the function
5826   // context.
5827   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5828
5829   MachineMemOperand *FIMMOLd =
5830     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5831                              MachineMemOperand::MOLoad |
5832                              MachineMemOperand::MOVolatile, 4, 4);
5833
5834   if (AFI->isThumb1OnlyFunction())
5835     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5836   else if (!Subtarget->hasVFP2())
5837     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5838   else 
5839     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5840
5841   unsigned NumLPads = LPadList.size();
5842   if (Subtarget->isThumb2()) {
5843     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5844     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5845                    .addFrameIndex(FI)
5846                    .addImm(4)
5847                    .addMemOperand(FIMMOLd));
5848
5849     if (NumLPads < 256) {
5850       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5851                      .addReg(NewVReg1)
5852                      .addImm(LPadList.size()));
5853     } else {
5854       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5855       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5856                      .addImm(NumLPads & 0xFFFF));
5857
5858       unsigned VReg2 = VReg1;
5859       if ((NumLPads & 0xFFFF0000) != 0) {
5860         VReg2 = MRI->createVirtualRegister(TRC);
5861         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5862                        .addReg(VReg1)
5863                        .addImm(NumLPads >> 16));
5864       }
5865
5866       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5867                      .addReg(NewVReg1)
5868                      .addReg(VReg2));
5869     }
5870
5871     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5872       .addMBB(TrapBB)
5873       .addImm(ARMCC::HI)
5874       .addReg(ARM::CPSR);
5875
5876     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5877     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5878                    .addJumpTableIndex(MJTI)
5879                    .addImm(UId));
5880
5881     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5882     AddDefaultCC(
5883       AddDefaultPred(
5884         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5885         .addReg(NewVReg3, RegState::Kill)
5886         .addReg(NewVReg1)
5887         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5888
5889     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5890       .addReg(NewVReg4, RegState::Kill)
5891       .addReg(NewVReg1)
5892       .addJumpTableIndex(MJTI)
5893       .addImm(UId);
5894   } else if (Subtarget->isThumb()) {
5895     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5896     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
5897                    .addFrameIndex(FI)
5898                    .addImm(1)
5899                    .addMemOperand(FIMMOLd));
5900
5901     if (NumLPads < 256) {
5902       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
5903                      .addReg(NewVReg1)
5904                      .addImm(NumLPads));
5905     } else {
5906       MachineConstantPool *ConstantPool = MF->getConstantPool();
5907       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5908       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5909
5910       // MachineConstantPool wants an explicit alignment.
5911       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
5912       if (Align == 0)
5913         Align = getTargetData()->getTypeAllocSize(C->getType());
5914       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
5915
5916       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5917       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
5918                      .addReg(VReg1, RegState::Define)
5919                      .addConstantPoolIndex(Idx));
5920       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
5921                      .addReg(NewVReg1)
5922                      .addReg(VReg1));
5923     }
5924
5925     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
5926       .addMBB(TrapBB)
5927       .addImm(ARMCC::HI)
5928       .addReg(ARM::CPSR);
5929
5930     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5931     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
5932                    .addReg(ARM::CPSR, RegState::Define)
5933                    .addReg(NewVReg1)
5934                    .addImm(2));
5935
5936     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5937     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
5938                    .addJumpTableIndex(MJTI)
5939                    .addImm(UId));
5940
5941     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5942     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
5943                    .addReg(ARM::CPSR, RegState::Define)
5944                    .addReg(NewVReg2, RegState::Kill)
5945                    .addReg(NewVReg3));
5946
5947     MachineMemOperand *JTMMOLd =
5948       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
5949                                MachineMemOperand::MOLoad, 4, 4);
5950
5951     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5952     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
5953                    .addReg(NewVReg4, RegState::Kill)
5954                    .addImm(0)
5955                    .addMemOperand(JTMMOLd));
5956
5957     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
5958     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
5959                    .addReg(ARM::CPSR, RegState::Define)
5960                    .addReg(NewVReg5, RegState::Kill)
5961                    .addReg(NewVReg3));
5962
5963     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
5964       .addReg(NewVReg6, RegState::Kill)
5965       .addJumpTableIndex(MJTI)
5966       .addImm(UId);
5967   } else {
5968     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5969     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
5970                    .addFrameIndex(FI)
5971                    .addImm(4)
5972                    .addMemOperand(FIMMOLd));
5973
5974     if (NumLPads < 256) {
5975       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
5976                      .addReg(NewVReg1)
5977                      .addImm(NumLPads));
5978     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
5979       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5980       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
5981                      .addImm(NumLPads & 0xFFFF));
5982
5983       unsigned VReg2 = VReg1;
5984       if ((NumLPads & 0xFFFF0000) != 0) {
5985         VReg2 = MRI->createVirtualRegister(TRC);
5986         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
5987                        .addReg(VReg1)
5988                        .addImm(NumLPads >> 16));
5989       }
5990
5991       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
5992                      .addReg(NewVReg1)
5993                      .addReg(VReg2));
5994     } else {
5995       MachineConstantPool *ConstantPool = MF->getConstantPool();
5996       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5997       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5998
5999       // MachineConstantPool wants an explicit alignment.
6000       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6001       if (Align == 0)
6002         Align = getTargetData()->getTypeAllocSize(C->getType());
6003       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6004
6005       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6006       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6007                      .addReg(VReg1, RegState::Define)
6008                      .addConstantPoolIndex(Idx)
6009                      .addImm(0));
6010       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6011                      .addReg(NewVReg1)
6012                      .addReg(VReg1, RegState::Kill));
6013     }
6014
6015     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6016       .addMBB(TrapBB)
6017       .addImm(ARMCC::HI)
6018       .addReg(ARM::CPSR);
6019
6020     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6021     AddDefaultCC(
6022       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6023                      .addReg(NewVReg1)
6024                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6025     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6026     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6027                    .addJumpTableIndex(MJTI)
6028                    .addImm(UId));
6029
6030     MachineMemOperand *JTMMOLd =
6031       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6032                                MachineMemOperand::MOLoad, 4, 4);
6033     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6034     AddDefaultPred(
6035       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6036       .addReg(NewVReg3, RegState::Kill)
6037       .addReg(NewVReg4)
6038       .addImm(0)
6039       .addMemOperand(JTMMOLd));
6040
6041     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6042       .addReg(NewVReg5, RegState::Kill)
6043       .addReg(NewVReg4)
6044       .addJumpTableIndex(MJTI)
6045       .addImm(UId);
6046   }
6047
6048   // Add the jump table entries as successors to the MBB.
6049   MachineBasicBlock *PrevMBB = 0;
6050   for (std::vector<MachineBasicBlock*>::iterator
6051          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6052     MachineBasicBlock *CurMBB = *I;
6053     if (PrevMBB != CurMBB)
6054       DispContBB->addSuccessor(CurMBB);
6055     PrevMBB = CurMBB;
6056   }
6057
6058   // N.B. the order the invoke BBs are processed in doesn't matter here.
6059   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6060   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6061   const unsigned *SavedRegs = RI.getCalleeSavedRegs(MF);
6062   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6063   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6064          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6065     MachineBasicBlock *BB = *I;
6066
6067     // Remove the landing pad successor from the invoke block and replace it
6068     // with the new dispatch block.
6069     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6070                                                   BB->succ_end());
6071     while (!Successors.empty()) {
6072       MachineBasicBlock *SMBB = Successors.pop_back_val();
6073       if (SMBB->isLandingPad()) {
6074         BB->removeSuccessor(SMBB);
6075         MBBLPads.push_back(SMBB);
6076       }
6077     }
6078
6079     BB->addSuccessor(DispatchBB);
6080
6081     // Find the invoke call and mark all of the callee-saved registers as
6082     // 'implicit defined' so that they're spilled. This prevents code from
6083     // moving instructions to before the EH block, where they will never be
6084     // executed.
6085     for (MachineBasicBlock::reverse_iterator
6086            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6087       if (!II->isCall()) continue;
6088
6089       DenseMap<unsigned, bool> DefRegs;
6090       for (MachineInstr::mop_iterator
6091              OI = II->operands_begin(), OE = II->operands_end();
6092            OI != OE; ++OI) {
6093         if (!OI->isReg()) continue;
6094         DefRegs[OI->getReg()] = true;
6095       }
6096
6097       MachineInstrBuilder MIB(&*II);
6098
6099       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6100         unsigned Reg = SavedRegs[i];
6101         if (Subtarget->isThumb2() &&
6102             !ARM::tGPRRegisterClass->contains(Reg) &&
6103             !ARM::hGPRRegisterClass->contains(Reg))
6104           continue;
6105         else if (Subtarget->isThumb1Only() &&
6106                  !ARM::tGPRRegisterClass->contains(Reg))
6107           continue;
6108         else if (!Subtarget->isThumb() &&
6109                  !ARM::GPRRegisterClass->contains(Reg))
6110           continue;
6111         if (!DefRegs[Reg])
6112           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6113       }
6114
6115       break;
6116     }
6117   }
6118
6119   // Mark all former landing pads as non-landing pads. The dispatch is the only
6120   // landing pad now.
6121   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6122          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6123     (*I)->setIsLandingPad(false);
6124
6125   // The instruction is gone now.
6126   MI->eraseFromParent();
6127
6128   return MBB;
6129 }
6130
6131 static
6132 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6133   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6134        E = MBB->succ_end(); I != E; ++I)
6135     if (*I != Succ)
6136       return *I;
6137   llvm_unreachable("Expecting a BB with two successors!");
6138 }
6139
6140 MachineBasicBlock *
6141 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6142                                                MachineBasicBlock *BB) const {
6143   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6144   DebugLoc dl = MI->getDebugLoc();
6145   bool isThumb2 = Subtarget->isThumb2();
6146   switch (MI->getOpcode()) {
6147   default: {
6148     MI->dump();
6149     llvm_unreachable("Unexpected instr type to insert");
6150   }
6151   // The Thumb2 pre-indexed stores have the same MI operands, they just
6152   // define them differently in the .td files from the isel patterns, so
6153   // they need pseudos.
6154   case ARM::t2STR_preidx:
6155     MI->setDesc(TII->get(ARM::t2STR_PRE));
6156     return BB;
6157   case ARM::t2STRB_preidx:
6158     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6159     return BB;
6160   case ARM::t2STRH_preidx:
6161     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6162     return BB;
6163
6164   case ARM::STRi_preidx:
6165   case ARM::STRBi_preidx: {
6166     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6167       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6168     // Decode the offset.
6169     unsigned Offset = MI->getOperand(4).getImm();
6170     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6171     Offset = ARM_AM::getAM2Offset(Offset);
6172     if (isSub)
6173       Offset = -Offset;
6174
6175     MachineMemOperand *MMO = *MI->memoperands_begin();
6176     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6177       .addOperand(MI->getOperand(0))  // Rn_wb
6178       .addOperand(MI->getOperand(1))  // Rt
6179       .addOperand(MI->getOperand(2))  // Rn
6180       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6181       .addOperand(MI->getOperand(5))  // pred
6182       .addOperand(MI->getOperand(6))
6183       .addMemOperand(MMO);
6184     MI->eraseFromParent();
6185     return BB;
6186   }
6187   case ARM::STRr_preidx:
6188   case ARM::STRBr_preidx:
6189   case ARM::STRH_preidx: {
6190     unsigned NewOpc;
6191     switch (MI->getOpcode()) {
6192     default: llvm_unreachable("unexpected opcode!");
6193     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6194     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6195     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6196     }
6197     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6198     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6199       MIB.addOperand(MI->getOperand(i));
6200     MI->eraseFromParent();
6201     return BB;
6202   }
6203   case ARM::ATOMIC_LOAD_ADD_I8:
6204      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6205   case ARM::ATOMIC_LOAD_ADD_I16:
6206      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6207   case ARM::ATOMIC_LOAD_ADD_I32:
6208      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6209
6210   case ARM::ATOMIC_LOAD_AND_I8:
6211      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6212   case ARM::ATOMIC_LOAD_AND_I16:
6213      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6214   case ARM::ATOMIC_LOAD_AND_I32:
6215      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6216
6217   case ARM::ATOMIC_LOAD_OR_I8:
6218      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6219   case ARM::ATOMIC_LOAD_OR_I16:
6220      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6221   case ARM::ATOMIC_LOAD_OR_I32:
6222      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6223
6224   case ARM::ATOMIC_LOAD_XOR_I8:
6225      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6226   case ARM::ATOMIC_LOAD_XOR_I16:
6227      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6228   case ARM::ATOMIC_LOAD_XOR_I32:
6229      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6230
6231   case ARM::ATOMIC_LOAD_NAND_I8:
6232      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6233   case ARM::ATOMIC_LOAD_NAND_I16:
6234      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6235   case ARM::ATOMIC_LOAD_NAND_I32:
6236      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6237
6238   case ARM::ATOMIC_LOAD_SUB_I8:
6239      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6240   case ARM::ATOMIC_LOAD_SUB_I16:
6241      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6242   case ARM::ATOMIC_LOAD_SUB_I32:
6243      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6244
6245   case ARM::ATOMIC_LOAD_MIN_I8:
6246      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6247   case ARM::ATOMIC_LOAD_MIN_I16:
6248      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6249   case ARM::ATOMIC_LOAD_MIN_I32:
6250      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6251
6252   case ARM::ATOMIC_LOAD_MAX_I8:
6253      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6254   case ARM::ATOMIC_LOAD_MAX_I16:
6255      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6256   case ARM::ATOMIC_LOAD_MAX_I32:
6257      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6258
6259   case ARM::ATOMIC_LOAD_UMIN_I8:
6260      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6261   case ARM::ATOMIC_LOAD_UMIN_I16:
6262      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6263   case ARM::ATOMIC_LOAD_UMIN_I32:
6264      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6265
6266   case ARM::ATOMIC_LOAD_UMAX_I8:
6267      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6268   case ARM::ATOMIC_LOAD_UMAX_I16:
6269      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6270   case ARM::ATOMIC_LOAD_UMAX_I32:
6271      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6272
6273   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6274   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6275   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6276
6277   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6278   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6279   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6280
6281
6282   case ARM::ATOMADD6432:
6283     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6284                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6285                               /*NeedsCarry*/ true);
6286   case ARM::ATOMSUB6432:
6287     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6288                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6289                               /*NeedsCarry*/ true);
6290   case ARM::ATOMOR6432:
6291     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6292                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6293   case ARM::ATOMXOR6432:
6294     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6295                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6296   case ARM::ATOMAND6432:
6297     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6298                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6299   case ARM::ATOMSWAP6432:
6300     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6301   case ARM::ATOMCMPXCHG6432:
6302     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6303                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6304                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6305
6306   case ARM::tMOVCCr_pseudo: {
6307     // To "insert" a SELECT_CC instruction, we actually have to insert the
6308     // diamond control-flow pattern.  The incoming instruction knows the
6309     // destination vreg to set, the condition code register to branch on, the
6310     // true/false values to select between, and a branch opcode to use.
6311     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6312     MachineFunction::iterator It = BB;
6313     ++It;
6314
6315     //  thisMBB:
6316     //  ...
6317     //   TrueVal = ...
6318     //   cmpTY ccX, r1, r2
6319     //   bCC copy1MBB
6320     //   fallthrough --> copy0MBB
6321     MachineBasicBlock *thisMBB  = BB;
6322     MachineFunction *F = BB->getParent();
6323     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6324     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6325     F->insert(It, copy0MBB);
6326     F->insert(It, sinkMBB);
6327
6328     // Transfer the remainder of BB and its successor edges to sinkMBB.
6329     sinkMBB->splice(sinkMBB->begin(), BB,
6330                     llvm::next(MachineBasicBlock::iterator(MI)),
6331                     BB->end());
6332     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6333
6334     BB->addSuccessor(copy0MBB);
6335     BB->addSuccessor(sinkMBB);
6336
6337     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6338       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6339
6340     //  copy0MBB:
6341     //   %FalseValue = ...
6342     //   # fallthrough to sinkMBB
6343     BB = copy0MBB;
6344
6345     // Update machine-CFG edges
6346     BB->addSuccessor(sinkMBB);
6347
6348     //  sinkMBB:
6349     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6350     //  ...
6351     BB = sinkMBB;
6352     BuildMI(*BB, BB->begin(), dl,
6353             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6354       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6355       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6356
6357     MI->eraseFromParent();   // The pseudo instruction is gone now.
6358     return BB;
6359   }
6360
6361   case ARM::BCCi64:
6362   case ARM::BCCZi64: {
6363     // If there is an unconditional branch to the other successor, remove it.
6364     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6365
6366     // Compare both parts that make up the double comparison separately for
6367     // equality.
6368     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6369
6370     unsigned LHS1 = MI->getOperand(1).getReg();
6371     unsigned LHS2 = MI->getOperand(2).getReg();
6372     if (RHSisZero) {
6373       AddDefaultPred(BuildMI(BB, dl,
6374                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6375                      .addReg(LHS1).addImm(0));
6376       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6377         .addReg(LHS2).addImm(0)
6378         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6379     } else {
6380       unsigned RHS1 = MI->getOperand(3).getReg();
6381       unsigned RHS2 = MI->getOperand(4).getReg();
6382       AddDefaultPred(BuildMI(BB, dl,
6383                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6384                      .addReg(LHS1).addReg(RHS1));
6385       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6386         .addReg(LHS2).addReg(RHS2)
6387         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6388     }
6389
6390     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6391     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6392     if (MI->getOperand(0).getImm() == ARMCC::NE)
6393       std::swap(destMBB, exitMBB);
6394
6395     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6396       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6397     if (isThumb2)
6398       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6399     else
6400       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6401
6402     MI->eraseFromParent();   // The pseudo instruction is gone now.
6403     return BB;
6404   }
6405
6406   case ARM::Int_eh_sjlj_setjmp:
6407   case ARM::Int_eh_sjlj_setjmp_nofp:
6408   case ARM::tInt_eh_sjlj_setjmp:
6409   case ARM::t2Int_eh_sjlj_setjmp:
6410   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6411     EmitSjLjDispatchBlock(MI, BB);
6412     return BB;
6413
6414   case ARM::ABS:
6415   case ARM::t2ABS: {
6416     // To insert an ABS instruction, we have to insert the
6417     // diamond control-flow pattern.  The incoming instruction knows the
6418     // source vreg to test against 0, the destination vreg to set,
6419     // the condition code register to branch on, the
6420     // true/false values to select between, and a branch opcode to use.
6421     // It transforms
6422     //     V1 = ABS V0
6423     // into
6424     //     V2 = MOVS V0
6425     //     BCC                      (branch to SinkBB if V0 >= 0)
6426     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6427     //     SinkBB: V1 = PHI(V2, V3)
6428     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6429     MachineFunction::iterator BBI = BB;
6430     ++BBI;
6431     MachineFunction *Fn = BB->getParent();
6432     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6433     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6434     Fn->insert(BBI, RSBBB);
6435     Fn->insert(BBI, SinkBB);
6436
6437     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6438     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6439     bool isThumb2 = Subtarget->isThumb2();
6440     MachineRegisterInfo &MRI = Fn->getRegInfo();
6441     // In Thumb mode S must not be specified if source register is the SP or
6442     // PC and if destination register is the SP, so restrict register class
6443     unsigned NewMovDstReg = MRI.createVirtualRegister(
6444       isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6445     unsigned NewRsbDstReg = MRI.createVirtualRegister(
6446       isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6447
6448     // Transfer the remainder of BB and its successor edges to sinkMBB.
6449     SinkBB->splice(SinkBB->begin(), BB,
6450       llvm::next(MachineBasicBlock::iterator(MI)),
6451       BB->end());
6452     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6453
6454     BB->addSuccessor(RSBBB);
6455     BB->addSuccessor(SinkBB);
6456
6457     // fall through to SinkMBB
6458     RSBBB->addSuccessor(SinkBB);
6459
6460     // insert a movs at the end of BB
6461     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6462       NewMovDstReg)
6463       .addReg(ABSSrcReg, RegState::Kill)
6464       .addImm((unsigned)ARMCC::AL).addReg(0)
6465       .addReg(ARM::CPSR, RegState::Define);
6466
6467     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6468     BuildMI(BB, dl,
6469       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6470       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6471
6472     // insert rsbri in RSBBB
6473     // Note: BCC and rsbri will be converted into predicated rsbmi
6474     // by if-conversion pass
6475     BuildMI(*RSBBB, RSBBB->begin(), dl,
6476       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6477       .addReg(NewMovDstReg, RegState::Kill)
6478       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6479
6480     // insert PHI in SinkBB,
6481     // reuse ABSDstReg to not change uses of ABS instruction
6482     BuildMI(*SinkBB, SinkBB->begin(), dl,
6483       TII->get(ARM::PHI), ABSDstReg)
6484       .addReg(NewRsbDstReg).addMBB(RSBBB)
6485       .addReg(NewMovDstReg).addMBB(BB);
6486
6487     // remove ABS instruction
6488     MI->eraseFromParent();
6489
6490     // return last added BB
6491     return SinkBB;
6492   }
6493   }
6494 }
6495
6496 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6497                                                       SDNode *Node) const {
6498   if (!MI->hasPostISelHook()) {
6499     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6500            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6501     return;
6502   }
6503
6504   const MCInstrDesc *MCID = &MI->getDesc();
6505   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6506   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6507   // operand is still set to noreg. If needed, set the optional operand's
6508   // register to CPSR, and remove the redundant implicit def.
6509   //
6510   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6511
6512   // Rename pseudo opcodes.
6513   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6514   if (NewOpc) {
6515     const ARMBaseInstrInfo *TII =
6516       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6517     MCID = &TII->get(NewOpc);
6518
6519     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6520            "converted opcode should be the same except for cc_out");
6521
6522     MI->setDesc(*MCID);
6523
6524     // Add the optional cc_out operand
6525     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6526   }
6527   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6528
6529   // Any ARM instruction that sets the 's' bit should specify an optional
6530   // "cc_out" operand in the last operand position.
6531   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6532     assert(!NewOpc && "Optional cc_out operand required");
6533     return;
6534   }
6535   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6536   // since we already have an optional CPSR def.
6537   bool definesCPSR = false;
6538   bool deadCPSR = false;
6539   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6540        i != e; ++i) {
6541     const MachineOperand &MO = MI->getOperand(i);
6542     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6543       definesCPSR = true;
6544       if (MO.isDead())
6545         deadCPSR = true;
6546       MI->RemoveOperand(i);
6547       break;
6548     }
6549   }
6550   if (!definesCPSR) {
6551     assert(!NewOpc && "Optional cc_out operand required");
6552     return;
6553   }
6554   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6555   if (deadCPSR) {
6556     assert(!MI->getOperand(ccOutIdx).getReg() &&
6557            "expect uninitialized optional cc_out operand");
6558     return;
6559   }
6560
6561   // If this instruction was defined with an optional CPSR def and its dag node
6562   // had a live implicit CPSR def, then activate the optional CPSR def.
6563   MachineOperand &MO = MI->getOperand(ccOutIdx);
6564   MO.setReg(ARM::CPSR);
6565   MO.setIsDef(true);
6566 }
6567
6568 //===----------------------------------------------------------------------===//
6569 //                           ARM Optimization Hooks
6570 //===----------------------------------------------------------------------===//
6571
6572 static
6573 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6574                             TargetLowering::DAGCombinerInfo &DCI) {
6575   SelectionDAG &DAG = DCI.DAG;
6576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6577   EVT VT = N->getValueType(0);
6578   unsigned Opc = N->getOpcode();
6579   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6580   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6581   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6582   ISD::CondCode CC = ISD::SETCC_INVALID;
6583
6584   if (isSlctCC) {
6585     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6586   } else {
6587     SDValue CCOp = Slct.getOperand(0);
6588     if (CCOp.getOpcode() == ISD::SETCC)
6589       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6590   }
6591
6592   bool DoXform = false;
6593   bool InvCC = false;
6594   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6595           "Bad input!");
6596
6597   if (LHS.getOpcode() == ISD::Constant &&
6598       cast<ConstantSDNode>(LHS)->isNullValue()) {
6599     DoXform = true;
6600   } else if (CC != ISD::SETCC_INVALID &&
6601              RHS.getOpcode() == ISD::Constant &&
6602              cast<ConstantSDNode>(RHS)->isNullValue()) {
6603     std::swap(LHS, RHS);
6604     SDValue Op0 = Slct.getOperand(0);
6605     EVT OpVT = isSlctCC ? Op0.getValueType() :
6606                           Op0.getOperand(0).getValueType();
6607     bool isInt = OpVT.isInteger();
6608     CC = ISD::getSetCCInverse(CC, isInt);
6609
6610     if (!TLI.isCondCodeLegal(CC, OpVT))
6611       return SDValue();         // Inverse operator isn't legal.
6612
6613     DoXform = true;
6614     InvCC = true;
6615   }
6616
6617   if (DoXform) {
6618     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6619     if (isSlctCC)
6620       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6621                              Slct.getOperand(0), Slct.getOperand(1), CC);
6622     SDValue CCOp = Slct.getOperand(0);
6623     if (InvCC)
6624       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6625                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
6626     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6627                        CCOp, OtherOp, Result);
6628   }
6629   return SDValue();
6630 }
6631
6632 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6633 // (only after legalization).
6634 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6635                                  TargetLowering::DAGCombinerInfo &DCI,
6636                                  const ARMSubtarget *Subtarget) {
6637
6638   // Only perform optimization if after legalize, and if NEON is available. We
6639   // also expected both operands to be BUILD_VECTORs.
6640   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6641       || N0.getOpcode() != ISD::BUILD_VECTOR
6642       || N1.getOpcode() != ISD::BUILD_VECTOR)
6643     return SDValue();
6644
6645   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6646   EVT VT = N->getValueType(0);
6647   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6648     return SDValue();
6649
6650   // Check that the vector operands are of the right form.
6651   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6652   // operands, where N is the size of the formed vector.
6653   // Each EXTRACT_VECTOR should have the same input vector and odd or even
6654   // index such that we have a pair wise add pattern.
6655
6656   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6657   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6658     return SDValue();
6659   SDValue Vec = N0->getOperand(0)->getOperand(0);
6660   SDNode *V = Vec.getNode();
6661   unsigned nextIndex = 0;
6662
6663   // For each operands to the ADD which are BUILD_VECTORs,
6664   // check to see if each of their operands are an EXTRACT_VECTOR with
6665   // the same vector and appropriate index.
6666   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6667     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6668         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6669
6670       SDValue ExtVec0 = N0->getOperand(i);
6671       SDValue ExtVec1 = N1->getOperand(i);
6672
6673       // First operand is the vector, verify its the same.
6674       if (V != ExtVec0->getOperand(0).getNode() ||
6675           V != ExtVec1->getOperand(0).getNode())
6676         return SDValue();
6677
6678       // Second is the constant, verify its correct.
6679       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6680       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6681
6682       // For the constant, we want to see all the even or all the odd.
6683       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6684           || C1->getZExtValue() != nextIndex+1)
6685         return SDValue();
6686
6687       // Increment index.
6688       nextIndex+=2;
6689     } else
6690       return SDValue();
6691   }
6692
6693   // Create VPADDL node.
6694   SelectionDAG &DAG = DCI.DAG;
6695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6696
6697   // Build operand list.
6698   SmallVector<SDValue, 8> Ops;
6699   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6700                                 TLI.getPointerTy()));
6701
6702   // Input is the vector.
6703   Ops.push_back(Vec);
6704
6705   // Get widened type and narrowed type.
6706   MVT widenType;
6707   unsigned numElem = VT.getVectorNumElements();
6708   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6709     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6710     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6711     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6712     default:
6713       llvm_unreachable("Invalid vector element type for padd optimization.");
6714   }
6715
6716   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6717                             widenType, &Ops[0], Ops.size());
6718   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6719 }
6720
6721 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6722 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
6723 /// called with the default operands, and if that fails, with commuted
6724 /// operands.
6725 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6726                                           TargetLowering::DAGCombinerInfo &DCI,
6727                                           const ARMSubtarget *Subtarget){
6728
6729   // Attempt to create vpaddl for this add.
6730   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6731   if (Result.getNode())
6732     return Result;
6733
6734   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6735   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6736     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6737     if (Result.getNode()) return Result;
6738   }
6739   return SDValue();
6740 }
6741
6742 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6743 ///
6744 static SDValue PerformADDCombine(SDNode *N,
6745                                  TargetLowering::DAGCombinerInfo &DCI,
6746                                  const ARMSubtarget *Subtarget) {
6747   SDValue N0 = N->getOperand(0);
6748   SDValue N1 = N->getOperand(1);
6749
6750   // First try with the default operand order.
6751   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6752   if (Result.getNode())
6753     return Result;
6754
6755   // If that didn't work, try again with the operands commuted.
6756   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6757 }
6758
6759 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6760 ///
6761 static SDValue PerformSUBCombine(SDNode *N,
6762                                  TargetLowering::DAGCombinerInfo &DCI) {
6763   SDValue N0 = N->getOperand(0);
6764   SDValue N1 = N->getOperand(1);
6765
6766   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6767   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6768     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6769     if (Result.getNode()) return Result;
6770   }
6771
6772   return SDValue();
6773 }
6774
6775 /// PerformVMULCombine
6776 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6777 /// special multiplier accumulator forwarding.
6778 ///   vmul d3, d0, d2
6779 ///   vmla d3, d1, d2
6780 /// is faster than
6781 ///   vadd d3, d0, d1
6782 ///   vmul d3, d3, d2
6783 static SDValue PerformVMULCombine(SDNode *N,
6784                                   TargetLowering::DAGCombinerInfo &DCI,
6785                                   const ARMSubtarget *Subtarget) {
6786   if (!Subtarget->hasVMLxForwarding())
6787     return SDValue();
6788
6789   SelectionDAG &DAG = DCI.DAG;
6790   SDValue N0 = N->getOperand(0);
6791   SDValue N1 = N->getOperand(1);
6792   unsigned Opcode = N0.getOpcode();
6793   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6794       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6795     Opcode = N1.getOpcode();
6796     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6797         Opcode != ISD::FADD && Opcode != ISD::FSUB)
6798       return SDValue();
6799     std::swap(N0, N1);
6800   }
6801
6802   EVT VT = N->getValueType(0);
6803   DebugLoc DL = N->getDebugLoc();
6804   SDValue N00 = N0->getOperand(0);
6805   SDValue N01 = N0->getOperand(1);
6806   return DAG.getNode(Opcode, DL, VT,
6807                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6808                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6809 }
6810
6811 static SDValue PerformMULCombine(SDNode *N,
6812                                  TargetLowering::DAGCombinerInfo &DCI,
6813                                  const ARMSubtarget *Subtarget) {
6814   SelectionDAG &DAG = DCI.DAG;
6815
6816   if (Subtarget->isThumb1Only())
6817     return SDValue();
6818
6819   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6820     return SDValue();
6821
6822   EVT VT = N->getValueType(0);
6823   if (VT.is64BitVector() || VT.is128BitVector())
6824     return PerformVMULCombine(N, DCI, Subtarget);
6825   if (VT != MVT::i32)
6826     return SDValue();
6827
6828   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6829   if (!C)
6830     return SDValue();
6831
6832   uint64_t MulAmt = C->getZExtValue();
6833   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6834   ShiftAmt = ShiftAmt & (32 - 1);
6835   SDValue V = N->getOperand(0);
6836   DebugLoc DL = N->getDebugLoc();
6837
6838   SDValue Res;
6839   MulAmt >>= ShiftAmt;
6840   if (isPowerOf2_32(MulAmt - 1)) {
6841     // (mul x, 2^N + 1) => (add (shl x, N), x)
6842     Res = DAG.getNode(ISD::ADD, DL, VT,
6843                       V, DAG.getNode(ISD::SHL, DL, VT,
6844                                      V, DAG.getConstant(Log2_32(MulAmt-1),
6845                                                         MVT::i32)));
6846   } else if (isPowerOf2_32(MulAmt + 1)) {
6847     // (mul x, 2^N - 1) => (sub (shl x, N), x)
6848     Res = DAG.getNode(ISD::SUB, DL, VT,
6849                       DAG.getNode(ISD::SHL, DL, VT,
6850                                   V, DAG.getConstant(Log2_32(MulAmt+1),
6851                                                      MVT::i32)),
6852                                                      V);
6853   } else
6854     return SDValue();
6855
6856   if (ShiftAmt != 0)
6857     Res = DAG.getNode(ISD::SHL, DL, VT, Res,
6858                       DAG.getConstant(ShiftAmt, MVT::i32));
6859
6860   // Do not add new nodes to DAG combiner worklist.
6861   DCI.CombineTo(N, Res, false);
6862   return SDValue();
6863 }
6864
6865 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
6866   if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
6867     return false;
6868
6869   SDValue FalseVal = N.getOperand(0);
6870   ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
6871   if (!C)
6872     return false;
6873   if (AllOnes)
6874     return C->isAllOnesValue();
6875   return C->isNullValue();
6876 }
6877
6878 /// formConditionalOp - Combine an operation with a conditional move operand
6879 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
6880 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
6881 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
6882                                  bool Commutable) {
6883   SDValue N0 = N->getOperand(0);
6884   SDValue N1 = N->getOperand(1);
6885
6886   bool isAND = N->getOpcode() == ISD::AND;
6887   bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
6888   if (!isCand && Commutable) {
6889     isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
6890     if (isCand)
6891       std::swap(N0, N1);
6892   }
6893   if (!isCand)
6894     return SDValue();
6895
6896   unsigned Opc = 0;
6897   switch (N->getOpcode()) {
6898   default: llvm_unreachable("Unexpected node");
6899   case ISD::AND: Opc = ARMISD::CAND; break;
6900   case ISD::OR:  Opc = ARMISD::COR; break;
6901   case ISD::XOR: Opc = ARMISD::CXOR; break;
6902   }
6903   return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
6904                      N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
6905                      N1.getOperand(4));
6906 }
6907
6908 static SDValue PerformANDCombine(SDNode *N,
6909                                  TargetLowering::DAGCombinerInfo &DCI,
6910                                  const ARMSubtarget *Subtarget) {
6911
6912   // Attempt to use immediate-form VBIC
6913   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6914   DebugLoc dl = N->getDebugLoc();
6915   EVT VT = N->getValueType(0);
6916   SelectionDAG &DAG = DCI.DAG;
6917
6918   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6919     return SDValue();
6920
6921   APInt SplatBits, SplatUndef;
6922   unsigned SplatBitSize;
6923   bool HasAnyUndefs;
6924   if (BVN &&
6925       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6926     if (SplatBitSize <= 64) {
6927       EVT VbicVT;
6928       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
6929                                       SplatUndef.getZExtValue(), SplatBitSize,
6930                                       DAG, VbicVT, VT.is128BitVector(),
6931                                       OtherModImm);
6932       if (Val.getNode()) {
6933         SDValue Input =
6934           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
6935         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
6936         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
6937       }
6938     }
6939   }
6940
6941   if (!Subtarget->isThumb1Only()) {
6942     // (and x, (cmov -1, y, cond)) => (and.cond x, y)
6943     SDValue CAND = formConditionalOp(N, DAG, true);
6944     if (CAND.getNode())
6945       return CAND;
6946   }
6947
6948   return SDValue();
6949 }
6950
6951 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
6952 static SDValue PerformORCombine(SDNode *N,
6953                                 TargetLowering::DAGCombinerInfo &DCI,
6954                                 const ARMSubtarget *Subtarget) {
6955   // Attempt to use immediate-form VORR
6956   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6957   DebugLoc dl = N->getDebugLoc();
6958   EVT VT = N->getValueType(0);
6959   SelectionDAG &DAG = DCI.DAG;
6960
6961   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6962     return SDValue();
6963
6964   APInt SplatBits, SplatUndef;
6965   unsigned SplatBitSize;
6966   bool HasAnyUndefs;
6967   if (BVN && Subtarget->hasNEON() &&
6968       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6969     if (SplatBitSize <= 64) {
6970       EVT VorrVT;
6971       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6972                                       SplatUndef.getZExtValue(), SplatBitSize,
6973                                       DAG, VorrVT, VT.is128BitVector(),
6974                                       OtherModImm);
6975       if (Val.getNode()) {
6976         SDValue Input =
6977           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
6978         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
6979         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
6980       }
6981     }
6982   }
6983
6984   if (!Subtarget->isThumb1Only()) {
6985     // (or x, (cmov 0, y, cond)) => (or.cond x, y)
6986     SDValue COR = formConditionalOp(N, DAG, true);
6987     if (COR.getNode())
6988       return COR;
6989   }
6990
6991   SDValue N0 = N->getOperand(0);
6992   if (N0.getOpcode() != ISD::AND)
6993     return SDValue();
6994   SDValue N1 = N->getOperand(1);
6995
6996   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
6997   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
6998       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
6999     APInt SplatUndef;
7000     unsigned SplatBitSize;
7001     bool HasAnyUndefs;
7002
7003     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7004     APInt SplatBits0;
7005     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7006                                   HasAnyUndefs) && !HasAnyUndefs) {
7007       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7008       APInt SplatBits1;
7009       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7010                                     HasAnyUndefs) && !HasAnyUndefs &&
7011           SplatBits0 == ~SplatBits1) {
7012         // Canonicalize the vector type to make instruction selection simpler.
7013         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7014         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7015                                      N0->getOperand(1), N0->getOperand(0),
7016                                      N1->getOperand(0));
7017         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7018       }
7019     }
7020   }
7021
7022   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7023   // reasonable.
7024
7025   // BFI is only available on V6T2+
7026   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7027     return SDValue();
7028
7029   DebugLoc DL = N->getDebugLoc();
7030   // 1) or (and A, mask), val => ARMbfi A, val, mask
7031   //      iff (val & mask) == val
7032   //
7033   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7034   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7035   //          && mask == ~mask2
7036   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7037   //          && ~mask == mask2
7038   //  (i.e., copy a bitfield value into another bitfield of the same width)
7039
7040   if (VT != MVT::i32)
7041     return SDValue();
7042
7043   SDValue N00 = N0.getOperand(0);
7044
7045   // The value and the mask need to be constants so we can verify this is
7046   // actually a bitfield set. If the mask is 0xffff, we can do better
7047   // via a movt instruction, so don't use BFI in that case.
7048   SDValue MaskOp = N0.getOperand(1);
7049   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7050   if (!MaskC)
7051     return SDValue();
7052   unsigned Mask = MaskC->getZExtValue();
7053   if (Mask == 0xffff)
7054     return SDValue();
7055   SDValue Res;
7056   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7057   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7058   if (N1C) {
7059     unsigned Val = N1C->getZExtValue();
7060     if ((Val & ~Mask) != Val)
7061       return SDValue();
7062
7063     if (ARM::isBitFieldInvertedMask(Mask)) {
7064       Val >>= CountTrailingZeros_32(~Mask);
7065
7066       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7067                         DAG.getConstant(Val, MVT::i32),
7068                         DAG.getConstant(Mask, MVT::i32));
7069
7070       // Do not add new nodes to DAG combiner worklist.
7071       DCI.CombineTo(N, Res, false);
7072       return SDValue();
7073     }
7074   } else if (N1.getOpcode() == ISD::AND) {
7075     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7076     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7077     if (!N11C)
7078       return SDValue();
7079     unsigned Mask2 = N11C->getZExtValue();
7080
7081     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7082     // as is to match.
7083     if (ARM::isBitFieldInvertedMask(Mask) &&
7084         (Mask == ~Mask2)) {
7085       // The pack halfword instruction works better for masks that fit it,
7086       // so use that when it's available.
7087       if (Subtarget->hasT2ExtractPack() &&
7088           (Mask == 0xffff || Mask == 0xffff0000))
7089         return SDValue();
7090       // 2a
7091       unsigned amt = CountTrailingZeros_32(Mask2);
7092       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7093                         DAG.getConstant(amt, MVT::i32));
7094       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7095                         DAG.getConstant(Mask, MVT::i32));
7096       // Do not add new nodes to DAG combiner worklist.
7097       DCI.CombineTo(N, Res, false);
7098       return SDValue();
7099     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7100                (~Mask == Mask2)) {
7101       // The pack halfword instruction works better for masks that fit it,
7102       // so use that when it's available.
7103       if (Subtarget->hasT2ExtractPack() &&
7104           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7105         return SDValue();
7106       // 2b
7107       unsigned lsb = CountTrailingZeros_32(Mask);
7108       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7109                         DAG.getConstant(lsb, MVT::i32));
7110       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7111                         DAG.getConstant(Mask2, MVT::i32));
7112       // Do not add new nodes to DAG combiner worklist.
7113       DCI.CombineTo(N, Res, false);
7114       return SDValue();
7115     }
7116   }
7117
7118   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7119       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7120       ARM::isBitFieldInvertedMask(~Mask)) {
7121     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7122     // where lsb(mask) == #shamt and masked bits of B are known zero.
7123     SDValue ShAmt = N00.getOperand(1);
7124     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7125     unsigned LSB = CountTrailingZeros_32(Mask);
7126     if (ShAmtC != LSB)
7127       return SDValue();
7128
7129     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7130                       DAG.getConstant(~Mask, MVT::i32));
7131
7132     // Do not add new nodes to DAG combiner worklist.
7133     DCI.CombineTo(N, Res, false);
7134   }
7135
7136   return SDValue();
7137 }
7138
7139 static SDValue PerformXORCombine(SDNode *N,
7140                                  TargetLowering::DAGCombinerInfo &DCI,
7141                                  const ARMSubtarget *Subtarget) {
7142   EVT VT = N->getValueType(0);
7143   SelectionDAG &DAG = DCI.DAG;
7144
7145   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7146     return SDValue();
7147
7148   if (!Subtarget->isThumb1Only()) {
7149     // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7150     SDValue CXOR = formConditionalOp(N, DAG, true);
7151     if (CXOR.getNode())
7152       return CXOR;
7153   }
7154
7155   return SDValue();
7156 }
7157
7158 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7159 /// the bits being cleared by the AND are not demanded by the BFI.
7160 static SDValue PerformBFICombine(SDNode *N,
7161                                  TargetLowering::DAGCombinerInfo &DCI) {
7162   SDValue N1 = N->getOperand(1);
7163   if (N1.getOpcode() == ISD::AND) {
7164     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7165     if (!N11C)
7166       return SDValue();
7167     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7168     unsigned LSB = CountTrailingZeros_32(~InvMask);
7169     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7170     unsigned Mask = (1 << Width)-1;
7171     unsigned Mask2 = N11C->getZExtValue();
7172     if ((Mask & (~Mask2)) == 0)
7173       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7174                              N->getOperand(0), N1.getOperand(0),
7175                              N->getOperand(2));
7176   }
7177   return SDValue();
7178 }
7179
7180 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7181 /// ARMISD::VMOVRRD.
7182 static SDValue PerformVMOVRRDCombine(SDNode *N,
7183                                      TargetLowering::DAGCombinerInfo &DCI) {
7184   // vmovrrd(vmovdrr x, y) -> x,y
7185   SDValue InDouble = N->getOperand(0);
7186   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7187     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7188
7189   // vmovrrd(load f64) -> (load i32), (load i32)
7190   SDNode *InNode = InDouble.getNode();
7191   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7192       InNode->getValueType(0) == MVT::f64 &&
7193       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7194       !cast<LoadSDNode>(InNode)->isVolatile()) {
7195     // TODO: Should this be done for non-FrameIndex operands?
7196     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7197
7198     SelectionDAG &DAG = DCI.DAG;
7199     DebugLoc DL = LD->getDebugLoc();
7200     SDValue BasePtr = LD->getBasePtr();
7201     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7202                                  LD->getPointerInfo(), LD->isVolatile(),
7203                                  LD->isNonTemporal(), LD->isInvariant(),
7204                                  LD->getAlignment());
7205
7206     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7207                                     DAG.getConstant(4, MVT::i32));
7208     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7209                                  LD->getPointerInfo(), LD->isVolatile(),
7210                                  LD->isNonTemporal(), LD->isInvariant(),
7211                                  std::min(4U, LD->getAlignment() / 2));
7212
7213     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7214     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7215     DCI.RemoveFromWorklist(LD);
7216     DAG.DeleteNode(LD);
7217     return Result;
7218   }
7219
7220   return SDValue();
7221 }
7222
7223 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7224 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7225 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7226   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7227   SDValue Op0 = N->getOperand(0);
7228   SDValue Op1 = N->getOperand(1);
7229   if (Op0.getOpcode() == ISD::BITCAST)
7230     Op0 = Op0.getOperand(0);
7231   if (Op1.getOpcode() == ISD::BITCAST)
7232     Op1 = Op1.getOperand(0);
7233   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7234       Op0.getNode() == Op1.getNode() &&
7235       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7236     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7237                        N->getValueType(0), Op0.getOperand(0));
7238   return SDValue();
7239 }
7240
7241 /// PerformSTORECombine - Target-specific dag combine xforms for
7242 /// ISD::STORE.
7243 static SDValue PerformSTORECombine(SDNode *N,
7244                                    TargetLowering::DAGCombinerInfo &DCI) {
7245   // Bitcast an i64 store extracted from a vector to f64.
7246   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7247   StoreSDNode *St = cast<StoreSDNode>(N);
7248   SDValue StVal = St->getValue();
7249   if (!ISD::isNormalStore(St) || St->isVolatile())
7250     return SDValue();
7251
7252   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7253       StVal.getNode()->hasOneUse() && !St->isVolatile()) {
7254     SelectionDAG  &DAG = DCI.DAG;
7255     DebugLoc DL = St->getDebugLoc();
7256     SDValue BasePtr = St->getBasePtr();
7257     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7258                                   StVal.getNode()->getOperand(0), BasePtr,
7259                                   St->getPointerInfo(), St->isVolatile(),
7260                                   St->isNonTemporal(), St->getAlignment());
7261
7262     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7263                                     DAG.getConstant(4, MVT::i32));
7264     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7265                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7266                         St->isNonTemporal(),
7267                         std::min(4U, St->getAlignment() / 2));
7268   }
7269
7270   if (StVal.getValueType() != MVT::i64 ||
7271       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7272     return SDValue();
7273
7274   SelectionDAG &DAG = DCI.DAG;
7275   DebugLoc dl = StVal.getDebugLoc();
7276   SDValue IntVec = StVal.getOperand(0);
7277   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7278                                  IntVec.getValueType().getVectorNumElements());
7279   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7280   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7281                                Vec, StVal.getOperand(1));
7282   dl = N->getDebugLoc();
7283   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7284   // Make the DAGCombiner fold the bitcasts.
7285   DCI.AddToWorklist(Vec.getNode());
7286   DCI.AddToWorklist(ExtElt.getNode());
7287   DCI.AddToWorklist(V.getNode());
7288   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7289                       St->getPointerInfo(), St->isVolatile(),
7290                       St->isNonTemporal(), St->getAlignment(),
7291                       St->getTBAAInfo());
7292 }
7293
7294 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7295 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7296 /// i64 vector to have f64 elements, since the value can then be loaded
7297 /// directly into a VFP register.
7298 static bool hasNormalLoadOperand(SDNode *N) {
7299   unsigned NumElts = N->getValueType(0).getVectorNumElements();
7300   for (unsigned i = 0; i < NumElts; ++i) {
7301     SDNode *Elt = N->getOperand(i).getNode();
7302     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7303       return true;
7304   }
7305   return false;
7306 }
7307
7308 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7309 /// ISD::BUILD_VECTOR.
7310 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7311                                           TargetLowering::DAGCombinerInfo &DCI){
7312   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7313   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7314   // into a pair of GPRs, which is fine when the value is used as a scalar,
7315   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7316   SelectionDAG &DAG = DCI.DAG;
7317   if (N->getNumOperands() == 2) {
7318     SDValue RV = PerformVMOVDRRCombine(N, DAG);
7319     if (RV.getNode())
7320       return RV;
7321   }
7322
7323   // Load i64 elements as f64 values so that type legalization does not split
7324   // them up into i32 values.
7325   EVT VT = N->getValueType(0);
7326   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7327     return SDValue();
7328   DebugLoc dl = N->getDebugLoc();
7329   SmallVector<SDValue, 8> Ops;
7330   unsigned NumElts = VT.getVectorNumElements();
7331   for (unsigned i = 0; i < NumElts; ++i) {
7332     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7333     Ops.push_back(V);
7334     // Make the DAGCombiner fold the bitcast.
7335     DCI.AddToWorklist(V.getNode());
7336   }
7337   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7338   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7339   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7340 }
7341
7342 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7343 /// ISD::INSERT_VECTOR_ELT.
7344 static SDValue PerformInsertEltCombine(SDNode *N,
7345                                        TargetLowering::DAGCombinerInfo &DCI) {
7346   // Bitcast an i64 load inserted into a vector to f64.
7347   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7348   EVT VT = N->getValueType(0);
7349   SDNode *Elt = N->getOperand(1).getNode();
7350   if (VT.getVectorElementType() != MVT::i64 ||
7351       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7352     return SDValue();
7353
7354   SelectionDAG &DAG = DCI.DAG;
7355   DebugLoc dl = N->getDebugLoc();
7356   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7357                                  VT.getVectorNumElements());
7358   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7359   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7360   // Make the DAGCombiner fold the bitcasts.
7361   DCI.AddToWorklist(Vec.getNode());
7362   DCI.AddToWorklist(V.getNode());
7363   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7364                                Vec, V, N->getOperand(2));
7365   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7366 }
7367
7368 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7369 /// ISD::VECTOR_SHUFFLE.
7370 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7371   // The LLVM shufflevector instruction does not require the shuffle mask
7372   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7373   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7374   // operands do not match the mask length, they are extended by concatenating
7375   // them with undef vectors.  That is probably the right thing for other
7376   // targets, but for NEON it is better to concatenate two double-register
7377   // size vector operands into a single quad-register size vector.  Do that
7378   // transformation here:
7379   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7380   //   shuffle(concat(v1, v2), undef)
7381   SDValue Op0 = N->getOperand(0);
7382   SDValue Op1 = N->getOperand(1);
7383   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7384       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7385       Op0.getNumOperands() != 2 ||
7386       Op1.getNumOperands() != 2)
7387     return SDValue();
7388   SDValue Concat0Op1 = Op0.getOperand(1);
7389   SDValue Concat1Op1 = Op1.getOperand(1);
7390   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7391       Concat1Op1.getOpcode() != ISD::UNDEF)
7392     return SDValue();
7393   // Skip the transformation if any of the types are illegal.
7394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7395   EVT VT = N->getValueType(0);
7396   if (!TLI.isTypeLegal(VT) ||
7397       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7398       !TLI.isTypeLegal(Concat1Op1.getValueType()))
7399     return SDValue();
7400
7401   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7402                                   Op0.getOperand(0), Op1.getOperand(0));
7403   // Translate the shuffle mask.
7404   SmallVector<int, 16> NewMask;
7405   unsigned NumElts = VT.getVectorNumElements();
7406   unsigned HalfElts = NumElts/2;
7407   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7408   for (unsigned n = 0; n < NumElts; ++n) {
7409     int MaskElt = SVN->getMaskElt(n);
7410     int NewElt = -1;
7411     if (MaskElt < (int)HalfElts)
7412       NewElt = MaskElt;
7413     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7414       NewElt = HalfElts + MaskElt - NumElts;
7415     NewMask.push_back(NewElt);
7416   }
7417   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7418                               DAG.getUNDEF(VT), NewMask.data());
7419 }
7420
7421 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7422 /// NEON load/store intrinsics to merge base address updates.
7423 static SDValue CombineBaseUpdate(SDNode *N,
7424                                  TargetLowering::DAGCombinerInfo &DCI) {
7425   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7426     return SDValue();
7427
7428   SelectionDAG &DAG = DCI.DAG;
7429   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7430                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7431   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7432   SDValue Addr = N->getOperand(AddrOpIdx);
7433
7434   // Search for a use of the address operand that is an increment.
7435   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7436          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7437     SDNode *User = *UI;
7438     if (User->getOpcode() != ISD::ADD ||
7439         UI.getUse().getResNo() != Addr.getResNo())
7440       continue;
7441
7442     // Check that the add is independent of the load/store.  Otherwise, folding
7443     // it would create a cycle.
7444     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7445       continue;
7446
7447     // Find the new opcode for the updating load/store.
7448     bool isLoad = true;
7449     bool isLaneOp = false;
7450     unsigned NewOpc = 0;
7451     unsigned NumVecs = 0;
7452     if (isIntrinsic) {
7453       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7454       switch (IntNo) {
7455       default: llvm_unreachable("unexpected intrinsic for Neon base update");
7456       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
7457         NumVecs = 1; break;
7458       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
7459         NumVecs = 2; break;
7460       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
7461         NumVecs = 3; break;
7462       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
7463         NumVecs = 4; break;
7464       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7465         NumVecs = 2; isLaneOp = true; break;
7466       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7467         NumVecs = 3; isLaneOp = true; break;
7468       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7469         NumVecs = 4; isLaneOp = true; break;
7470       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
7471         NumVecs = 1; isLoad = false; break;
7472       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
7473         NumVecs = 2; isLoad = false; break;
7474       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
7475         NumVecs = 3; isLoad = false; break;
7476       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
7477         NumVecs = 4; isLoad = false; break;
7478       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7479         NumVecs = 2; isLoad = false; isLaneOp = true; break;
7480       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7481         NumVecs = 3; isLoad = false; isLaneOp = true; break;
7482       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7483         NumVecs = 4; isLoad = false; isLaneOp = true; break;
7484       }
7485     } else {
7486       isLaneOp = true;
7487       switch (N->getOpcode()) {
7488       default: llvm_unreachable("unexpected opcode for Neon base update");
7489       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7490       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7491       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7492       }
7493     }
7494
7495     // Find the size of memory referenced by the load/store.
7496     EVT VecTy;
7497     if (isLoad)
7498       VecTy = N->getValueType(0);
7499     else
7500       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7501     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7502     if (isLaneOp)
7503       NumBytes /= VecTy.getVectorNumElements();
7504
7505     // If the increment is a constant, it must match the memory ref size.
7506     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7507     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7508       uint64_t IncVal = CInc->getZExtValue();
7509       if (IncVal != NumBytes)
7510         continue;
7511     } else if (NumBytes >= 3 * 16) {
7512       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7513       // separate instructions that make it harder to use a non-constant update.
7514       continue;
7515     }
7516
7517     // Create the new updating load/store node.
7518     EVT Tys[6];
7519     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7520     unsigned n;
7521     for (n = 0; n < NumResultVecs; ++n)
7522       Tys[n] = VecTy;
7523     Tys[n++] = MVT::i32;
7524     Tys[n] = MVT::Other;
7525     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7526     SmallVector<SDValue, 8> Ops;
7527     Ops.push_back(N->getOperand(0)); // incoming chain
7528     Ops.push_back(N->getOperand(AddrOpIdx));
7529     Ops.push_back(Inc);
7530     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7531       Ops.push_back(N->getOperand(i));
7532     }
7533     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7534     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7535                                            Ops.data(), Ops.size(),
7536                                            MemInt->getMemoryVT(),
7537                                            MemInt->getMemOperand());
7538
7539     // Update the uses.
7540     std::vector<SDValue> NewResults;
7541     for (unsigned i = 0; i < NumResultVecs; ++i) {
7542       NewResults.push_back(SDValue(UpdN.getNode(), i));
7543     }
7544     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7545     DCI.CombineTo(N, NewResults);
7546     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7547
7548     break;
7549   }
7550   return SDValue();
7551 }
7552
7553 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7554 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7555 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
7556 /// return true.
7557 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7558   SelectionDAG &DAG = DCI.DAG;
7559   EVT VT = N->getValueType(0);
7560   // vldN-dup instructions only support 64-bit vectors for N > 1.
7561   if (!VT.is64BitVector())
7562     return false;
7563
7564   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7565   SDNode *VLD = N->getOperand(0).getNode();
7566   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7567     return false;
7568   unsigned NumVecs = 0;
7569   unsigned NewOpc = 0;
7570   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7571   if (IntNo == Intrinsic::arm_neon_vld2lane) {
7572     NumVecs = 2;
7573     NewOpc = ARMISD::VLD2DUP;
7574   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7575     NumVecs = 3;
7576     NewOpc = ARMISD::VLD3DUP;
7577   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7578     NumVecs = 4;
7579     NewOpc = ARMISD::VLD4DUP;
7580   } else {
7581     return false;
7582   }
7583
7584   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7585   // numbers match the load.
7586   unsigned VLDLaneNo =
7587     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7588   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7589        UI != UE; ++UI) {
7590     // Ignore uses of the chain result.
7591     if (UI.getUse().getResNo() == NumVecs)
7592       continue;
7593     SDNode *User = *UI;
7594     if (User->getOpcode() != ARMISD::VDUPLANE ||
7595         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7596       return false;
7597   }
7598
7599   // Create the vldN-dup node.
7600   EVT Tys[5];
7601   unsigned n;
7602   for (n = 0; n < NumVecs; ++n)
7603     Tys[n] = VT;
7604   Tys[n] = MVT::Other;
7605   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7606   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7607   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7608   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7609                                            Ops, 2, VLDMemInt->getMemoryVT(),
7610                                            VLDMemInt->getMemOperand());
7611
7612   // Update the uses.
7613   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7614        UI != UE; ++UI) {
7615     unsigned ResNo = UI.getUse().getResNo();
7616     // Ignore uses of the chain result.
7617     if (ResNo == NumVecs)
7618       continue;
7619     SDNode *User = *UI;
7620     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7621   }
7622
7623   // Now the vldN-lane intrinsic is dead except for its chain result.
7624   // Update uses of the chain.
7625   std::vector<SDValue> VLDDupResults;
7626   for (unsigned n = 0; n < NumVecs; ++n)
7627     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7628   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7629   DCI.CombineTo(VLD, VLDDupResults);
7630
7631   return true;
7632 }
7633
7634 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
7635 /// ARMISD::VDUPLANE.
7636 static SDValue PerformVDUPLANECombine(SDNode *N,
7637                                       TargetLowering::DAGCombinerInfo &DCI) {
7638   SDValue Op = N->getOperand(0);
7639
7640   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7641   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7642   if (CombineVLDDUP(N, DCI))
7643     return SDValue(N, 0);
7644
7645   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7646   // redundant.  Ignore bit_converts for now; element sizes are checked below.
7647   while (Op.getOpcode() == ISD::BITCAST)
7648     Op = Op.getOperand(0);
7649   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7650     return SDValue();
7651
7652   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7653   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7654   // The canonical VMOV for a zero vector uses a 32-bit element size.
7655   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7656   unsigned EltBits;
7657   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7658     EltSize = 8;
7659   EVT VT = N->getValueType(0);
7660   if (EltSize > VT.getVectorElementType().getSizeInBits())
7661     return SDValue();
7662
7663   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7664 }
7665
7666 // isConstVecPow2 - Return true if each vector element is a power of 2, all
7667 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7668 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7669 {
7670   integerPart cN;
7671   integerPart c0 = 0;
7672   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7673        I != E; I++) {
7674     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7675     if (!C)
7676       return false;
7677
7678     bool isExact;
7679     APFloat APF = C->getValueAPF();
7680     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7681         != APFloat::opOK || !isExact)
7682       return false;
7683
7684     c0 = (I == 0) ? cN : c0;
7685     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7686       return false;
7687   }
7688   C = c0;
7689   return true;
7690 }
7691
7692 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7693 /// can replace combinations of VMUL and VCVT (floating-point to integer)
7694 /// when the VMUL has a constant operand that is a power of 2.
7695 ///
7696 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7697 ///  vmul.f32        d16, d17, d16
7698 ///  vcvt.s32.f32    d16, d16
7699 /// becomes:
7700 ///  vcvt.s32.f32    d16, d16, #3
7701 static SDValue PerformVCVTCombine(SDNode *N,
7702                                   TargetLowering::DAGCombinerInfo &DCI,
7703                                   const ARMSubtarget *Subtarget) {
7704   SelectionDAG &DAG = DCI.DAG;
7705   SDValue Op = N->getOperand(0);
7706
7707   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7708       Op.getOpcode() != ISD::FMUL)
7709     return SDValue();
7710
7711   uint64_t C;
7712   SDValue N0 = Op->getOperand(0);
7713   SDValue ConstVec = Op->getOperand(1);
7714   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7715
7716   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7717       !isConstVecPow2(ConstVec, isSigned, C))
7718     return SDValue();
7719
7720   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7721     Intrinsic::arm_neon_vcvtfp2fxu;
7722   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7723                      N->getValueType(0),
7724                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7725                      DAG.getConstant(Log2_64(C), MVT::i32));
7726 }
7727
7728 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7729 /// can replace combinations of VCVT (integer to floating-point) and VDIV
7730 /// when the VDIV has a constant operand that is a power of 2.
7731 ///
7732 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7733 ///  vcvt.f32.s32    d16, d16
7734 ///  vdiv.f32        d16, d17, d16
7735 /// becomes:
7736 ///  vcvt.f32.s32    d16, d16, #3
7737 static SDValue PerformVDIVCombine(SDNode *N,
7738                                   TargetLowering::DAGCombinerInfo &DCI,
7739                                   const ARMSubtarget *Subtarget) {
7740   SelectionDAG &DAG = DCI.DAG;
7741   SDValue Op = N->getOperand(0);
7742   unsigned OpOpcode = Op.getNode()->getOpcode();
7743
7744   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7745       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7746     return SDValue();
7747
7748   uint64_t C;
7749   SDValue ConstVec = N->getOperand(1);
7750   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7751
7752   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7753       !isConstVecPow2(ConstVec, isSigned, C))
7754     return SDValue();
7755
7756   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7757     Intrinsic::arm_neon_vcvtfxu2fp;
7758   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7759                      Op.getValueType(),
7760                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
7761                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7762 }
7763
7764 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
7765 /// operand of a vector shift operation, where all the elements of the
7766 /// build_vector must have the same constant integer value.
7767 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7768   // Ignore bit_converts.
7769   while (Op.getOpcode() == ISD::BITCAST)
7770     Op = Op.getOperand(0);
7771   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7772   APInt SplatBits, SplatUndef;
7773   unsigned SplatBitSize;
7774   bool HasAnyUndefs;
7775   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7776                                       HasAnyUndefs, ElementBits) ||
7777       SplatBitSize > ElementBits)
7778     return false;
7779   Cnt = SplatBits.getSExtValue();
7780   return true;
7781 }
7782
7783 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7784 /// operand of a vector shift left operation.  That value must be in the range:
7785 ///   0 <= Value < ElementBits for a left shift; or
7786 ///   0 <= Value <= ElementBits for a long left shift.
7787 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7788   assert(VT.isVector() && "vector shift count is not a vector type");
7789   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7790   if (! getVShiftImm(Op, ElementBits, Cnt))
7791     return false;
7792   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
7793 }
7794
7795 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7796 /// operand of a vector shift right operation.  For a shift opcode, the value
7797 /// is positive, but for an intrinsic the value count must be negative. The
7798 /// absolute value must be in the range:
7799 ///   1 <= |Value| <= ElementBits for a right shift; or
7800 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
7801 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
7802                          int64_t &Cnt) {
7803   assert(VT.isVector() && "vector shift count is not a vector type");
7804   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7805   if (! getVShiftImm(Op, ElementBits, Cnt))
7806     return false;
7807   if (isIntrinsic)
7808     Cnt = -Cnt;
7809   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
7810 }
7811
7812 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
7813 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
7814   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7815   switch (IntNo) {
7816   default:
7817     // Don't do anything for most intrinsics.
7818     break;
7819
7820   // Vector shifts: check for immediate versions and lower them.
7821   // Note: This is done during DAG combining instead of DAG legalizing because
7822   // the build_vectors for 64-bit vector element shift counts are generally
7823   // not legal, and it is hard to see their values after they get legalized to
7824   // loads from a constant pool.
7825   case Intrinsic::arm_neon_vshifts:
7826   case Intrinsic::arm_neon_vshiftu:
7827   case Intrinsic::arm_neon_vshiftls:
7828   case Intrinsic::arm_neon_vshiftlu:
7829   case Intrinsic::arm_neon_vshiftn:
7830   case Intrinsic::arm_neon_vrshifts:
7831   case Intrinsic::arm_neon_vrshiftu:
7832   case Intrinsic::arm_neon_vrshiftn:
7833   case Intrinsic::arm_neon_vqshifts:
7834   case Intrinsic::arm_neon_vqshiftu:
7835   case Intrinsic::arm_neon_vqshiftsu:
7836   case Intrinsic::arm_neon_vqshiftns:
7837   case Intrinsic::arm_neon_vqshiftnu:
7838   case Intrinsic::arm_neon_vqshiftnsu:
7839   case Intrinsic::arm_neon_vqrshiftns:
7840   case Intrinsic::arm_neon_vqrshiftnu:
7841   case Intrinsic::arm_neon_vqrshiftnsu: {
7842     EVT VT = N->getOperand(1).getValueType();
7843     int64_t Cnt;
7844     unsigned VShiftOpc = 0;
7845
7846     switch (IntNo) {
7847     case Intrinsic::arm_neon_vshifts:
7848     case Intrinsic::arm_neon_vshiftu:
7849       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
7850         VShiftOpc = ARMISD::VSHL;
7851         break;
7852       }
7853       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
7854         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
7855                      ARMISD::VSHRs : ARMISD::VSHRu);
7856         break;
7857       }
7858       return SDValue();
7859
7860     case Intrinsic::arm_neon_vshiftls:
7861     case Intrinsic::arm_neon_vshiftlu:
7862       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
7863         break;
7864       llvm_unreachable("invalid shift count for vshll intrinsic");
7865
7866     case Intrinsic::arm_neon_vrshifts:
7867     case Intrinsic::arm_neon_vrshiftu:
7868       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
7869         break;
7870       return SDValue();
7871
7872     case Intrinsic::arm_neon_vqshifts:
7873     case Intrinsic::arm_neon_vqshiftu:
7874       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7875         break;
7876       return SDValue();
7877
7878     case Intrinsic::arm_neon_vqshiftsu:
7879       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7880         break;
7881       llvm_unreachable("invalid shift count for vqshlu intrinsic");
7882
7883     case Intrinsic::arm_neon_vshiftn:
7884     case Intrinsic::arm_neon_vrshiftn:
7885     case Intrinsic::arm_neon_vqshiftns:
7886     case Intrinsic::arm_neon_vqshiftnu:
7887     case Intrinsic::arm_neon_vqshiftnsu:
7888     case Intrinsic::arm_neon_vqrshiftns:
7889     case Intrinsic::arm_neon_vqrshiftnu:
7890     case Intrinsic::arm_neon_vqrshiftnsu:
7891       // Narrowing shifts require an immediate right shift.
7892       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
7893         break;
7894       llvm_unreachable("invalid shift count for narrowing vector shift "
7895                        "intrinsic");
7896
7897     default:
7898       llvm_unreachable("unhandled vector shift");
7899     }
7900
7901     switch (IntNo) {
7902     case Intrinsic::arm_neon_vshifts:
7903     case Intrinsic::arm_neon_vshiftu:
7904       // Opcode already set above.
7905       break;
7906     case Intrinsic::arm_neon_vshiftls:
7907     case Intrinsic::arm_neon_vshiftlu:
7908       if (Cnt == VT.getVectorElementType().getSizeInBits())
7909         VShiftOpc = ARMISD::VSHLLi;
7910       else
7911         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
7912                      ARMISD::VSHLLs : ARMISD::VSHLLu);
7913       break;
7914     case Intrinsic::arm_neon_vshiftn:
7915       VShiftOpc = ARMISD::VSHRN; break;
7916     case Intrinsic::arm_neon_vrshifts:
7917       VShiftOpc = ARMISD::VRSHRs; break;
7918     case Intrinsic::arm_neon_vrshiftu:
7919       VShiftOpc = ARMISD::VRSHRu; break;
7920     case Intrinsic::arm_neon_vrshiftn:
7921       VShiftOpc = ARMISD::VRSHRN; break;
7922     case Intrinsic::arm_neon_vqshifts:
7923       VShiftOpc = ARMISD::VQSHLs; break;
7924     case Intrinsic::arm_neon_vqshiftu:
7925       VShiftOpc = ARMISD::VQSHLu; break;
7926     case Intrinsic::arm_neon_vqshiftsu:
7927       VShiftOpc = ARMISD::VQSHLsu; break;
7928     case Intrinsic::arm_neon_vqshiftns:
7929       VShiftOpc = ARMISD::VQSHRNs; break;
7930     case Intrinsic::arm_neon_vqshiftnu:
7931       VShiftOpc = ARMISD::VQSHRNu; break;
7932     case Intrinsic::arm_neon_vqshiftnsu:
7933       VShiftOpc = ARMISD::VQSHRNsu; break;
7934     case Intrinsic::arm_neon_vqrshiftns:
7935       VShiftOpc = ARMISD::VQRSHRNs; break;
7936     case Intrinsic::arm_neon_vqrshiftnu:
7937       VShiftOpc = ARMISD::VQRSHRNu; break;
7938     case Intrinsic::arm_neon_vqrshiftnsu:
7939       VShiftOpc = ARMISD::VQRSHRNsu; break;
7940     }
7941
7942     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7943                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
7944   }
7945
7946   case Intrinsic::arm_neon_vshiftins: {
7947     EVT VT = N->getOperand(1).getValueType();
7948     int64_t Cnt;
7949     unsigned VShiftOpc = 0;
7950
7951     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
7952       VShiftOpc = ARMISD::VSLI;
7953     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
7954       VShiftOpc = ARMISD::VSRI;
7955     else {
7956       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
7957     }
7958
7959     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7960                        N->getOperand(1), N->getOperand(2),
7961                        DAG.getConstant(Cnt, MVT::i32));
7962   }
7963
7964   case Intrinsic::arm_neon_vqrshifts:
7965   case Intrinsic::arm_neon_vqrshiftu:
7966     // No immediate versions of these to check for.
7967     break;
7968   }
7969
7970   return SDValue();
7971 }
7972
7973 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
7974 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
7975 /// combining instead of DAG legalizing because the build_vectors for 64-bit
7976 /// vector element shift counts are generally not legal, and it is hard to see
7977 /// their values after they get legalized to loads from a constant pool.
7978 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
7979                                    const ARMSubtarget *ST) {
7980   EVT VT = N->getValueType(0);
7981   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
7982     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
7983     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
7984     SDValue N1 = N->getOperand(1);
7985     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
7986       SDValue N0 = N->getOperand(0);
7987       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
7988           DAG.MaskedValueIsZero(N0.getOperand(0),
7989                                 APInt::getHighBitsSet(32, 16)))
7990         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
7991     }
7992   }
7993
7994   // Nothing to be done for scalar shifts.
7995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7996   if (!VT.isVector() || !TLI.isTypeLegal(VT))
7997     return SDValue();
7998
7999   assert(ST->hasNEON() && "unexpected vector shift");
8000   int64_t Cnt;
8001
8002   switch (N->getOpcode()) {
8003   default: llvm_unreachable("unexpected shift opcode");
8004
8005   case ISD::SHL:
8006     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8007       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8008                          DAG.getConstant(Cnt, MVT::i32));
8009     break;
8010
8011   case ISD::SRA:
8012   case ISD::SRL:
8013     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8014       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8015                             ARMISD::VSHRs : ARMISD::VSHRu);
8016       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8017                          DAG.getConstant(Cnt, MVT::i32));
8018     }
8019   }
8020   return SDValue();
8021 }
8022
8023 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8024 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8025 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8026                                     const ARMSubtarget *ST) {
8027   SDValue N0 = N->getOperand(0);
8028
8029   // Check for sign- and zero-extensions of vector extract operations of 8-
8030   // and 16-bit vector elements.  NEON supports these directly.  They are
8031   // handled during DAG combining because type legalization will promote them
8032   // to 32-bit types and it is messy to recognize the operations after that.
8033   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8034     SDValue Vec = N0.getOperand(0);
8035     SDValue Lane = N0.getOperand(1);
8036     EVT VT = N->getValueType(0);
8037     EVT EltVT = N0.getValueType();
8038     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8039
8040     if (VT == MVT::i32 &&
8041         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8042         TLI.isTypeLegal(Vec.getValueType()) &&
8043         isa<ConstantSDNode>(Lane)) {
8044
8045       unsigned Opc = 0;
8046       switch (N->getOpcode()) {
8047       default: llvm_unreachable("unexpected opcode");
8048       case ISD::SIGN_EXTEND:
8049         Opc = ARMISD::VGETLANEs;
8050         break;
8051       case ISD::ZERO_EXTEND:
8052       case ISD::ANY_EXTEND:
8053         Opc = ARMISD::VGETLANEu;
8054         break;
8055       }
8056       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8057     }
8058   }
8059
8060   return SDValue();
8061 }
8062
8063 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8064 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8065 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8066                                        const ARMSubtarget *ST) {
8067   // If the target supports NEON, try to use vmax/vmin instructions for f32
8068   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8069   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8070   // a NaN; only do the transformation when it matches that behavior.
8071
8072   // For now only do this when using NEON for FP operations; if using VFP, it
8073   // is not obvious that the benefit outweighs the cost of switching to the
8074   // NEON pipeline.
8075   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8076       N->getValueType(0) != MVT::f32)
8077     return SDValue();
8078
8079   SDValue CondLHS = N->getOperand(0);
8080   SDValue CondRHS = N->getOperand(1);
8081   SDValue LHS = N->getOperand(2);
8082   SDValue RHS = N->getOperand(3);
8083   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8084
8085   unsigned Opcode = 0;
8086   bool IsReversed;
8087   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8088     IsReversed = false; // x CC y ? x : y
8089   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8090     IsReversed = true ; // x CC y ? y : x
8091   } else {
8092     return SDValue();
8093   }
8094
8095   bool IsUnordered;
8096   switch (CC) {
8097   default: break;
8098   case ISD::SETOLT:
8099   case ISD::SETOLE:
8100   case ISD::SETLT:
8101   case ISD::SETLE:
8102   case ISD::SETULT:
8103   case ISD::SETULE:
8104     // If LHS is NaN, an ordered comparison will be false and the result will
8105     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8106     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8107     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8108     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8109       break;
8110     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8111     // will return -0, so vmin can only be used for unsafe math or if one of
8112     // the operands is known to be nonzero.
8113     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8114         !DAG.getTarget().Options.UnsafeFPMath &&
8115         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8116       break;
8117     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8118     break;
8119
8120   case ISD::SETOGT:
8121   case ISD::SETOGE:
8122   case ISD::SETGT:
8123   case ISD::SETGE:
8124   case ISD::SETUGT:
8125   case ISD::SETUGE:
8126     // If LHS is NaN, an ordered comparison will be false and the result will
8127     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8128     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8129     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8130     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8131       break;
8132     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8133     // will return +0, so vmax can only be used for unsafe math or if one of
8134     // the operands is known to be nonzero.
8135     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8136         !DAG.getTarget().Options.UnsafeFPMath &&
8137         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8138       break;
8139     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8140     break;
8141   }
8142
8143   if (!Opcode)
8144     return SDValue();
8145   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8146 }
8147
8148 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8149 SDValue
8150 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8151   SDValue Cmp = N->getOperand(4);
8152   if (Cmp.getOpcode() != ARMISD::CMPZ)
8153     // Only looking at EQ and NE cases.
8154     return SDValue();
8155
8156   EVT VT = N->getValueType(0);
8157   DebugLoc dl = N->getDebugLoc();
8158   SDValue LHS = Cmp.getOperand(0);
8159   SDValue RHS = Cmp.getOperand(1);
8160   SDValue FalseVal = N->getOperand(0);
8161   SDValue TrueVal = N->getOperand(1);
8162   SDValue ARMcc = N->getOperand(2);
8163   ARMCC::CondCodes CC =
8164     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8165
8166   // Simplify
8167   //   mov     r1, r0
8168   //   cmp     r1, x
8169   //   mov     r0, y
8170   //   moveq   r0, x
8171   // to
8172   //   cmp     r0, x
8173   //   movne   r0, y
8174   //
8175   //   mov     r1, r0
8176   //   cmp     r1, x
8177   //   mov     r0, x
8178   //   movne   r0, y
8179   // to
8180   //   cmp     r0, x
8181   //   movne   r0, y
8182   /// FIXME: Turn this into a target neutral optimization?
8183   SDValue Res;
8184   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8185     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8186                       N->getOperand(3), Cmp);
8187   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8188     SDValue ARMcc;
8189     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8190     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8191                       N->getOperand(3), NewCmp);
8192   }
8193
8194   if (Res.getNode()) {
8195     APInt KnownZero, KnownOne;
8196     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
8197     DAG.ComputeMaskedBits(SDValue(N,0), Mask, KnownZero, KnownOne);
8198     // Capture demanded bits information that would be otherwise lost.
8199     if (KnownZero == 0xfffffffe)
8200       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8201                         DAG.getValueType(MVT::i1));
8202     else if (KnownZero == 0xffffff00)
8203       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8204                         DAG.getValueType(MVT::i8));
8205     else if (KnownZero == 0xffff0000)
8206       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8207                         DAG.getValueType(MVT::i16));
8208   }
8209
8210   return Res;
8211 }
8212
8213 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8214                                              DAGCombinerInfo &DCI) const {
8215   switch (N->getOpcode()) {
8216   default: break;
8217   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8218   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8219   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8220   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8221   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8222   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8223   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8224   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8225   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8226   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8227   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8228   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8229   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8230   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8231   case ISD::FP_TO_SINT:
8232   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8233   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8234   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8235   case ISD::SHL:
8236   case ISD::SRA:
8237   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8238   case ISD::SIGN_EXTEND:
8239   case ISD::ZERO_EXTEND:
8240   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8241   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8242   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8243   case ARMISD::VLD2DUP:
8244   case ARMISD::VLD3DUP:
8245   case ARMISD::VLD4DUP:
8246     return CombineBaseUpdate(N, DCI);
8247   case ISD::INTRINSIC_VOID:
8248   case ISD::INTRINSIC_W_CHAIN:
8249     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8250     case Intrinsic::arm_neon_vld1:
8251     case Intrinsic::arm_neon_vld2:
8252     case Intrinsic::arm_neon_vld3:
8253     case Intrinsic::arm_neon_vld4:
8254     case Intrinsic::arm_neon_vld2lane:
8255     case Intrinsic::arm_neon_vld3lane:
8256     case Intrinsic::arm_neon_vld4lane:
8257     case Intrinsic::arm_neon_vst1:
8258     case Intrinsic::arm_neon_vst2:
8259     case Intrinsic::arm_neon_vst3:
8260     case Intrinsic::arm_neon_vst4:
8261     case Intrinsic::arm_neon_vst2lane:
8262     case Intrinsic::arm_neon_vst3lane:
8263     case Intrinsic::arm_neon_vst4lane:
8264       return CombineBaseUpdate(N, DCI);
8265     default: break;
8266     }
8267     break;
8268   }
8269   return SDValue();
8270 }
8271
8272 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8273                                                           EVT VT) const {
8274   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8275 }
8276
8277 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8278   if (!Subtarget->allowsUnalignedMem())
8279     return false;
8280
8281   switch (VT.getSimpleVT().SimpleTy) {
8282   default:
8283     return false;
8284   case MVT::i8:
8285   case MVT::i16:
8286   case MVT::i32:
8287     return true;
8288   // FIXME: VLD1 etc with standard alignment is legal.
8289   }
8290 }
8291
8292 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8293                        unsigned AlignCheck) {
8294   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8295           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8296 }
8297
8298 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8299                                            unsigned DstAlign, unsigned SrcAlign,
8300                                            bool IsZeroVal,
8301                                            bool MemcpyStrSrc,
8302                                            MachineFunction &MF) const {
8303   const Function *F = MF.getFunction();
8304
8305   // See if we can use NEON instructions for this...
8306   if (IsZeroVal &&
8307       !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8308       Subtarget->hasNEON()) {
8309     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8310       return MVT::v4i32;
8311     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8312       return MVT::v2i32;
8313     }
8314   }
8315
8316   // Lowering to i32/i16 if the size permits.
8317   if (Size >= 4) {
8318     return MVT::i32;
8319   } else if (Size >= 2) {
8320     return MVT::i16;
8321   }
8322
8323   // Let the target-independent logic figure it out.
8324   return MVT::Other;
8325 }
8326
8327 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8328   if (V < 0)
8329     return false;
8330
8331   unsigned Scale = 1;
8332   switch (VT.getSimpleVT().SimpleTy) {
8333   default: return false;
8334   case MVT::i1:
8335   case MVT::i8:
8336     // Scale == 1;
8337     break;
8338   case MVT::i16:
8339     // Scale == 2;
8340     Scale = 2;
8341     break;
8342   case MVT::i32:
8343     // Scale == 4;
8344     Scale = 4;
8345     break;
8346   }
8347
8348   if ((V & (Scale - 1)) != 0)
8349     return false;
8350   V /= Scale;
8351   return V == (V & ((1LL << 5) - 1));
8352 }
8353
8354 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8355                                       const ARMSubtarget *Subtarget) {
8356   bool isNeg = false;
8357   if (V < 0) {
8358     isNeg = true;
8359     V = - V;
8360   }
8361
8362   switch (VT.getSimpleVT().SimpleTy) {
8363   default: return false;
8364   case MVT::i1:
8365   case MVT::i8:
8366   case MVT::i16:
8367   case MVT::i32:
8368     // + imm12 or - imm8
8369     if (isNeg)
8370       return V == (V & ((1LL << 8) - 1));
8371     return V == (V & ((1LL << 12) - 1));
8372   case MVT::f32:
8373   case MVT::f64:
8374     // Same as ARM mode. FIXME: NEON?
8375     if (!Subtarget->hasVFP2())
8376       return false;
8377     if ((V & 3) != 0)
8378       return false;
8379     V >>= 2;
8380     return V == (V & ((1LL << 8) - 1));
8381   }
8382 }
8383
8384 /// isLegalAddressImmediate - Return true if the integer value can be used
8385 /// as the offset of the target addressing mode for load / store of the
8386 /// given type.
8387 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8388                                     const ARMSubtarget *Subtarget) {
8389   if (V == 0)
8390     return true;
8391
8392   if (!VT.isSimple())
8393     return false;
8394
8395   if (Subtarget->isThumb1Only())
8396     return isLegalT1AddressImmediate(V, VT);
8397   else if (Subtarget->isThumb2())
8398     return isLegalT2AddressImmediate(V, VT, Subtarget);
8399
8400   // ARM mode.
8401   if (V < 0)
8402     V = - V;
8403   switch (VT.getSimpleVT().SimpleTy) {
8404   default: return false;
8405   case MVT::i1:
8406   case MVT::i8:
8407   case MVT::i32:
8408     // +- imm12
8409     return V == (V & ((1LL << 12) - 1));
8410   case MVT::i16:
8411     // +- imm8
8412     return V == (V & ((1LL << 8) - 1));
8413   case MVT::f32:
8414   case MVT::f64:
8415     if (!Subtarget->hasVFP2()) // FIXME: NEON?
8416       return false;
8417     if ((V & 3) != 0)
8418       return false;
8419     V >>= 2;
8420     return V == (V & ((1LL << 8) - 1));
8421   }
8422 }
8423
8424 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8425                                                       EVT VT) const {
8426   int Scale = AM.Scale;
8427   if (Scale < 0)
8428     return false;
8429
8430   switch (VT.getSimpleVT().SimpleTy) {
8431   default: return false;
8432   case MVT::i1:
8433   case MVT::i8:
8434   case MVT::i16:
8435   case MVT::i32:
8436     if (Scale == 1)
8437       return true;
8438     // r + r << imm
8439     Scale = Scale & ~1;
8440     return Scale == 2 || Scale == 4 || Scale == 8;
8441   case MVT::i64:
8442     // r + r
8443     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8444       return true;
8445     return false;
8446   case MVT::isVoid:
8447     // Note, we allow "void" uses (basically, uses that aren't loads or
8448     // stores), because arm allows folding a scale into many arithmetic
8449     // operations.  This should be made more precise and revisited later.
8450
8451     // Allow r << imm, but the imm has to be a multiple of two.
8452     if (Scale & 1) return false;
8453     return isPowerOf2_32(Scale);
8454   }
8455 }
8456
8457 /// isLegalAddressingMode - Return true if the addressing mode represented
8458 /// by AM is legal for this target, for a load/store of the specified type.
8459 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8460                                               Type *Ty) const {
8461   EVT VT = getValueType(Ty, true);
8462   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8463     return false;
8464
8465   // Can never fold addr of global into load/store.
8466   if (AM.BaseGV)
8467     return false;
8468
8469   switch (AM.Scale) {
8470   case 0:  // no scale reg, must be "r+i" or "r", or "i".
8471     break;
8472   case 1:
8473     if (Subtarget->isThumb1Only())
8474       return false;
8475     // FALL THROUGH.
8476   default:
8477     // ARM doesn't support any R+R*scale+imm addr modes.
8478     if (AM.BaseOffs)
8479       return false;
8480
8481     if (!VT.isSimple())
8482       return false;
8483
8484     if (Subtarget->isThumb2())
8485       return isLegalT2ScaledAddressingMode(AM, VT);
8486
8487     int Scale = AM.Scale;
8488     switch (VT.getSimpleVT().SimpleTy) {
8489     default: return false;
8490     case MVT::i1:
8491     case MVT::i8:
8492     case MVT::i32:
8493       if (Scale < 0) Scale = -Scale;
8494       if (Scale == 1)
8495         return true;
8496       // r + r << imm
8497       return isPowerOf2_32(Scale & ~1);
8498     case MVT::i16:
8499     case MVT::i64:
8500       // r + r
8501       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8502         return true;
8503       return false;
8504
8505     case MVT::isVoid:
8506       // Note, we allow "void" uses (basically, uses that aren't loads or
8507       // stores), because arm allows folding a scale into many arithmetic
8508       // operations.  This should be made more precise and revisited later.
8509
8510       // Allow r << imm, but the imm has to be a multiple of two.
8511       if (Scale & 1) return false;
8512       return isPowerOf2_32(Scale);
8513     }
8514   }
8515   return true;
8516 }
8517
8518 /// isLegalICmpImmediate - Return true if the specified immediate is legal
8519 /// icmp immediate, that is the target has icmp instructions which can compare
8520 /// a register against the immediate without having to materialize the
8521 /// immediate into a register.
8522 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8523   if (!Subtarget->isThumb())
8524     return ARM_AM::getSOImmVal(Imm) != -1;
8525   if (Subtarget->isThumb2())
8526     return ARM_AM::getT2SOImmVal(Imm) != -1;
8527   return Imm >= 0 && Imm <= 255;
8528 }
8529
8530 /// isLegalAddImmediate - Return true if the specified immediate is legal
8531 /// add immediate, that is the target has add instructions which can add
8532 /// a register with the immediate without having to materialize the
8533 /// immediate into a register.
8534 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8535   return ARM_AM::getSOImmVal(Imm) != -1;
8536 }
8537
8538 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8539                                       bool isSEXTLoad, SDValue &Base,
8540                                       SDValue &Offset, bool &isInc,
8541                                       SelectionDAG &DAG) {
8542   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8543     return false;
8544
8545   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8546     // AddressingMode 3
8547     Base = Ptr->getOperand(0);
8548     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8549       int RHSC = (int)RHS->getZExtValue();
8550       if (RHSC < 0 && RHSC > -256) {
8551         assert(Ptr->getOpcode() == ISD::ADD);
8552         isInc = false;
8553         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8554         return true;
8555       }
8556     }
8557     isInc = (Ptr->getOpcode() == ISD::ADD);
8558     Offset = Ptr->getOperand(1);
8559     return true;
8560   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8561     // AddressingMode 2
8562     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8563       int RHSC = (int)RHS->getZExtValue();
8564       if (RHSC < 0 && RHSC > -0x1000) {
8565         assert(Ptr->getOpcode() == ISD::ADD);
8566         isInc = false;
8567         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8568         Base = Ptr->getOperand(0);
8569         return true;
8570       }
8571     }
8572
8573     if (Ptr->getOpcode() == ISD::ADD) {
8574       isInc = true;
8575       ARM_AM::ShiftOpc ShOpcVal=
8576         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8577       if (ShOpcVal != ARM_AM::no_shift) {
8578         Base = Ptr->getOperand(1);
8579         Offset = Ptr->getOperand(0);
8580       } else {
8581         Base = Ptr->getOperand(0);
8582         Offset = Ptr->getOperand(1);
8583       }
8584       return true;
8585     }
8586
8587     isInc = (Ptr->getOpcode() == ISD::ADD);
8588     Base = Ptr->getOperand(0);
8589     Offset = Ptr->getOperand(1);
8590     return true;
8591   }
8592
8593   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8594   return false;
8595 }
8596
8597 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8598                                      bool isSEXTLoad, SDValue &Base,
8599                                      SDValue &Offset, bool &isInc,
8600                                      SelectionDAG &DAG) {
8601   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8602     return false;
8603
8604   Base = Ptr->getOperand(0);
8605   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8606     int RHSC = (int)RHS->getZExtValue();
8607     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8608       assert(Ptr->getOpcode() == ISD::ADD);
8609       isInc = false;
8610       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8611       return true;
8612     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8613       isInc = Ptr->getOpcode() == ISD::ADD;
8614       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8615       return true;
8616     }
8617   }
8618
8619   return false;
8620 }
8621
8622 /// getPreIndexedAddressParts - returns true by value, base pointer and
8623 /// offset pointer and addressing mode by reference if the node's address
8624 /// can be legally represented as pre-indexed load / store address.
8625 bool
8626 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8627                                              SDValue &Offset,
8628                                              ISD::MemIndexedMode &AM,
8629                                              SelectionDAG &DAG) const {
8630   if (Subtarget->isThumb1Only())
8631     return false;
8632
8633   EVT VT;
8634   SDValue Ptr;
8635   bool isSEXTLoad = false;
8636   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8637     Ptr = LD->getBasePtr();
8638     VT  = LD->getMemoryVT();
8639     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8640   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8641     Ptr = ST->getBasePtr();
8642     VT  = ST->getMemoryVT();
8643   } else
8644     return false;
8645
8646   bool isInc;
8647   bool isLegal = false;
8648   if (Subtarget->isThumb2())
8649     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8650                                        Offset, isInc, DAG);
8651   else
8652     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8653                                         Offset, isInc, DAG);
8654   if (!isLegal)
8655     return false;
8656
8657   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8658   return true;
8659 }
8660
8661 /// getPostIndexedAddressParts - returns true by value, base pointer and
8662 /// offset pointer and addressing mode by reference if this node can be
8663 /// combined with a load / store to form a post-indexed load / store.
8664 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8665                                                    SDValue &Base,
8666                                                    SDValue &Offset,
8667                                                    ISD::MemIndexedMode &AM,
8668                                                    SelectionDAG &DAG) const {
8669   if (Subtarget->isThumb1Only())
8670     return false;
8671
8672   EVT VT;
8673   SDValue Ptr;
8674   bool isSEXTLoad = false;
8675   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8676     VT  = LD->getMemoryVT();
8677     Ptr = LD->getBasePtr();
8678     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8679   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8680     VT  = ST->getMemoryVT();
8681     Ptr = ST->getBasePtr();
8682   } else
8683     return false;
8684
8685   bool isInc;
8686   bool isLegal = false;
8687   if (Subtarget->isThumb2())
8688     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8689                                        isInc, DAG);
8690   else
8691     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8692                                         isInc, DAG);
8693   if (!isLegal)
8694     return false;
8695
8696   if (Ptr != Base) {
8697     // Swap base ptr and offset to catch more post-index load / store when
8698     // it's legal. In Thumb2 mode, offset must be an immediate.
8699     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8700         !Subtarget->isThumb2())
8701       std::swap(Base, Offset);
8702
8703     // Post-indexed load / store update the base pointer.
8704     if (Ptr != Base)
8705       return false;
8706   }
8707
8708   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8709   return true;
8710 }
8711
8712 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8713                                                        const APInt &Mask,
8714                                                        APInt &KnownZero,
8715                                                        APInt &KnownOne,
8716                                                        const SelectionDAG &DAG,
8717                                                        unsigned Depth) const {
8718   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
8719   switch (Op.getOpcode()) {
8720   default: break;
8721   case ARMISD::CMOV: {
8722     // Bits are known zero/one if known on the LHS and RHS.
8723     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
8724     if (KnownZero == 0 && KnownOne == 0) return;
8725
8726     APInt KnownZeroRHS, KnownOneRHS;
8727     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
8728                           KnownZeroRHS, KnownOneRHS, Depth+1);
8729     KnownZero &= KnownZeroRHS;
8730     KnownOne  &= KnownOneRHS;
8731     return;
8732   }
8733   }
8734 }
8735
8736 //===----------------------------------------------------------------------===//
8737 //                           ARM Inline Assembly Support
8738 //===----------------------------------------------------------------------===//
8739
8740 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8741   // Looking for "rev" which is V6+.
8742   if (!Subtarget->hasV6Ops())
8743     return false;
8744
8745   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8746   std::string AsmStr = IA->getAsmString();
8747   SmallVector<StringRef, 4> AsmPieces;
8748   SplitString(AsmStr, AsmPieces, ";\n");
8749
8750   switch (AsmPieces.size()) {
8751   default: return false;
8752   case 1:
8753     AsmStr = AsmPieces[0];
8754     AsmPieces.clear();
8755     SplitString(AsmStr, AsmPieces, " \t,");
8756
8757     // rev $0, $1
8758     if (AsmPieces.size() == 3 &&
8759         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8760         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8761       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8762       if (Ty && Ty->getBitWidth() == 32)
8763         return IntrinsicLowering::LowerToByteSwap(CI);
8764     }
8765     break;
8766   }
8767
8768   return false;
8769 }
8770
8771 /// getConstraintType - Given a constraint letter, return the type of
8772 /// constraint it is for this target.
8773 ARMTargetLowering::ConstraintType
8774 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8775   if (Constraint.size() == 1) {
8776     switch (Constraint[0]) {
8777     default:  break;
8778     case 'l': return C_RegisterClass;
8779     case 'w': return C_RegisterClass;
8780     case 'h': return C_RegisterClass;
8781     case 'x': return C_RegisterClass;
8782     case 't': return C_RegisterClass;
8783     case 'j': return C_Other; // Constant for movw.
8784       // An address with a single base register. Due to the way we
8785       // currently handle addresses it is the same as an 'r' memory constraint.
8786     case 'Q': return C_Memory;
8787     }
8788   } else if (Constraint.size() == 2) {
8789     switch (Constraint[0]) {
8790     default: break;
8791     // All 'U+' constraints are addresses.
8792     case 'U': return C_Memory;
8793     }
8794   }
8795   return TargetLowering::getConstraintType(Constraint);
8796 }
8797
8798 /// Examine constraint type and operand type and determine a weight value.
8799 /// This object must already have been set up with the operand type
8800 /// and the current alternative constraint selected.
8801 TargetLowering::ConstraintWeight
8802 ARMTargetLowering::getSingleConstraintMatchWeight(
8803     AsmOperandInfo &info, const char *constraint) const {
8804   ConstraintWeight weight = CW_Invalid;
8805   Value *CallOperandVal = info.CallOperandVal;
8806     // If we don't have a value, we can't do a match,
8807     // but allow it at the lowest weight.
8808   if (CallOperandVal == NULL)
8809     return CW_Default;
8810   Type *type = CallOperandVal->getType();
8811   // Look at the constraint type.
8812   switch (*constraint) {
8813   default:
8814     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8815     break;
8816   case 'l':
8817     if (type->isIntegerTy()) {
8818       if (Subtarget->isThumb())
8819         weight = CW_SpecificReg;
8820       else
8821         weight = CW_Register;
8822     }
8823     break;
8824   case 'w':
8825     if (type->isFloatingPointTy())
8826       weight = CW_Register;
8827     break;
8828   }
8829   return weight;
8830 }
8831
8832 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
8833 RCPair
8834 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8835                                                 EVT VT) const {
8836   if (Constraint.size() == 1) {
8837     // GCC ARM Constraint Letters
8838     switch (Constraint[0]) {
8839     case 'l': // Low regs or general regs.
8840       if (Subtarget->isThumb())
8841         return RCPair(0U, ARM::tGPRRegisterClass);
8842       else
8843         return RCPair(0U, ARM::GPRRegisterClass);
8844     case 'h': // High regs or no regs.
8845       if (Subtarget->isThumb())
8846         return RCPair(0U, ARM::hGPRRegisterClass);
8847       break;
8848     case 'r':
8849       return RCPair(0U, ARM::GPRRegisterClass);
8850     case 'w':
8851       if (VT == MVT::f32)
8852         return RCPair(0U, ARM::SPRRegisterClass);
8853       if (VT.getSizeInBits() == 64)
8854         return RCPair(0U, ARM::DPRRegisterClass);
8855       if (VT.getSizeInBits() == 128)
8856         return RCPair(0U, ARM::QPRRegisterClass);
8857       break;
8858     case 'x':
8859       if (VT == MVT::f32)
8860         return RCPair(0U, ARM::SPR_8RegisterClass);
8861       if (VT.getSizeInBits() == 64)
8862         return RCPair(0U, ARM::DPR_8RegisterClass);
8863       if (VT.getSizeInBits() == 128)
8864         return RCPair(0U, ARM::QPR_8RegisterClass);
8865       break;
8866     case 't':
8867       if (VT == MVT::f32)
8868         return RCPair(0U, ARM::SPRRegisterClass);
8869       break;
8870     }
8871   }
8872   if (StringRef("{cc}").equals_lower(Constraint))
8873     return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
8874
8875   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8876 }
8877
8878 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8879 /// vector.  If it is invalid, don't add anything to Ops.
8880 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8881                                                      std::string &Constraint,
8882                                                      std::vector<SDValue>&Ops,
8883                                                      SelectionDAG &DAG) const {
8884   SDValue Result(0, 0);
8885
8886   // Currently only support length 1 constraints.
8887   if (Constraint.length() != 1) return;
8888
8889   char ConstraintLetter = Constraint[0];
8890   switch (ConstraintLetter) {
8891   default: break;
8892   case 'j':
8893   case 'I': case 'J': case 'K': case 'L':
8894   case 'M': case 'N': case 'O':
8895     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8896     if (!C)
8897       return;
8898
8899     int64_t CVal64 = C->getSExtValue();
8900     int CVal = (int) CVal64;
8901     // None of these constraints allow values larger than 32 bits.  Check
8902     // that the value fits in an int.
8903     if (CVal != CVal64)
8904       return;
8905
8906     switch (ConstraintLetter) {
8907       case 'j':
8908         // Constant suitable for movw, must be between 0 and
8909         // 65535.
8910         if (Subtarget->hasV6T2Ops())
8911           if (CVal >= 0 && CVal <= 65535)
8912             break;
8913         return;
8914       case 'I':
8915         if (Subtarget->isThumb1Only()) {
8916           // This must be a constant between 0 and 255, for ADD
8917           // immediates.
8918           if (CVal >= 0 && CVal <= 255)
8919             break;
8920         } else if (Subtarget->isThumb2()) {
8921           // A constant that can be used as an immediate value in a
8922           // data-processing instruction.
8923           if (ARM_AM::getT2SOImmVal(CVal) != -1)
8924             break;
8925         } else {
8926           // A constant that can be used as an immediate value in a
8927           // data-processing instruction.
8928           if (ARM_AM::getSOImmVal(CVal) != -1)
8929             break;
8930         }
8931         return;
8932
8933       case 'J':
8934         if (Subtarget->isThumb()) {  // FIXME thumb2
8935           // This must be a constant between -255 and -1, for negated ADD
8936           // immediates. This can be used in GCC with an "n" modifier that
8937           // prints the negated value, for use with SUB instructions. It is
8938           // not useful otherwise but is implemented for compatibility.
8939           if (CVal >= -255 && CVal <= -1)
8940             break;
8941         } else {
8942           // This must be a constant between -4095 and 4095. It is not clear
8943           // what this constraint is intended for. Implemented for
8944           // compatibility with GCC.
8945           if (CVal >= -4095 && CVal <= 4095)
8946             break;
8947         }
8948         return;
8949
8950       case 'K':
8951         if (Subtarget->isThumb1Only()) {
8952           // A 32-bit value where only one byte has a nonzero value. Exclude
8953           // zero to match GCC. This constraint is used by GCC internally for
8954           // constants that can be loaded with a move/shift combination.
8955           // It is not useful otherwise but is implemented for compatibility.
8956           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
8957             break;
8958         } else if (Subtarget->isThumb2()) {
8959           // A constant whose bitwise inverse can be used as an immediate
8960           // value in a data-processing instruction. This can be used in GCC
8961           // with a "B" modifier that prints the inverted value, for use with
8962           // BIC and MVN instructions. It is not useful otherwise but is
8963           // implemented for compatibility.
8964           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
8965             break;
8966         } else {
8967           // A constant whose bitwise inverse can be used as an immediate
8968           // value in a data-processing instruction. This can be used in GCC
8969           // with a "B" modifier that prints the inverted value, for use with
8970           // BIC and MVN instructions. It is not useful otherwise but is
8971           // implemented for compatibility.
8972           if (ARM_AM::getSOImmVal(~CVal) != -1)
8973             break;
8974         }
8975         return;
8976
8977       case 'L':
8978         if (Subtarget->isThumb1Only()) {
8979           // This must be a constant between -7 and 7,
8980           // for 3-operand ADD/SUB immediate instructions.
8981           if (CVal >= -7 && CVal < 7)
8982             break;
8983         } else if (Subtarget->isThumb2()) {
8984           // A constant whose negation can be used as an immediate value in a
8985           // data-processing instruction. This can be used in GCC with an "n"
8986           // modifier that prints the negated value, for use with SUB
8987           // instructions. It is not useful otherwise but is implemented for
8988           // compatibility.
8989           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
8990             break;
8991         } else {
8992           // A constant whose negation can be used as an immediate value in a
8993           // data-processing instruction. This can be used in GCC with an "n"
8994           // modifier that prints the negated value, for use with SUB
8995           // instructions. It is not useful otherwise but is implemented for
8996           // compatibility.
8997           if (ARM_AM::getSOImmVal(-CVal) != -1)
8998             break;
8999         }
9000         return;
9001
9002       case 'M':
9003         if (Subtarget->isThumb()) { // FIXME thumb2
9004           // This must be a multiple of 4 between 0 and 1020, for
9005           // ADD sp + immediate.
9006           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9007             break;
9008         } else {
9009           // A power of two or a constant between 0 and 32.  This is used in
9010           // GCC for the shift amount on shifted register operands, but it is
9011           // useful in general for any shift amounts.
9012           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9013             break;
9014         }
9015         return;
9016
9017       case 'N':
9018         if (Subtarget->isThumb()) {  // FIXME thumb2
9019           // This must be a constant between 0 and 31, for shift amounts.
9020           if (CVal >= 0 && CVal <= 31)
9021             break;
9022         }
9023         return;
9024
9025       case 'O':
9026         if (Subtarget->isThumb()) {  // FIXME thumb2
9027           // This must be a multiple of 4 between -508 and 508, for
9028           // ADD/SUB sp = sp + immediate.
9029           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9030             break;
9031         }
9032         return;
9033     }
9034     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9035     break;
9036   }
9037
9038   if (Result.getNode()) {
9039     Ops.push_back(Result);
9040     return;
9041   }
9042   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9043 }
9044
9045 bool
9046 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9047   // The ARM target isn't yet aware of offsets.
9048   return false;
9049 }
9050
9051 bool ARM::isBitFieldInvertedMask(unsigned v) {
9052   if (v == 0xffffffff)
9053     return 0;
9054   // there can be 1's on either or both "outsides", all the "inside"
9055   // bits must be 0's
9056   unsigned int lsb = 0, msb = 31;
9057   while (v & (1 << msb)) --msb;
9058   while (v & (1 << lsb)) ++lsb;
9059   for (unsigned int i = lsb; i <= msb; ++i) {
9060     if (v & (1 << i))
9061       return 0;
9062   }
9063   return 1;
9064 }
9065
9066 /// isFPImmLegal - Returns true if the target can instruction select the
9067 /// specified FP immediate natively. If false, the legalizer will
9068 /// materialize the FP immediate as a load from a constant pool.
9069 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9070   if (!Subtarget->hasVFP3())
9071     return false;
9072   if (VT == MVT::f32)
9073     return ARM_AM::getFP32Imm(Imm) != -1;
9074   if (VT == MVT::f64)
9075     return ARM_AM::getFP64Imm(Imm) != -1;
9076   return false;
9077 }
9078
9079 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9080 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9081 /// specified in the intrinsic calls.
9082 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9083                                            const CallInst &I,
9084                                            unsigned Intrinsic) const {
9085   switch (Intrinsic) {
9086   case Intrinsic::arm_neon_vld1:
9087   case Intrinsic::arm_neon_vld2:
9088   case Intrinsic::arm_neon_vld3:
9089   case Intrinsic::arm_neon_vld4:
9090   case Intrinsic::arm_neon_vld2lane:
9091   case Intrinsic::arm_neon_vld3lane:
9092   case Intrinsic::arm_neon_vld4lane: {
9093     Info.opc = ISD::INTRINSIC_W_CHAIN;
9094     // Conservatively set memVT to the entire set of vectors loaded.
9095     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9096     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9097     Info.ptrVal = I.getArgOperand(0);
9098     Info.offset = 0;
9099     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9100     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9101     Info.vol = false; // volatile loads with NEON intrinsics not supported
9102     Info.readMem = true;
9103     Info.writeMem = false;
9104     return true;
9105   }
9106   case Intrinsic::arm_neon_vst1:
9107   case Intrinsic::arm_neon_vst2:
9108   case Intrinsic::arm_neon_vst3:
9109   case Intrinsic::arm_neon_vst4:
9110   case Intrinsic::arm_neon_vst2lane:
9111   case Intrinsic::arm_neon_vst3lane:
9112   case Intrinsic::arm_neon_vst4lane: {
9113     Info.opc = ISD::INTRINSIC_VOID;
9114     // Conservatively set memVT to the entire set of vectors stored.
9115     unsigned NumElts = 0;
9116     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9117       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9118       if (!ArgTy->isVectorTy())
9119         break;
9120       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9121     }
9122     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9123     Info.ptrVal = I.getArgOperand(0);
9124     Info.offset = 0;
9125     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9126     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9127     Info.vol = false; // volatile stores with NEON intrinsics not supported
9128     Info.readMem = false;
9129     Info.writeMem = true;
9130     return true;
9131   }
9132   case Intrinsic::arm_strexd: {
9133     Info.opc = ISD::INTRINSIC_W_CHAIN;
9134     Info.memVT = MVT::i64;
9135     Info.ptrVal = I.getArgOperand(2);
9136     Info.offset = 0;
9137     Info.align = 8;
9138     Info.vol = true;
9139     Info.readMem = false;
9140     Info.writeMem = true;
9141     return true;
9142   }
9143   case Intrinsic::arm_ldrexd: {
9144     Info.opc = ISD::INTRINSIC_W_CHAIN;
9145     Info.memVT = MVT::i64;
9146     Info.ptrVal = I.getArgOperand(0);
9147     Info.offset = 0;
9148     Info.align = 8;
9149     Info.vol = true;
9150     Info.readMem = true;
9151     Info.writeMem = false;
9152     return true;
9153   }
9154   default:
9155     break;
9156   }
9157
9158   return false;
9159 }