The getRegForInlineAsmConstraint function should only accept MVT value types.
[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 "ARMISelLowering.h"
17 #include "ARM.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
55 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
56
57 // This option should go away when tail calls fully work.
58 static cl::opt<bool>
59 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
60   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
61   cl::init(false));
62
63 cl::opt<bool>
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65   cl::desc("Generate calls via indirect call instructions"),
66   cl::init(false));
67
68 static cl::opt<bool>
69 ARMInterworking("arm-interworking", cl::Hidden,
70   cl::desc("Enable / disable ARM interworking (for debugging only)"),
71   cl::init(true));
72
73 namespace {
74   class ARMCCState : public CCState {
75   public:
76     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
78                LLVMContext &C, ParmContext PC)
79         : CCState(CC, isVarArg, MF, TM, locs, C) {
80       assert(((PC == Call) || (PC == Prologue)) &&
81              "ARMCCState users must specify whether their context is call"
82              "or prologue generation.");
83       CallOrPrologue = PC;
84     }
85   };
86 }
87
88 // The APCS parameter registers.
89 static const uint16_t GPRArgRegs[] = {
90   ARM::R0, ARM::R1, ARM::R2, ARM::R3
91 };
92
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94                                        MVT PromotedBitwiseVT) {
95   if (VT != PromotedLdStVT) {
96     setOperationAction(ISD::LOAD, VT, Promote);
97     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
98
99     setOperationAction(ISD::STORE, VT, Promote);
100     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
101   }
102
103   MVT ElemTy = VT.getVectorElementType();
104   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105     setOperationAction(ISD::SETCC, VT, Custom);
106   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108   if (ElemTy == MVT::i32) {
109     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
113   } else {
114     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
118   }
119   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
120   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
121   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
122   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123   setOperationAction(ISD::SELECT,            VT, Expand);
124   setOperationAction(ISD::SELECT_CC,         VT, Expand);
125   setOperationAction(ISD::VSELECT,           VT, Expand);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127   if (VT.isInteger()) {
128     setOperationAction(ISD::SHL, VT, Custom);
129     setOperationAction(ISD::SRA, VT, Custom);
130     setOperationAction(ISD::SRL, VT, Custom);
131   }
132
133   // Promote all bit-wise operations.
134   if (VT.isInteger() && VT != PromotedBitwiseVT) {
135     setOperationAction(ISD::AND, VT, Promote);
136     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137     setOperationAction(ISD::OR,  VT, Promote);
138     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
139     setOperationAction(ISD::XOR, VT, Promote);
140     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
141   }
142
143   // Neon does not support vector divide/remainder operations.
144   setOperationAction(ISD::SDIV, VT, Expand);
145   setOperationAction(ISD::UDIV, VT, Expand);
146   setOperationAction(ISD::FDIV, VT, Expand);
147   setOperationAction(ISD::SREM, VT, Expand);
148   setOperationAction(ISD::UREM, VT, Expand);
149   setOperationAction(ISD::FREM, VT, Expand);
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::QPRRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
163   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
164     return new TargetLoweringObjectFileMachO();
165
166   return new ARMElfTargetObjectFile();
167 }
168
169 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
170     : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<ARMSubtarget>();
172   RegInfo = TM.getRegisterInfo();
173   Itins = TM.getInstrItineraryData();
174
175   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
176
177   if (Subtarget->isTargetDarwin()) {
178     // Uses VFP for Thumb libfuncs if available.
179     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
180       // Single-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
182       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
183       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
184       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185
186       // Double-precision floating-point arithmetic.
187       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
188       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
189       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
190       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191
192       // Single-precision comparisons.
193       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
194       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
195       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
196       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
197       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
198       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
199       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
200       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
201
202       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
209       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
210
211       // Double-precision comparisons.
212       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
213       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
214       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
215       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
216       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
217       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
218       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
219       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
220
221       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
228       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
229
230       // Floating-point to integer conversions.
231       // i64 conversions are done via library routines even when generating VFP
232       // instructions, so use the same ones.
233       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
235       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
236       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237
238       // Conversions between floating types.
239       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
240       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
241
242       // Integer to floating-point conversions.
243       // i64 conversions are done via library routines even when generating VFP
244       // instructions, so use the same ones.
245       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
246       // e.g., __floatunsidf vs. __floatunssidfvfp.
247       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
249       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
250       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
251     }
252   }
253
254   // These libcalls are not available in 32-bit.
255   setLibcallName(RTLIB::SHL_I128, 0);
256   setLibcallName(RTLIB::SRL_I128, 0);
257   setLibcallName(RTLIB::SRA_I128, 0);
258
259   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
260     // Double-precision floating-point arithmetic helper functions
261     // RTABI chapter 4.1.2, Table 2
262     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
263     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
264     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
265     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
266     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
267     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
268     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
269     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270
271     // Double-precision floating-point comparison helper functions
272     // RTABI chapter 4.1.2, Table 3
273     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
274     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
275     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
276     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
277     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
278     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
279     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
280     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
281     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
282     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
283     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
284     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
285     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
286     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
287     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
288     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
289     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
294     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297
298     // Single-precision floating-point arithmetic helper functions
299     // RTABI chapter 4.1.2, Table 4
300     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
301     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
302     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
303     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
304     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
305     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
306     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
307     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308
309     // Single-precision floating-point comparison helper functions
310     // RTABI chapter 4.1.2, Table 5
311     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
312     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
313     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
314     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
315     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
316     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
317     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
318     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
319     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
320     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
321     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
322     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
323     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
324     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
325     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
326     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
327     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
332     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335
336     // Floating-point to integer conversions.
337     // RTABI chapter 4.1.2, Table 6
338     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
339     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
340     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
341     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
342     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
343     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
344     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
345     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
346     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
351     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354
355     // Conversions between floating types.
356     // RTABI chapter 4.1.2, Table 7
357     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
358     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
359     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
360     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361
362     // Integer to floating-point conversions.
363     // RTABI chapter 4.1.2, Table 8
364     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
365     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
366     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
367     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
368     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
369     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
370     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
371     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
372     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380
381     // Long long helper functions
382     // RTABI chapter 4.2, Table 9
383     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
384     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
385     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
386     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
387     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
390     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393
394     // Integer division functions
395     // RTABI chapter 4.3.1
396     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
397     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
398     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
399     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
400     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
401     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
402     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
403     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
404     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
409     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
412
413     // Memory operations
414     // RTABI chapter 4.3.4
415     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
416     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
417     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
418     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
419     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
420     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
421   }
422
423   // Use divmod compiler-rt calls for iOS 5.0 and later.
424   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
425       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
426     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
427     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428   }
429
430   if (Subtarget->isThumb1Only())
431     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
432   else
433     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
434   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
435       !Subtarget->isThumb1Only()) {
436     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
437     if (!Subtarget->isFPOnlySP())
438       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
439
440     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441   }
442
443   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
445     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
446          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
447       setTruncStoreAction((MVT::SimpleValueType)VT,
448                           (MVT::SimpleValueType)InnerVT, Expand);
449     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
450     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
452   }
453
454   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
455
456   if (Subtarget->hasNEON()) {
457     addDRTypeForNEON(MVT::v2f32);
458     addDRTypeForNEON(MVT::v8i8);
459     addDRTypeForNEON(MVT::v4i16);
460     addDRTypeForNEON(MVT::v2i32);
461     addDRTypeForNEON(MVT::v1i64);
462
463     addQRTypeForNEON(MVT::v4f32);
464     addQRTypeForNEON(MVT::v2f64);
465     addQRTypeForNEON(MVT::v16i8);
466     addQRTypeForNEON(MVT::v8i16);
467     addQRTypeForNEON(MVT::v4i32);
468     addQRTypeForNEON(MVT::v2i64);
469
470     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
471     // neither Neon nor VFP support any arithmetic operations on it.
472     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
473     // supported for v4f32.
474     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
475     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
476     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
477     // FIXME: Code duplication: FDIV and FREM are expanded always, see
478     // ARMTargetLowering::addTypeForNEON method for details.
479     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
480     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
481     // FIXME: Create unittest.
482     // In another words, find a way when "copysign" appears in DAG with vector
483     // operands.
484     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
485     // FIXME: Code duplication: SETCC has custom operation action, see
486     // ARMTargetLowering::addTypeForNEON method for details.
487     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
488     // FIXME: Create unittest for FNEG and for FABS.
489     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
490     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
491     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
492     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
493     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
495     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
496     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
497     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
498     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
499     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
500     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
501     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
502     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
503     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
504     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
505     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
506     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
507     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
508
509     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
510     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
511     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
512     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
513     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
514     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
515     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
517     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
518     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
520     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
521     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
522     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
523     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
524
525     // Mark v2f32 intrinsics.
526     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
527     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
528     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
529     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
530     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
531     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
532     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
533     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
534     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
535     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
537     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
538     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
539     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
540     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
541
542     // Neon does not support some operations on v1i64 and v2i64 types.
543     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
544     // Custom handling for some quad-vector types to detect VMULL.
545     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
546     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
547     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
548     // Custom handling for some vector types to avoid expensive expansions
549     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
550     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
551     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
552     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
553     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
554     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
555     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
556     // a destination type that is wider than the source, and nor does
557     // it have a FP_TO_[SU]INT instruction with a narrower destination than
558     // source.
559     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
560     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
561     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
562     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
563
564     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
565     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
566
567     // Custom expand long extensions to vectors.
568     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32,  Custom);
569     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32,  Custom);
570     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64,  Custom);
571     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64,  Custom);
572     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
573     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
574     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
575     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
576
577     // NEON does not have single instruction CTPOP for vectors with element
578     // types wider than 8-bits.  However, custom lowering can leverage the
579     // v8i8/v16i8 vcnt instruction.
580     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
581     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
582     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
583     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
584
585     // NEON only has FMA instructions as of VFP4.
586     if (!Subtarget->hasVFP4()) {
587       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
588       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
589     }
590
591     setTargetDAGCombine(ISD::INTRINSIC_VOID);
592     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
593     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
594     setTargetDAGCombine(ISD::SHL);
595     setTargetDAGCombine(ISD::SRL);
596     setTargetDAGCombine(ISD::SRA);
597     setTargetDAGCombine(ISD::SIGN_EXTEND);
598     setTargetDAGCombine(ISD::ZERO_EXTEND);
599     setTargetDAGCombine(ISD::ANY_EXTEND);
600     setTargetDAGCombine(ISD::SELECT_CC);
601     setTargetDAGCombine(ISD::BUILD_VECTOR);
602     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
603     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
604     setTargetDAGCombine(ISD::STORE);
605     setTargetDAGCombine(ISD::FP_TO_SINT);
606     setTargetDAGCombine(ISD::FP_TO_UINT);
607     setTargetDAGCombine(ISD::FDIV);
608
609     // It is legal to extload from v4i8 to v4i16 or v4i32.
610     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
611                   MVT::v4i16, MVT::v2i16,
612                   MVT::v2i32};
613     for (unsigned i = 0; i < 6; ++i) {
614       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
615       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
616       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
617     }
618   }
619
620   // ARM and Thumb2 support UMLAL/SMLAL.
621   if (!Subtarget->isThumb1Only())
622     setTargetDAGCombine(ISD::ADDC);
623
624
625   computeRegisterProperties();
626
627   // ARM does not have f32 extending load.
628   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
629
630   // ARM does not have i1 sign extending load.
631   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
632
633   // ARM supports all 4 flavors of integer indexed load / store.
634   if (!Subtarget->isThumb1Only()) {
635     for (unsigned im = (unsigned)ISD::PRE_INC;
636          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
637       setIndexedLoadAction(im,  MVT::i1,  Legal);
638       setIndexedLoadAction(im,  MVT::i8,  Legal);
639       setIndexedLoadAction(im,  MVT::i16, Legal);
640       setIndexedLoadAction(im,  MVT::i32, Legal);
641       setIndexedStoreAction(im, MVT::i1,  Legal);
642       setIndexedStoreAction(im, MVT::i8,  Legal);
643       setIndexedStoreAction(im, MVT::i16, Legal);
644       setIndexedStoreAction(im, MVT::i32, Legal);
645     }
646   }
647
648   // i64 operation support.
649   setOperationAction(ISD::MUL,     MVT::i64, Expand);
650   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
651   if (Subtarget->isThumb1Only()) {
652     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
653     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
654   }
655   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
656       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
657     setOperationAction(ISD::MULHS, MVT::i32, Expand);
658
659   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   setOperationAction(ISD::SRL,       MVT::i64, Custom);
663   setOperationAction(ISD::SRA,       MVT::i64, Custom);
664
665   if (!Subtarget->isThumb1Only()) {
666     // FIXME: We should do this for Thumb1 as well.
667     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
668     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
669     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
670     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
671   }
672
673   // ARM does not have ROTL.
674   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
675   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
676   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
677   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
678     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
679
680   // These just redirect to CTTZ and CTLZ on ARM.
681   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
682   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
683
684   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
685
686   // Only ARMv6 has BSWAP.
687   if (!Subtarget->hasV6Ops())
688     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
689
690   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
691       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
692     // These are expanded into libcalls if the cpu doesn't have HW divider.
693     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
694     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
695   }
696   setOperationAction(ISD::SREM,  MVT::i32, Expand);
697   setOperationAction(ISD::UREM,  MVT::i32, Expand);
698   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
699   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
700
701   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
702   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
703   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
704   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
705   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
706
707   setOperationAction(ISD::TRAP, MVT::Other, Legal);
708
709   // Use the default implementation.
710   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
711   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
712   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
713   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
714   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
715   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
716
717   if (!Subtarget->isTargetDarwin()) {
718     // Non-Darwin platforms may return values in these registers via the
719     // personality function.
720     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
721     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
722     setExceptionPointerRegister(ARM::R0);
723     setExceptionSelectorRegister(ARM::R1);
724   }
725
726   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
727   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
728   // the default expansion.
729   // FIXME: This should be checking for v6k, not just v6.
730   if (Subtarget->hasDataBarrier() ||
731       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
732     // membarrier needs custom lowering; the rest are legal and handled
733     // normally.
734     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
735     // Custom lowering for 64-bit ops
736     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
737     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
738     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
739     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
740     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
741     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
742     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
743     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
744     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
745     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
746     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
747     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
748     setInsertFencesForAtomic(true);
749   } else {
750     // Set them all for expansion, which will force libcalls.
751     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
752     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
755     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
756     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
757     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
758     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
759     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
760     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
761     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
762     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
763     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
764     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
765     // Unordered/Monotonic case.
766     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
767     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
768   }
769
770   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
771
772   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
773   if (!Subtarget->hasV6Ops()) {
774     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
775     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
776   }
777   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
778
779   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
780       !Subtarget->isThumb1Only()) {
781     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
782     // iff target supports vfp2.
783     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
784     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
785   }
786
787   // We want to custom lower some of our intrinsics.
788   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
789   if (Subtarget->isTargetDarwin()) {
790     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
791     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
792     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
793   }
794
795   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
796   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
797   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
798   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
799   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
800   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
801   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
802   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
803   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
804
805   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
806   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
807   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
808   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
809   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
810
811   // We don't support sin/cos/fmod/copysign/pow
812   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
813   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
814   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
815   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
816   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
817   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
818   setOperationAction(ISD::FREM,      MVT::f64, Expand);
819   setOperationAction(ISD::FREM,      MVT::f32, Expand);
820   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821       !Subtarget->isThumb1Only()) {
822     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
823     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
824   }
825   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
826   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
827
828   if (!Subtarget->hasVFP4()) {
829     setOperationAction(ISD::FMA, MVT::f64, Expand);
830     setOperationAction(ISD::FMA, MVT::f32, Expand);
831   }
832
833   // Various VFP goodness
834   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
835     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
836     if (Subtarget->hasVFP2()) {
837       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
838       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
839       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
840       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
841     }
842     // Special handling for half-precision FP.
843     if (!Subtarget->hasFP16()) {
844       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
845       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
846     }
847   }
848
849   // We have target-specific dag combine patterns for the following nodes:
850   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
851   setTargetDAGCombine(ISD::ADD);
852   setTargetDAGCombine(ISD::SUB);
853   setTargetDAGCombine(ISD::MUL);
854   setTargetDAGCombine(ISD::AND);
855   setTargetDAGCombine(ISD::OR);
856   setTargetDAGCombine(ISD::XOR);
857
858   if (Subtarget->hasV6Ops())
859     setTargetDAGCombine(ISD::SRL);
860
861   setStackPointerRegisterToSaveRestore(ARM::SP);
862
863   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
864       !Subtarget->hasVFP2())
865     setSchedulingPreference(Sched::RegPressure);
866   else
867     setSchedulingPreference(Sched::Hybrid);
868
869   //// temporary - rewrite interface to use type
870   MaxStoresPerMemset = 8;
871   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
872   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
873   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
875   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
876
877   // On ARM arguments smaller than 4 bytes are extended, so all arguments
878   // are at least 4 bytes aligned.
879   setMinStackArgumentAlignment(4);
880
881   // Prefer likely predicted branches to selects on out-of-order cores.
882   PredictableSelectIsExpensive = Subtarget->isLikeA9();
883
884   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
885 }
886
887 // FIXME: It might make sense to define the representative register class as the
888 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
889 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
890 // SPR's representative would be DPR_VFP2. This should work well if register
891 // pressure tracking were modified such that a register use would increment the
892 // pressure of the register class's representative and all of it's super
893 // classes' representatives transitively. We have not implemented this because
894 // of the difficulty prior to coalescing of modeling operand register classes
895 // due to the common occurrence of cross class copies and subregister insertions
896 // and extractions.
897 std::pair<const TargetRegisterClass*, uint8_t>
898 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
899   const TargetRegisterClass *RRC = 0;
900   uint8_t Cost = 1;
901   switch (VT.SimpleTy) {
902   default:
903     return TargetLowering::findRepresentativeClass(VT);
904   // Use DPR as representative register class for all floating point
905   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
906   // the cost is 1 for both f32 and f64.
907   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
908   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
909     RRC = &ARM::DPRRegClass;
910     // When NEON is used for SP, only half of the register file is available
911     // because operations that define both SP and DP results will be constrained
912     // to the VFP2 class (D0-D15). We currently model this constraint prior to
913     // coalescing by double-counting the SP regs. See the FIXME above.
914     if (Subtarget->useNEONForSinglePrecisionFP())
915       Cost = 2;
916     break;
917   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
918   case MVT::v4f32: case MVT::v2f64:
919     RRC = &ARM::DPRRegClass;
920     Cost = 2;
921     break;
922   case MVT::v4i64:
923     RRC = &ARM::DPRRegClass;
924     Cost = 4;
925     break;
926   case MVT::v8i64:
927     RRC = &ARM::DPRRegClass;
928     Cost = 8;
929     break;
930   }
931   return std::make_pair(RRC, Cost);
932 }
933
934 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
935   switch (Opcode) {
936   default: return 0;
937   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
938   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
939   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
940   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
941   case ARMISD::CALL:          return "ARMISD::CALL";
942   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
943   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
944   case ARMISD::tCALL:         return "ARMISD::tCALL";
945   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
946   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
947   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
948   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
949   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
950   case ARMISD::CMP:           return "ARMISD::CMP";
951   case ARMISD::CMN:           return "ARMISD::CMN";
952   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
953   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
954   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
955   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
956   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
957
958   case ARMISD::CMOV:          return "ARMISD::CMOV";
959
960   case ARMISD::RBIT:          return "ARMISD::RBIT";
961
962   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
963   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
964   case ARMISD::SITOF:         return "ARMISD::SITOF";
965   case ARMISD::UITOF:         return "ARMISD::UITOF";
966
967   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
968   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
969   case ARMISD::RRX:           return "ARMISD::RRX";
970
971   case ARMISD::ADDC:          return "ARMISD::ADDC";
972   case ARMISD::ADDE:          return "ARMISD::ADDE";
973   case ARMISD::SUBC:          return "ARMISD::SUBC";
974   case ARMISD::SUBE:          return "ARMISD::SUBE";
975
976   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
977   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
978
979   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
980   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
981
982   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
983
984   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
985
986   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
987
988   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
989   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
990
991   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
992
993   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
994   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
995   case ARMISD::VCGE:          return "ARMISD::VCGE";
996   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
997   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
998   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
999   case ARMISD::VCGT:          return "ARMISD::VCGT";
1000   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1001   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1002   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1003   case ARMISD::VTST:          return "ARMISD::VTST";
1004
1005   case ARMISD::VSHL:          return "ARMISD::VSHL";
1006   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1007   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1008   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
1009   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
1010   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
1011   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
1012   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1013   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1014   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1015   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1016   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1017   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1018   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1019   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1020   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1021   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1022   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1023   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1024   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1025   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1026   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1027   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1028   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1029   case ARMISD::VDUP:          return "ARMISD::VDUP";
1030   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1031   case ARMISD::VEXT:          return "ARMISD::VEXT";
1032   case ARMISD::VREV64:        return "ARMISD::VREV64";
1033   case ARMISD::VREV32:        return "ARMISD::VREV32";
1034   case ARMISD::VREV16:        return "ARMISD::VREV16";
1035   case ARMISD::VZIP:          return "ARMISD::VZIP";
1036   case ARMISD::VUZP:          return "ARMISD::VUZP";
1037   case ARMISD::VTRN:          return "ARMISD::VTRN";
1038   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1039   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1040   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1041   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1042   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1043   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1044   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1045   case ARMISD::FMAX:          return "ARMISD::FMAX";
1046   case ARMISD::FMIN:          return "ARMISD::FMIN";
1047   case ARMISD::BFI:           return "ARMISD::BFI";
1048   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1049   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1050   case ARMISD::VBSL:          return "ARMISD::VBSL";
1051   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1052   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1053   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1054   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1055   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1056   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1057   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1058   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1059   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1060   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1061   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1062   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1063   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1064   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1065   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1066   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1067   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1068   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1069   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1070   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1071   }
1072 }
1073
1074 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1075   if (!VT.isVector()) return getPointerTy();
1076   return VT.changeVectorElementTypeToInteger();
1077 }
1078
1079 /// getRegClassFor - Return the register class that should be used for the
1080 /// specified value type.
1081 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1082   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1083   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1084   // load / store 4 to 8 consecutive D registers.
1085   if (Subtarget->hasNEON()) {
1086     if (VT == MVT::v4i64)
1087       return &ARM::QQPRRegClass;
1088     if (VT == MVT::v8i64)
1089       return &ARM::QQQQPRRegClass;
1090   }
1091   return TargetLowering::getRegClassFor(VT);
1092 }
1093
1094 // Create a fast isel object.
1095 FastISel *
1096 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1097                                   const TargetLibraryInfo *libInfo) const {
1098   return ARM::createFastISel(funcInfo, libInfo);
1099 }
1100
1101 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1102 /// be used for loads / stores from the global.
1103 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1104   return (Subtarget->isThumb1Only() ? 127 : 4095);
1105 }
1106
1107 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1108   unsigned NumVals = N->getNumValues();
1109   if (!NumVals)
1110     return Sched::RegPressure;
1111
1112   for (unsigned i = 0; i != NumVals; ++i) {
1113     EVT VT = N->getValueType(i);
1114     if (VT == MVT::Glue || VT == MVT::Other)
1115       continue;
1116     if (VT.isFloatingPoint() || VT.isVector())
1117       return Sched::ILP;
1118   }
1119
1120   if (!N->isMachineOpcode())
1121     return Sched::RegPressure;
1122
1123   // Load are scheduled for latency even if there instruction itinerary
1124   // is not available.
1125   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1126   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1127
1128   if (MCID.getNumDefs() == 0)
1129     return Sched::RegPressure;
1130   if (!Itins->isEmpty() &&
1131       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1132     return Sched::ILP;
1133
1134   return Sched::RegPressure;
1135 }
1136
1137 //===----------------------------------------------------------------------===//
1138 // Lowering Code
1139 //===----------------------------------------------------------------------===//
1140
1141 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1142 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1143   switch (CC) {
1144   default: llvm_unreachable("Unknown condition code!");
1145   case ISD::SETNE:  return ARMCC::NE;
1146   case ISD::SETEQ:  return ARMCC::EQ;
1147   case ISD::SETGT:  return ARMCC::GT;
1148   case ISD::SETGE:  return ARMCC::GE;
1149   case ISD::SETLT:  return ARMCC::LT;
1150   case ISD::SETLE:  return ARMCC::LE;
1151   case ISD::SETUGT: return ARMCC::HI;
1152   case ISD::SETUGE: return ARMCC::HS;
1153   case ISD::SETULT: return ARMCC::LO;
1154   case ISD::SETULE: return ARMCC::LS;
1155   }
1156 }
1157
1158 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1159 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1160                         ARMCC::CondCodes &CondCode2) {
1161   CondCode2 = ARMCC::AL;
1162   switch (CC) {
1163   default: llvm_unreachable("Unknown FP condition!");
1164   case ISD::SETEQ:
1165   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1166   case ISD::SETGT:
1167   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1168   case ISD::SETGE:
1169   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1170   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1171   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1172   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1173   case ISD::SETO:   CondCode = ARMCC::VC; break;
1174   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1175   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1176   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1177   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1178   case ISD::SETLT:
1179   case ISD::SETULT: CondCode = ARMCC::LT; break;
1180   case ISD::SETLE:
1181   case ISD::SETULE: CondCode = ARMCC::LE; break;
1182   case ISD::SETNE:
1183   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1184   }
1185 }
1186
1187 //===----------------------------------------------------------------------===//
1188 //                      Calling Convention Implementation
1189 //===----------------------------------------------------------------------===//
1190
1191 #include "ARMGenCallingConv.inc"
1192
1193 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1194 /// given CallingConvention value.
1195 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1196                                                  bool Return,
1197                                                  bool isVarArg) const {
1198   switch (CC) {
1199   default:
1200     llvm_unreachable("Unsupported calling convention");
1201   case CallingConv::Fast:
1202     if (Subtarget->hasVFP2() && !isVarArg) {
1203       if (!Subtarget->isAAPCS_ABI())
1204         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1205       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1206       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1207     }
1208     // Fallthrough
1209   case CallingConv::C: {
1210     // Use target triple & subtarget features to do actual dispatch.
1211     if (!Subtarget->isAAPCS_ABI())
1212       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1213     else if (Subtarget->hasVFP2() &&
1214              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1215              !isVarArg)
1216       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1217     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1218   }
1219   case CallingConv::ARM_AAPCS_VFP:
1220     if (!isVarArg)
1221       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1222     // Fallthrough
1223   case CallingConv::ARM_AAPCS:
1224     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1225   case CallingConv::ARM_APCS:
1226     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1227   case CallingConv::GHC:
1228     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1229   }
1230 }
1231
1232 /// LowerCallResult - Lower the result values of a call into the
1233 /// appropriate copies out of appropriate physical registers.
1234 SDValue
1235 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1236                                    CallingConv::ID CallConv, bool isVarArg,
1237                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1238                                    SDLoc dl, SelectionDAG &DAG,
1239                                    SmallVectorImpl<SDValue> &InVals,
1240                                    bool isThisReturn, SDValue ThisVal) const {
1241
1242   // Assign locations to each value returned by this call.
1243   SmallVector<CCValAssign, 16> RVLocs;
1244   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1245                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1246   CCInfo.AnalyzeCallResult(Ins,
1247                            CCAssignFnForNode(CallConv, /* Return*/ true,
1248                                              isVarArg));
1249
1250   // Copy all of the result registers out of their specified physreg.
1251   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1252     CCValAssign VA = RVLocs[i];
1253
1254     // Pass 'this' value directly from the argument to return value, to avoid
1255     // reg unit interference
1256     if (i == 0 && isThisReturn) {
1257       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1258              "unexpected return calling convention register assignment");
1259       InVals.push_back(ThisVal);
1260       continue;
1261     }
1262
1263     SDValue Val;
1264     if (VA.needsCustom()) {
1265       // Handle f64 or half of a v2f64.
1266       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1267                                       InFlag);
1268       Chain = Lo.getValue(1);
1269       InFlag = Lo.getValue(2);
1270       VA = RVLocs[++i]; // skip ahead to next loc
1271       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1272                                       InFlag);
1273       Chain = Hi.getValue(1);
1274       InFlag = Hi.getValue(2);
1275       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1276
1277       if (VA.getLocVT() == MVT::v2f64) {
1278         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1279         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1280                           DAG.getConstant(0, MVT::i32));
1281
1282         VA = RVLocs[++i]; // skip ahead to next loc
1283         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1284         Chain = Lo.getValue(1);
1285         InFlag = Lo.getValue(2);
1286         VA = RVLocs[++i]; // skip ahead to next loc
1287         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1288         Chain = Hi.getValue(1);
1289         InFlag = Hi.getValue(2);
1290         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1291         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1292                           DAG.getConstant(1, MVT::i32));
1293       }
1294     } else {
1295       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1296                                InFlag);
1297       Chain = Val.getValue(1);
1298       InFlag = Val.getValue(2);
1299     }
1300
1301     switch (VA.getLocInfo()) {
1302     default: llvm_unreachable("Unknown loc info!");
1303     case CCValAssign::Full: break;
1304     case CCValAssign::BCvt:
1305       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1306       break;
1307     }
1308
1309     InVals.push_back(Val);
1310   }
1311
1312   return Chain;
1313 }
1314
1315 /// LowerMemOpCallTo - Store the argument to the stack.
1316 SDValue
1317 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1318                                     SDValue StackPtr, SDValue Arg,
1319                                     SDLoc dl, SelectionDAG &DAG,
1320                                     const CCValAssign &VA,
1321                                     ISD::ArgFlagsTy Flags) const {
1322   unsigned LocMemOffset = VA.getLocMemOffset();
1323   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1324   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1325   return DAG.getStore(Chain, dl, Arg, PtrOff,
1326                       MachinePointerInfo::getStack(LocMemOffset),
1327                       false, false, 0);
1328 }
1329
1330 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1331                                          SDValue Chain, SDValue &Arg,
1332                                          RegsToPassVector &RegsToPass,
1333                                          CCValAssign &VA, CCValAssign &NextVA,
1334                                          SDValue &StackPtr,
1335                                          SmallVector<SDValue, 8> &MemOpChains,
1336                                          ISD::ArgFlagsTy Flags) const {
1337
1338   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1339                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1340   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1341
1342   if (NextVA.isRegLoc())
1343     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1344   else {
1345     assert(NextVA.isMemLoc());
1346     if (StackPtr.getNode() == 0)
1347       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1348
1349     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1350                                            dl, DAG, NextVA,
1351                                            Flags));
1352   }
1353 }
1354
1355 /// LowerCall - Lowering a call into a callseq_start <-
1356 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1357 /// nodes.
1358 SDValue
1359 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1360                              SmallVectorImpl<SDValue> &InVals) const {
1361   SelectionDAG &DAG                     = CLI.DAG;
1362   SDLoc &dl                          = CLI.DL;
1363   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1364   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
1365   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
1366   SDValue Chain                         = CLI.Chain;
1367   SDValue Callee                        = CLI.Callee;
1368   bool &isTailCall                      = CLI.IsTailCall;
1369   CallingConv::ID CallConv              = CLI.CallConv;
1370   bool doesNotRet                       = CLI.DoesNotReturn;
1371   bool isVarArg                         = CLI.IsVarArg;
1372
1373   MachineFunction &MF = DAG.getMachineFunction();
1374   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1375   bool isThisReturn   = false;
1376   bool isSibCall      = false;
1377   // Disable tail calls if they're not supported.
1378   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1379     isTailCall = false;
1380   if (isTailCall) {
1381     // Check if it's really possible to do a tail call.
1382     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1383                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1384                                                    Outs, OutVals, Ins, DAG);
1385     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1386     // detected sibcalls.
1387     if (isTailCall) {
1388       ++NumTailCalls;
1389       isSibCall = true;
1390     }
1391   }
1392
1393   // Analyze operands of the call, assigning locations to each operand.
1394   SmallVector<CCValAssign, 16> ArgLocs;
1395   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1396                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1397   CCInfo.AnalyzeCallOperands(Outs,
1398                              CCAssignFnForNode(CallConv, /* Return*/ false,
1399                                                isVarArg));
1400
1401   // Get a count of how many bytes are to be pushed on the stack.
1402   unsigned NumBytes = CCInfo.getNextStackOffset();
1403
1404   // For tail calls, memory operands are available in our caller's stack.
1405   if (isSibCall)
1406     NumBytes = 0;
1407
1408   // Adjust the stack pointer for the new arguments...
1409   // These operations are automatically eliminated by the prolog/epilog pass
1410   if (!isSibCall)
1411     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1412                                  dl);
1413
1414   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1415
1416   RegsToPassVector RegsToPass;
1417   SmallVector<SDValue, 8> MemOpChains;
1418
1419   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1420   // of tail call optimization, arguments are handled later.
1421   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1422        i != e;
1423        ++i, ++realArgIdx) {
1424     CCValAssign &VA = ArgLocs[i];
1425     SDValue Arg = OutVals[realArgIdx];
1426     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1427     bool isByVal = Flags.isByVal();
1428
1429     // Promote the value if needed.
1430     switch (VA.getLocInfo()) {
1431     default: llvm_unreachable("Unknown loc info!");
1432     case CCValAssign::Full: break;
1433     case CCValAssign::SExt:
1434       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1435       break;
1436     case CCValAssign::ZExt:
1437       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1438       break;
1439     case CCValAssign::AExt:
1440       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1441       break;
1442     case CCValAssign::BCvt:
1443       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1444       break;
1445     }
1446
1447     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1448     if (VA.needsCustom()) {
1449       if (VA.getLocVT() == MVT::v2f64) {
1450         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1451                                   DAG.getConstant(0, MVT::i32));
1452         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1453                                   DAG.getConstant(1, MVT::i32));
1454
1455         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1456                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1457
1458         VA = ArgLocs[++i]; // skip ahead to next loc
1459         if (VA.isRegLoc()) {
1460           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1461                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1462         } else {
1463           assert(VA.isMemLoc());
1464
1465           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1466                                                  dl, DAG, VA, Flags));
1467         }
1468       } else {
1469         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1470                          StackPtr, MemOpChains, Flags);
1471       }
1472     } else if (VA.isRegLoc()) {
1473       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1474         assert(VA.getLocVT() == MVT::i32 &&
1475                "unexpected calling convention register assignment");
1476         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1477                "unexpected use of 'returned'");
1478         isThisReturn = true;
1479       }
1480       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1481     } else if (isByVal) {
1482       assert(VA.isMemLoc());
1483       unsigned offset = 0;
1484
1485       // True if this byval aggregate will be split between registers
1486       // and memory.
1487       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1488       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1489
1490       if (CurByValIdx < ByValArgsCount) {
1491
1492         unsigned RegBegin, RegEnd;
1493         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1494
1495         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1496         unsigned int i, j;
1497         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1498           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1499           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1500           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1501                                      MachinePointerInfo(),
1502                                      false, false, false, 0);
1503           MemOpChains.push_back(Load.getValue(1));
1504           RegsToPass.push_back(std::make_pair(j, Load));
1505         }
1506
1507         // If parameter size outsides register area, "offset" value
1508         // helps us to calculate stack slot for remained part properly.
1509         offset = RegEnd - RegBegin;
1510
1511         CCInfo.nextInRegsParam();
1512       }
1513
1514       if (Flags.getByValSize() > 4*offset) {
1515         unsigned LocMemOffset = VA.getLocMemOffset();
1516         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1517         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1518                                   StkPtrOff);
1519         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1520         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1521         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1522                                            MVT::i32);
1523         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1524
1525         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1526         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1527         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1528                                           Ops, array_lengthof(Ops)));
1529       }
1530     } else if (!isSibCall) {
1531       assert(VA.isMemLoc());
1532
1533       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1534                                              dl, DAG, VA, Flags));
1535     }
1536   }
1537
1538   if (!MemOpChains.empty())
1539     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1540                         &MemOpChains[0], MemOpChains.size());
1541
1542   // Build a sequence of copy-to-reg nodes chained together with token chain
1543   // and flag operands which copy the outgoing args into the appropriate regs.
1544   SDValue InFlag;
1545   // Tail call byval lowering might overwrite argument registers so in case of
1546   // tail call optimization the copies to registers are lowered later.
1547   if (!isTailCall)
1548     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1549       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1550                                RegsToPass[i].second, InFlag);
1551       InFlag = Chain.getValue(1);
1552     }
1553
1554   // For tail calls lower the arguments to the 'real' stack slot.
1555   if (isTailCall) {
1556     // Force all the incoming stack arguments to be loaded from the stack
1557     // before any new outgoing arguments are stored to the stack, because the
1558     // outgoing stack slots may alias the incoming argument stack slots, and
1559     // the alias isn't otherwise explicit. This is slightly more conservative
1560     // than necessary, because it means that each store effectively depends
1561     // on every argument instead of just those arguments it would clobber.
1562
1563     // Do not flag preceding copytoreg stuff together with the following stuff.
1564     InFlag = SDValue();
1565     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1566       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1567                                RegsToPass[i].second, InFlag);
1568       InFlag = Chain.getValue(1);
1569     }
1570     InFlag = SDValue();
1571   }
1572
1573   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1574   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1575   // node so that legalize doesn't hack it.
1576   bool isDirect = false;
1577   bool isARMFunc = false;
1578   bool isLocalARMFunc = false;
1579   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1580
1581   if (EnableARMLongCalls) {
1582     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1583             && "long-calls with non-static relocation model!");
1584     // Handle a global address or an external symbol. If it's not one of
1585     // those, the target's already in a register, so we don't need to do
1586     // anything extra.
1587     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1588       const GlobalValue *GV = G->getGlobal();
1589       // Create a constant pool entry for the callee address
1590       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1591       ARMConstantPoolValue *CPV =
1592         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1593
1594       // Get the address of the callee into a register
1595       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1596       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1597       Callee = DAG.getLoad(getPointerTy(), dl,
1598                            DAG.getEntryNode(), CPAddr,
1599                            MachinePointerInfo::getConstantPool(),
1600                            false, false, false, 0);
1601     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1602       const char *Sym = S->getSymbol();
1603
1604       // Create a constant pool entry for the callee address
1605       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1606       ARMConstantPoolValue *CPV =
1607         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1608                                       ARMPCLabelIndex, 0);
1609       // Get the address of the callee into a register
1610       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1611       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1612       Callee = DAG.getLoad(getPointerTy(), dl,
1613                            DAG.getEntryNode(), CPAddr,
1614                            MachinePointerInfo::getConstantPool(),
1615                            false, false, false, 0);
1616     }
1617   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1618     const GlobalValue *GV = G->getGlobal();
1619     isDirect = true;
1620     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1621     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1622                    getTargetMachine().getRelocationModel() != Reloc::Static;
1623     isARMFunc = !Subtarget->isThumb() || isStub;
1624     // ARM call to a local ARM function is predicable.
1625     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1626     // tBX takes a register source operand.
1627     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1628       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1629       ARMConstantPoolValue *CPV =
1630         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1631       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1632       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1633       Callee = DAG.getLoad(getPointerTy(), dl,
1634                            DAG.getEntryNode(), CPAddr,
1635                            MachinePointerInfo::getConstantPool(),
1636                            false, false, false, 0);
1637       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1638       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1639                            getPointerTy(), Callee, PICLabel);
1640     } else {
1641       // On ELF targets for PIC code, direct calls should go through the PLT
1642       unsigned OpFlags = 0;
1643       if (Subtarget->isTargetELF() &&
1644           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1645         OpFlags = ARMII::MO_PLT;
1646       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1647     }
1648   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1649     isDirect = true;
1650     bool isStub = Subtarget->isTargetDarwin() &&
1651                   getTargetMachine().getRelocationModel() != Reloc::Static;
1652     isARMFunc = !Subtarget->isThumb() || isStub;
1653     // tBX takes a register source operand.
1654     const char *Sym = S->getSymbol();
1655     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1656       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1657       ARMConstantPoolValue *CPV =
1658         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1659                                       ARMPCLabelIndex, 4);
1660       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1661       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1662       Callee = DAG.getLoad(getPointerTy(), dl,
1663                            DAG.getEntryNode(), CPAddr,
1664                            MachinePointerInfo::getConstantPool(),
1665                            false, false, false, 0);
1666       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1667       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1668                            getPointerTy(), Callee, PICLabel);
1669     } else {
1670       unsigned OpFlags = 0;
1671       // On ELF targets for PIC code, direct calls should go through the PLT
1672       if (Subtarget->isTargetELF() &&
1673                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1674         OpFlags = ARMII::MO_PLT;
1675       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1676     }
1677   }
1678
1679   // FIXME: handle tail calls differently.
1680   unsigned CallOpc;
1681   bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1682     hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1683   if (Subtarget->isThumb()) {
1684     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1685       CallOpc = ARMISD::CALL_NOLINK;
1686     else
1687       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1688   } else {
1689     if (!isDirect && !Subtarget->hasV5TOps())
1690       CallOpc = ARMISD::CALL_NOLINK;
1691     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1692                // Emit regular call when code size is the priority
1693                !HasMinSizeAttr)
1694       // "mov lr, pc; b _foo" to avoid confusing the RSP
1695       CallOpc = ARMISD::CALL_NOLINK;
1696     else
1697       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1698   }
1699
1700   std::vector<SDValue> Ops;
1701   Ops.push_back(Chain);
1702   Ops.push_back(Callee);
1703
1704   // Add argument registers to the end of the list so that they are known live
1705   // into the call.
1706   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1707     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1708                                   RegsToPass[i].second.getValueType()));
1709
1710   // Add a register mask operand representing the call-preserved registers.
1711   const uint32_t *Mask;
1712   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1713   const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1714   if (isThisReturn)
1715     // For 'this' returns, use the R0-preserving mask
1716     Mask = ARI->getThisReturnPreservedMask(CallConv);
1717   else
1718     Mask = ARI->getCallPreservedMask(CallConv);
1719
1720   assert(Mask && "Missing call preserved mask for calling convention");
1721   Ops.push_back(DAG.getRegisterMask(Mask));
1722
1723   if (InFlag.getNode())
1724     Ops.push_back(InFlag);
1725
1726   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1727   if (isTailCall)
1728     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1729
1730   // Returns a chain and a flag for retval copy to use.
1731   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1732   InFlag = Chain.getValue(1);
1733
1734   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1735                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1736   if (!Ins.empty())
1737     InFlag = Chain.getValue(1);
1738
1739   // Handle result values, copying them out of physregs into vregs that we
1740   // return.
1741   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1742                          InVals, isThisReturn,
1743                          isThisReturn ? OutVals[0] : SDValue());
1744 }
1745
1746 /// HandleByVal - Every parameter *after* a byval parameter is passed
1747 /// on the stack.  Remember the next parameter register to allocate,
1748 /// and then confiscate the rest of the parameter registers to insure
1749 /// this.
1750 void
1751 ARMTargetLowering::HandleByVal(
1752     CCState *State, unsigned &size, unsigned Align) const {
1753   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1754   assert((State->getCallOrPrologue() == Prologue ||
1755           State->getCallOrPrologue() == Call) &&
1756          "unhandled ParmContext");
1757
1758   // For in-prologue parameters handling, we also introduce stack offset
1759   // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1760   // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1761   // NSAA should be evaluted (NSAA means "next stacked argument address").
1762   // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1763   // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1764   unsigned NSAAOffset = State->getNextStackOffset();
1765   if (State->getCallOrPrologue() != Call) {
1766     for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1767       unsigned RB, RE;
1768       State->getInRegsParamInfo(i, RB, RE);
1769       assert(NSAAOffset >= (RE-RB)*4 &&
1770              "Stack offset for byval regs doesn't introduced anymore?");
1771       NSAAOffset -= (RE-RB)*4;
1772     }
1773   }
1774   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1775     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1776       unsigned AlignInRegs = Align / 4;
1777       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1778       for (unsigned i = 0; i < Waste; ++i)
1779         reg = State->AllocateReg(GPRArgRegs, 4);
1780     }
1781     if (reg != 0) {
1782       unsigned excess = 4 * (ARM::R4 - reg);
1783
1784       // Special case when NSAA != SP and parameter size greater than size of
1785       // all remained GPR regs. In that case we can't split parameter, we must
1786       // send it to stack. We also must set NCRN to R4, so waste all
1787       // remained registers.
1788       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1789         while (State->AllocateReg(GPRArgRegs, 4))
1790           ;
1791         return;
1792       }
1793
1794       // First register for byval parameter is the first register that wasn't
1795       // allocated before this method call, so it would be "reg".
1796       // If parameter is small enough to be saved in range [reg, r4), then
1797       // the end (first after last) register would be reg + param-size-in-regs,
1798       // else parameter would be splitted between registers and stack,
1799       // end register would be r4 in this case.
1800       unsigned ByValRegBegin = reg;
1801       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1802       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1803       // Note, first register is allocated in the beginning of function already,
1804       // allocate remained amount of registers we need.
1805       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1806         State->AllocateReg(GPRArgRegs, 4);
1807       // At a call site, a byval parameter that is split between
1808       // registers and memory needs its size truncated here.  In a
1809       // function prologue, such byval parameters are reassembled in
1810       // memory, and are not truncated.
1811       if (State->getCallOrPrologue() == Call) {
1812         // Make remained size equal to 0 in case, when
1813         // the whole structure may be stored into registers.
1814         if (size < excess)
1815           size = 0;
1816         else
1817           size -= excess;
1818       }
1819     }
1820   }
1821 }
1822
1823 /// MatchingStackOffset - Return true if the given stack call argument is
1824 /// already available in the same position (relatively) of the caller's
1825 /// incoming argument stack.
1826 static
1827 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1828                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1829                          const TargetInstrInfo *TII) {
1830   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1831   int FI = INT_MAX;
1832   if (Arg.getOpcode() == ISD::CopyFromReg) {
1833     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1834     if (!TargetRegisterInfo::isVirtualRegister(VR))
1835       return false;
1836     MachineInstr *Def = MRI->getVRegDef(VR);
1837     if (!Def)
1838       return false;
1839     if (!Flags.isByVal()) {
1840       if (!TII->isLoadFromStackSlot(Def, FI))
1841         return false;
1842     } else {
1843       return false;
1844     }
1845   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1846     if (Flags.isByVal())
1847       // ByVal argument is passed in as a pointer but it's now being
1848       // dereferenced. e.g.
1849       // define @foo(%struct.X* %A) {
1850       //   tail call @bar(%struct.X* byval %A)
1851       // }
1852       return false;
1853     SDValue Ptr = Ld->getBasePtr();
1854     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1855     if (!FINode)
1856       return false;
1857     FI = FINode->getIndex();
1858   } else
1859     return false;
1860
1861   assert(FI != INT_MAX);
1862   if (!MFI->isFixedObjectIndex(FI))
1863     return false;
1864   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1865 }
1866
1867 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1868 /// for tail call optimization. Targets which want to do tail call
1869 /// optimization should implement this function.
1870 bool
1871 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1872                                                      CallingConv::ID CalleeCC,
1873                                                      bool isVarArg,
1874                                                      bool isCalleeStructRet,
1875                                                      bool isCallerStructRet,
1876                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1877                                     const SmallVectorImpl<SDValue> &OutVals,
1878                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1879                                                      SelectionDAG& DAG) const {
1880   const Function *CallerF = DAG.getMachineFunction().getFunction();
1881   CallingConv::ID CallerCC = CallerF->getCallingConv();
1882   bool CCMatch = CallerCC == CalleeCC;
1883
1884   // Look for obvious safe cases to perform tail call optimization that do not
1885   // require ABI changes. This is what gcc calls sibcall.
1886
1887   // Do not sibcall optimize vararg calls unless the call site is not passing
1888   // any arguments.
1889   if (isVarArg && !Outs.empty())
1890     return false;
1891
1892   // Also avoid sibcall optimization if either caller or callee uses struct
1893   // return semantics.
1894   if (isCalleeStructRet || isCallerStructRet)
1895     return false;
1896
1897   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1898   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1899   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1900   // support in the assembler and linker to be used. This would need to be
1901   // fixed to fully support tail calls in Thumb1.
1902   //
1903   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1904   // LR.  This means if we need to reload LR, it takes an extra instructions,
1905   // which outweighs the value of the tail call; but here we don't know yet
1906   // whether LR is going to be used.  Probably the right approach is to
1907   // generate the tail call here and turn it back into CALL/RET in
1908   // emitEpilogue if LR is used.
1909
1910   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1911   // but we need to make sure there are enough registers; the only valid
1912   // registers are the 4 used for parameters.  We don't currently do this
1913   // case.
1914   if (Subtarget->isThumb1Only())
1915     return false;
1916
1917   // If the calling conventions do not match, then we'd better make sure the
1918   // results are returned in the same way as what the caller expects.
1919   if (!CCMatch) {
1920     SmallVector<CCValAssign, 16> RVLocs1;
1921     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1922                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1923     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1924
1925     SmallVector<CCValAssign, 16> RVLocs2;
1926     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1927                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1928     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1929
1930     if (RVLocs1.size() != RVLocs2.size())
1931       return false;
1932     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1933       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1934         return false;
1935       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1936         return false;
1937       if (RVLocs1[i].isRegLoc()) {
1938         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1939           return false;
1940       } else {
1941         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1942           return false;
1943       }
1944     }
1945   }
1946
1947   // If Caller's vararg or byval argument has been split between registers and
1948   // stack, do not perform tail call, since part of the argument is in caller's
1949   // local frame.
1950   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1951                                       getInfo<ARMFunctionInfo>();
1952   if (AFI_Caller->getArgRegsSaveSize())
1953     return false;
1954
1955   // If the callee takes no arguments then go on to check the results of the
1956   // call.
1957   if (!Outs.empty()) {
1958     // Check if stack adjustment is needed. For now, do not do this if any
1959     // argument is passed on the stack.
1960     SmallVector<CCValAssign, 16> ArgLocs;
1961     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1962                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1963     CCInfo.AnalyzeCallOperands(Outs,
1964                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1965     if (CCInfo.getNextStackOffset()) {
1966       MachineFunction &MF = DAG.getMachineFunction();
1967
1968       // Check if the arguments are already laid out in the right way as
1969       // the caller's fixed stack objects.
1970       MachineFrameInfo *MFI = MF.getFrameInfo();
1971       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1972       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1973       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1974            i != e;
1975            ++i, ++realArgIdx) {
1976         CCValAssign &VA = ArgLocs[i];
1977         EVT RegVT = VA.getLocVT();
1978         SDValue Arg = OutVals[realArgIdx];
1979         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1980         if (VA.getLocInfo() == CCValAssign::Indirect)
1981           return false;
1982         if (VA.needsCustom()) {
1983           // f64 and vector types are split into multiple registers or
1984           // register/stack-slot combinations.  The types will not match
1985           // the registers; give up on memory f64 refs until we figure
1986           // out what to do about this.
1987           if (!VA.isRegLoc())
1988             return false;
1989           if (!ArgLocs[++i].isRegLoc())
1990             return false;
1991           if (RegVT == MVT::v2f64) {
1992             if (!ArgLocs[++i].isRegLoc())
1993               return false;
1994             if (!ArgLocs[++i].isRegLoc())
1995               return false;
1996           }
1997         } else if (!VA.isRegLoc()) {
1998           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1999                                    MFI, MRI, TII))
2000             return false;
2001         }
2002       }
2003     }
2004   }
2005
2006   return true;
2007 }
2008
2009 bool
2010 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2011                                   MachineFunction &MF, bool isVarArg,
2012                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2013                                   LLVMContext &Context) const {
2014   SmallVector<CCValAssign, 16> RVLocs;
2015   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2016   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2017                                                     isVarArg));
2018 }
2019
2020 SDValue
2021 ARMTargetLowering::LowerReturn(SDValue Chain,
2022                                CallingConv::ID CallConv, bool isVarArg,
2023                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2024                                const SmallVectorImpl<SDValue> &OutVals,
2025                                SDLoc dl, SelectionDAG &DAG) const {
2026
2027   // CCValAssign - represent the assignment of the return value to a location.
2028   SmallVector<CCValAssign, 16> RVLocs;
2029
2030   // CCState - Info about the registers and stack slots.
2031   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2032                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2033
2034   // Analyze outgoing return values.
2035   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2036                                                isVarArg));
2037
2038   SDValue Flag;
2039   SmallVector<SDValue, 4> RetOps;
2040   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2041
2042   // Copy the result values into the output registers.
2043   for (unsigned i = 0, realRVLocIdx = 0;
2044        i != RVLocs.size();
2045        ++i, ++realRVLocIdx) {
2046     CCValAssign &VA = RVLocs[i];
2047     assert(VA.isRegLoc() && "Can only return in registers!");
2048
2049     SDValue Arg = OutVals[realRVLocIdx];
2050
2051     switch (VA.getLocInfo()) {
2052     default: llvm_unreachable("Unknown loc info!");
2053     case CCValAssign::Full: break;
2054     case CCValAssign::BCvt:
2055       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2056       break;
2057     }
2058
2059     if (VA.needsCustom()) {
2060       if (VA.getLocVT() == MVT::v2f64) {
2061         // Extract the first half and return it in two registers.
2062         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2063                                    DAG.getConstant(0, MVT::i32));
2064         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2065                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2066
2067         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2068         Flag = Chain.getValue(1);
2069         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2070         VA = RVLocs[++i]; // skip ahead to next loc
2071         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2072                                  HalfGPRs.getValue(1), Flag);
2073         Flag = Chain.getValue(1);
2074         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2075         VA = RVLocs[++i]; // skip ahead to next loc
2076
2077         // Extract the 2nd half and fall through to handle it as an f64 value.
2078         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2079                           DAG.getConstant(1, MVT::i32));
2080       }
2081       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2082       // available.
2083       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2084                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2085       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2086       Flag = Chain.getValue(1);
2087       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2088       VA = RVLocs[++i]; // skip ahead to next loc
2089       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2090                                Flag);
2091     } else
2092       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2093
2094     // Guarantee that all emitted copies are
2095     // stuck together, avoiding something bad.
2096     Flag = Chain.getValue(1);
2097     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2098   }
2099
2100   // Update chain and glue.
2101   RetOps[0] = Chain;
2102   if (Flag.getNode())
2103     RetOps.push_back(Flag);
2104
2105   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2106                      RetOps.data(), RetOps.size());
2107 }
2108
2109 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2110   if (N->getNumValues() != 1)
2111     return false;
2112   if (!N->hasNUsesOfValue(1, 0))
2113     return false;
2114
2115   SDValue TCChain = Chain;
2116   SDNode *Copy = *N->use_begin();
2117   if (Copy->getOpcode() == ISD::CopyToReg) {
2118     // If the copy has a glue operand, we conservatively assume it isn't safe to
2119     // perform a tail call.
2120     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2121       return false;
2122     TCChain = Copy->getOperand(0);
2123   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2124     SDNode *VMov = Copy;
2125     // f64 returned in a pair of GPRs.
2126     SmallPtrSet<SDNode*, 2> Copies;
2127     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2128          UI != UE; ++UI) {
2129       if (UI->getOpcode() != ISD::CopyToReg)
2130         return false;
2131       Copies.insert(*UI);
2132     }
2133     if (Copies.size() > 2)
2134       return false;
2135
2136     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2137          UI != UE; ++UI) {
2138       SDValue UseChain = UI->getOperand(0);
2139       if (Copies.count(UseChain.getNode()))
2140         // Second CopyToReg
2141         Copy = *UI;
2142       else
2143         // First CopyToReg
2144         TCChain = UseChain;
2145     }
2146   } else if (Copy->getOpcode() == ISD::BITCAST) {
2147     // f32 returned in a single GPR.
2148     if (!Copy->hasOneUse())
2149       return false;
2150     Copy = *Copy->use_begin();
2151     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2152       return false;
2153     TCChain = Copy->getOperand(0);
2154   } else {
2155     return false;
2156   }
2157
2158   bool HasRet = false;
2159   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2160        UI != UE; ++UI) {
2161     if (UI->getOpcode() != ARMISD::RET_FLAG)
2162       return false;
2163     HasRet = true;
2164   }
2165
2166   if (!HasRet)
2167     return false;
2168
2169   Chain = TCChain;
2170   return true;
2171 }
2172
2173 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2174   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2175     return false;
2176
2177   if (!CI->isTailCall())
2178     return false;
2179
2180   return !Subtarget->isThumb1Only();
2181 }
2182
2183 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2184 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2185 // one of the above mentioned nodes. It has to be wrapped because otherwise
2186 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2187 // be used to form addressing mode. These wrapped nodes will be selected
2188 // into MOVi.
2189 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2190   EVT PtrVT = Op.getValueType();
2191   // FIXME there is no actual debug info here
2192   SDLoc dl(Op);
2193   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2194   SDValue Res;
2195   if (CP->isMachineConstantPoolEntry())
2196     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2197                                     CP->getAlignment());
2198   else
2199     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2200                                     CP->getAlignment());
2201   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2202 }
2203
2204 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2205   return MachineJumpTableInfo::EK_Inline;
2206 }
2207
2208 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2209                                              SelectionDAG &DAG) const {
2210   MachineFunction &MF = DAG.getMachineFunction();
2211   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2212   unsigned ARMPCLabelIndex = 0;
2213   SDLoc DL(Op);
2214   EVT PtrVT = getPointerTy();
2215   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2216   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2217   SDValue CPAddr;
2218   if (RelocM == Reloc::Static) {
2219     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2220   } else {
2221     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2222     ARMPCLabelIndex = AFI->createPICLabelUId();
2223     ARMConstantPoolValue *CPV =
2224       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2225                                       ARMCP::CPBlockAddress, PCAdj);
2226     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2227   }
2228   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2229   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2230                                MachinePointerInfo::getConstantPool(),
2231                                false, false, false, 0);
2232   if (RelocM == Reloc::Static)
2233     return Result;
2234   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2235   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2236 }
2237
2238 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2239 SDValue
2240 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2241                                                  SelectionDAG &DAG) const {
2242   SDLoc dl(GA);
2243   EVT PtrVT = getPointerTy();
2244   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2245   MachineFunction &MF = DAG.getMachineFunction();
2246   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2247   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2248   ARMConstantPoolValue *CPV =
2249     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2250                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2251   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2252   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2253   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2254                          MachinePointerInfo::getConstantPool(),
2255                          false, false, false, 0);
2256   SDValue Chain = Argument.getValue(1);
2257
2258   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2259   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2260
2261   // call __tls_get_addr.
2262   ArgListTy Args;
2263   ArgListEntry Entry;
2264   Entry.Node = Argument;
2265   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2266   Args.push_back(Entry);
2267   // FIXME: is there useful debug info available here?
2268   TargetLowering::CallLoweringInfo CLI(Chain,
2269                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2270                 false, false, false, false,
2271                 0, CallingConv::C, /*isTailCall=*/false,
2272                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2273                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2274   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2275   return CallResult.first;
2276 }
2277
2278 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2279 // "local exec" model.
2280 SDValue
2281 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2282                                         SelectionDAG &DAG,
2283                                         TLSModel::Model model) const {
2284   const GlobalValue *GV = GA->getGlobal();
2285   SDLoc dl(GA);
2286   SDValue Offset;
2287   SDValue Chain = DAG.getEntryNode();
2288   EVT PtrVT = getPointerTy();
2289   // Get the Thread Pointer
2290   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2291
2292   if (model == TLSModel::InitialExec) {
2293     MachineFunction &MF = DAG.getMachineFunction();
2294     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2295     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2296     // Initial exec model.
2297     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2298     ARMConstantPoolValue *CPV =
2299       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2300                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2301                                       true);
2302     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2303     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2304     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2305                          MachinePointerInfo::getConstantPool(),
2306                          false, false, false, 0);
2307     Chain = Offset.getValue(1);
2308
2309     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2310     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2311
2312     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2313                          MachinePointerInfo::getConstantPool(),
2314                          false, false, false, 0);
2315   } else {
2316     // local exec model
2317     assert(model == TLSModel::LocalExec);
2318     ARMConstantPoolValue *CPV =
2319       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2320     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2321     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2322     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2323                          MachinePointerInfo::getConstantPool(),
2324                          false, false, false, 0);
2325   }
2326
2327   // The address of the thread local variable is the add of the thread
2328   // pointer with the offset of the variable.
2329   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2330 }
2331
2332 SDValue
2333 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2334   // TODO: implement the "local dynamic" model
2335   assert(Subtarget->isTargetELF() &&
2336          "TLS not implemented for non-ELF targets");
2337   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2338
2339   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2340
2341   switch (model) {
2342     case TLSModel::GeneralDynamic:
2343     case TLSModel::LocalDynamic:
2344       return LowerToTLSGeneralDynamicModel(GA, DAG);
2345     case TLSModel::InitialExec:
2346     case TLSModel::LocalExec:
2347       return LowerToTLSExecModels(GA, DAG, model);
2348   }
2349   llvm_unreachable("bogus TLS model");
2350 }
2351
2352 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2353                                                  SelectionDAG &DAG) const {
2354   EVT PtrVT = getPointerTy();
2355   SDLoc dl(Op);
2356   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2357   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2358     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2359     ARMConstantPoolValue *CPV =
2360       ARMConstantPoolConstant::Create(GV,
2361                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2362     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2363     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2364     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2365                                  CPAddr,
2366                                  MachinePointerInfo::getConstantPool(),
2367                                  false, false, false, 0);
2368     SDValue Chain = Result.getValue(1);
2369     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2370     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2371     if (!UseGOTOFF)
2372       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2373                            MachinePointerInfo::getGOT(),
2374                            false, false, false, 0);
2375     return Result;
2376   }
2377
2378   // If we have T2 ops, we can materialize the address directly via movt/movw
2379   // pair. This is always cheaper.
2380   if (Subtarget->useMovt()) {
2381     ++NumMovwMovt;
2382     // FIXME: Once remat is capable of dealing with instructions with register
2383     // operands, expand this into two nodes.
2384     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2385                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2386   } else {
2387     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2388     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2389     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2390                        MachinePointerInfo::getConstantPool(),
2391                        false, false, false, 0);
2392   }
2393 }
2394
2395 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2396                                                     SelectionDAG &DAG) const {
2397   EVT PtrVT = getPointerTy();
2398   SDLoc dl(Op);
2399   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2400   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2401
2402   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2403   // update ARMFastISel::ARMMaterializeGV.
2404   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2405     ++NumMovwMovt;
2406     // FIXME: Once remat is capable of dealing with instructions with register
2407     // operands, expand this into two nodes.
2408     if (RelocM == Reloc::Static)
2409       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2410                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2411
2412     unsigned Wrapper = (RelocM == Reloc::PIC_)
2413       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2414     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2415                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2416     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2417       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2418                            MachinePointerInfo::getGOT(),
2419                            false, false, false, 0);
2420     return Result;
2421   }
2422
2423   unsigned ARMPCLabelIndex = 0;
2424   SDValue CPAddr;
2425   if (RelocM == Reloc::Static) {
2426     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2427   } else {
2428     ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2429     ARMPCLabelIndex = AFI->createPICLabelUId();
2430     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2431     ARMConstantPoolValue *CPV =
2432       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2433                                       PCAdj);
2434     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2435   }
2436   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2437
2438   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2439                                MachinePointerInfo::getConstantPool(),
2440                                false, false, false, 0);
2441   SDValue Chain = Result.getValue(1);
2442
2443   if (RelocM == Reloc::PIC_) {
2444     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2445     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2446   }
2447
2448   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2449     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2450                          false, false, false, 0);
2451
2452   return Result;
2453 }
2454
2455 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2456                                                     SelectionDAG &DAG) const {
2457   assert(Subtarget->isTargetELF() &&
2458          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2459   MachineFunction &MF = DAG.getMachineFunction();
2460   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2461   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2462   EVT PtrVT = getPointerTy();
2463   SDLoc dl(Op);
2464   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2465   ARMConstantPoolValue *CPV =
2466     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2467                                   ARMPCLabelIndex, PCAdj);
2468   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2469   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2470   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2471                                MachinePointerInfo::getConstantPool(),
2472                                false, false, false, 0);
2473   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2474   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2475 }
2476
2477 SDValue
2478 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2479   SDLoc dl(Op);
2480   SDValue Val = DAG.getConstant(0, MVT::i32);
2481   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2482                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2483                      Op.getOperand(1), Val);
2484 }
2485
2486 SDValue
2487 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2488   SDLoc dl(Op);
2489   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2490                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2491 }
2492
2493 SDValue
2494 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2495                                           const ARMSubtarget *Subtarget) const {
2496   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2497   SDLoc dl(Op);
2498   switch (IntNo) {
2499   default: return SDValue();    // Don't custom lower most intrinsics.
2500   case Intrinsic::arm_thread_pointer: {
2501     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2502     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2503   }
2504   case Intrinsic::eh_sjlj_lsda: {
2505     MachineFunction &MF = DAG.getMachineFunction();
2506     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2507     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2508     EVT PtrVT = getPointerTy();
2509     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2510     SDValue CPAddr;
2511     unsigned PCAdj = (RelocM != Reloc::PIC_)
2512       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2513     ARMConstantPoolValue *CPV =
2514       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2515                                       ARMCP::CPLSDA, PCAdj);
2516     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2517     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2518     SDValue Result =
2519       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2520                   MachinePointerInfo::getConstantPool(),
2521                   false, false, false, 0);
2522
2523     if (RelocM == Reloc::PIC_) {
2524       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2525       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2526     }
2527     return Result;
2528   }
2529   case Intrinsic::arm_neon_vmulls:
2530   case Intrinsic::arm_neon_vmullu: {
2531     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2532       ? ARMISD::VMULLs : ARMISD::VMULLu;
2533     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2534                        Op.getOperand(1), Op.getOperand(2));
2535   }
2536   }
2537 }
2538
2539 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2540                                  const ARMSubtarget *Subtarget) {
2541   // FIXME: handle "fence singlethread" more efficiently.
2542   SDLoc dl(Op);
2543   if (!Subtarget->hasDataBarrier()) {
2544     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2545     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2546     // here.
2547     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2548            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2549     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2550                        DAG.getConstant(0, MVT::i32));
2551   }
2552
2553   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2554                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2555 }
2556
2557 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2558                              const ARMSubtarget *Subtarget) {
2559   // ARM pre v5TE and Thumb1 does not have preload instructions.
2560   if (!(Subtarget->isThumb2() ||
2561         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2562     // Just preserve the chain.
2563     return Op.getOperand(0);
2564
2565   SDLoc dl(Op);
2566   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2567   if (!isRead &&
2568       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2569     // ARMv7 with MP extension has PLDW.
2570     return Op.getOperand(0);
2571
2572   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2573   if (Subtarget->isThumb()) {
2574     // Invert the bits.
2575     isRead = ~isRead & 1;
2576     isData = ~isData & 1;
2577   }
2578
2579   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2580                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2581                      DAG.getConstant(isData, MVT::i32));
2582 }
2583
2584 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2585   MachineFunction &MF = DAG.getMachineFunction();
2586   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2587
2588   // vastart just stores the address of the VarArgsFrameIndex slot into the
2589   // memory location argument.
2590   SDLoc dl(Op);
2591   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2592   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2593   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2594   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2595                       MachinePointerInfo(SV), false, false, 0);
2596 }
2597
2598 SDValue
2599 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2600                                         SDValue &Root, SelectionDAG &DAG,
2601                                         SDLoc dl) const {
2602   MachineFunction &MF = DAG.getMachineFunction();
2603   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2604
2605   const TargetRegisterClass *RC;
2606   if (AFI->isThumb1OnlyFunction())
2607     RC = &ARM::tGPRRegClass;
2608   else
2609     RC = &ARM::GPRRegClass;
2610
2611   // Transform the arguments stored in physical registers into virtual ones.
2612   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2613   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2614
2615   SDValue ArgValue2;
2616   if (NextVA.isMemLoc()) {
2617     MachineFrameInfo *MFI = MF.getFrameInfo();
2618     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2619
2620     // Create load node to retrieve arguments from the stack.
2621     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2622     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2623                             MachinePointerInfo::getFixedStack(FI),
2624                             false, false, false, 0);
2625   } else {
2626     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2627     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2628   }
2629
2630   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2631 }
2632
2633 void
2634 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2635                                   unsigned InRegsParamRecordIdx,
2636                                   unsigned ArgSize,
2637                                   unsigned &ArgRegsSize,
2638                                   unsigned &ArgRegsSaveSize)
2639   const {
2640   unsigned NumGPRs;
2641   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2642     unsigned RBegin, REnd;
2643     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2644     NumGPRs = REnd - RBegin;
2645   } else {
2646     unsigned int firstUnalloced;
2647     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2648                                                 sizeof(GPRArgRegs) /
2649                                                 sizeof(GPRArgRegs[0]));
2650     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2651   }
2652
2653   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2654   ArgRegsSize = NumGPRs * 4;
2655
2656   // If parameter is split between stack and GPRs...
2657   if (NumGPRs && Align == 8 &&
2658       (ArgRegsSize < ArgSize ||
2659         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2660     // Add padding for part of param recovered from GPRs, so
2661     // its last byte must be at address K*8 - 1.
2662     // We need to do it, since remained (stack) part of parameter has
2663     // stack alignment, and we need to "attach" "GPRs head" without gaps
2664     // to it:
2665     // Stack:
2666     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2667     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2668     //
2669     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2670     unsigned Padding =
2671         ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2672         (ArgRegsSize + AFI->getArgRegsSaveSize());
2673     ArgRegsSaveSize = ArgRegsSize + Padding;
2674   } else
2675     // We don't need to extend regs save size for byval parameters if they
2676     // are passed via GPRs only.
2677     ArgRegsSaveSize = ArgRegsSize;
2678 }
2679
2680 // The remaining GPRs hold either the beginning of variable-argument
2681 // data, or the beginning of an aggregate passed by value (usually
2682 // byval).  Either way, we allocate stack slots adjacent to the data
2683 // provided by our caller, and store the unallocated registers there.
2684 // If this is a variadic function, the va_list pointer will begin with
2685 // these values; otherwise, this reassembles a (byval) structure that
2686 // was split between registers and memory.
2687 // Return: The frame index registers were stored into.
2688 int
2689 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2690                                   SDLoc dl, SDValue &Chain,
2691                                   const Value *OrigArg,
2692                                   unsigned InRegsParamRecordIdx,
2693                                   unsigned OffsetFromOrigArg,
2694                                   unsigned ArgOffset,
2695                                   unsigned ArgSize,
2696                                   bool ForceMutable) const {
2697
2698   // Currently, two use-cases possible:
2699   // Case #1. Non var-args function, and we meet first byval parameter.
2700   //          Setup first unallocated register as first byval register;
2701   //          eat all remained registers
2702   //          (these two actions are performed by HandleByVal method).
2703   //          Then, here, we initialize stack frame with
2704   //          "store-reg" instructions.
2705   // Case #2. Var-args function, that doesn't contain byval parameters.
2706   //          The same: eat all remained unallocated registers,
2707   //          initialize stack frame.
2708
2709   MachineFunction &MF = DAG.getMachineFunction();
2710   MachineFrameInfo *MFI = MF.getFrameInfo();
2711   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2712   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2713   unsigned RBegin, REnd;
2714   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2715     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2716     firstRegToSaveIndex = RBegin - ARM::R0;
2717     lastRegToSaveIndex = REnd - ARM::R0;
2718   } else {
2719     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2720       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2721     lastRegToSaveIndex = 4;
2722   }
2723
2724   unsigned ArgRegsSize, ArgRegsSaveSize;
2725   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2726                  ArgRegsSize, ArgRegsSaveSize);
2727
2728   // Store any by-val regs to their spots on the stack so that they may be
2729   // loaded by deferencing the result of formal parameter pointer or va_next.
2730   // Note: once stack area for byval/varargs registers
2731   // was initialized, it can't be initialized again.
2732   if (ArgRegsSaveSize) {
2733
2734     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2735
2736     if (Padding) {
2737       assert(AFI->getStoredByValParamsPadding() == 0 &&
2738              "The only parameter may be padded.");
2739       AFI->setStoredByValParamsPadding(Padding);
2740     }
2741
2742     int FrameIndex = MFI->CreateFixedObject(
2743                       ArgRegsSaveSize,
2744                       Padding + ArgOffset,
2745                       false);
2746     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2747
2748     SmallVector<SDValue, 4> MemOps;
2749     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2750          ++firstRegToSaveIndex, ++i) {
2751       const TargetRegisterClass *RC;
2752       if (AFI->isThumb1OnlyFunction())
2753         RC = &ARM::tGPRRegClass;
2754       else
2755         RC = &ARM::GPRRegClass;
2756
2757       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2758       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2759       SDValue Store =
2760         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2761                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2762                      false, false, 0);
2763       MemOps.push_back(Store);
2764       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2765                         DAG.getConstant(4, getPointerTy()));
2766     }
2767
2768     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2769
2770     if (!MemOps.empty())
2771       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2772                           &MemOps[0], MemOps.size());
2773     return FrameIndex;
2774   } else
2775     // This will point to the next argument passed via stack.
2776     return MFI->CreateFixedObject(
2777         4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2778 }
2779
2780 // Setup stack frame, the va_list pointer will start from.
2781 void
2782 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2783                                         SDLoc dl, SDValue &Chain,
2784                                         unsigned ArgOffset,
2785                                         bool ForceMutable) const {
2786   MachineFunction &MF = DAG.getMachineFunction();
2787   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2788
2789   // Try to store any remaining integer argument regs
2790   // to their spots on the stack so that they may be loaded by deferencing
2791   // the result of va_next.
2792   // If there is no regs to be stored, just point address after last
2793   // argument passed via stack.
2794   int FrameIndex =
2795     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2796                    0, ArgOffset, 0, ForceMutable);
2797
2798   AFI->setVarArgsFrameIndex(FrameIndex);
2799 }
2800
2801 SDValue
2802 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2803                                         CallingConv::ID CallConv, bool isVarArg,
2804                                         const SmallVectorImpl<ISD::InputArg>
2805                                           &Ins,
2806                                         SDLoc dl, SelectionDAG &DAG,
2807                                         SmallVectorImpl<SDValue> &InVals)
2808                                           const {
2809   MachineFunction &MF = DAG.getMachineFunction();
2810   MachineFrameInfo *MFI = MF.getFrameInfo();
2811
2812   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2813
2814   // Assign locations to all of the incoming arguments.
2815   SmallVector<CCValAssign, 16> ArgLocs;
2816   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2817                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2818   CCInfo.AnalyzeFormalArguments(Ins,
2819                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2820                                                   isVarArg));
2821
2822   SmallVector<SDValue, 16> ArgValues;
2823   int lastInsIndex = -1;
2824   SDValue ArgValue;
2825   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2826   unsigned CurArgIdx = 0;
2827
2828   // Initially ArgRegsSaveSize is zero.
2829   // Then we increase this value each time we meet byval parameter.
2830   // We also increase this value in case of varargs function.
2831   AFI->setArgRegsSaveSize(0);
2832
2833   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2834     CCValAssign &VA = ArgLocs[i];
2835     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2836     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2837     // Arguments stored in registers.
2838     if (VA.isRegLoc()) {
2839       EVT RegVT = VA.getLocVT();
2840
2841       if (VA.needsCustom()) {
2842         // f64 and vector types are split up into multiple registers or
2843         // combinations of registers and stack slots.
2844         if (VA.getLocVT() == MVT::v2f64) {
2845           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2846                                                    Chain, DAG, dl);
2847           VA = ArgLocs[++i]; // skip ahead to next loc
2848           SDValue ArgValue2;
2849           if (VA.isMemLoc()) {
2850             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2851             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2852             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2853                                     MachinePointerInfo::getFixedStack(FI),
2854                                     false, false, false, 0);
2855           } else {
2856             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2857                                              Chain, DAG, dl);
2858           }
2859           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2860           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2861                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2862           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2863                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2864         } else
2865           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2866
2867       } else {
2868         const TargetRegisterClass *RC;
2869
2870         if (RegVT == MVT::f32)
2871           RC = &ARM::SPRRegClass;
2872         else if (RegVT == MVT::f64)
2873           RC = &ARM::DPRRegClass;
2874         else if (RegVT == MVT::v2f64)
2875           RC = &ARM::QPRRegClass;
2876         else if (RegVT == MVT::i32)
2877           RC = AFI->isThumb1OnlyFunction() ?
2878             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2879             (const TargetRegisterClass*)&ARM::GPRRegClass;
2880         else
2881           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2882
2883         // Transform the arguments in physical registers into virtual ones.
2884         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2885         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2886       }
2887
2888       // If this is an 8 or 16-bit value, it is really passed promoted
2889       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2890       // truncate to the right size.
2891       switch (VA.getLocInfo()) {
2892       default: llvm_unreachable("Unknown loc info!");
2893       case CCValAssign::Full: break;
2894       case CCValAssign::BCvt:
2895         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2896         break;
2897       case CCValAssign::SExt:
2898         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2899                                DAG.getValueType(VA.getValVT()));
2900         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2901         break;
2902       case CCValAssign::ZExt:
2903         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2904                                DAG.getValueType(VA.getValVT()));
2905         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2906         break;
2907       }
2908
2909       InVals.push_back(ArgValue);
2910
2911     } else { // VA.isRegLoc()
2912
2913       // sanity check
2914       assert(VA.isMemLoc());
2915       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2916
2917       int index = ArgLocs[i].getValNo();
2918
2919       // Some Ins[] entries become multiple ArgLoc[] entries.
2920       // Process them only once.
2921       if (index != lastInsIndex)
2922         {
2923           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2924           // FIXME: For now, all byval parameter objects are marked mutable.
2925           // This can be changed with more analysis.
2926           // In case of tail call optimization mark all arguments mutable.
2927           // Since they could be overwritten by lowering of arguments in case of
2928           // a tail call.
2929           if (Flags.isByVal()) {
2930             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
2931             int FrameIndex = StoreByValRegs(
2932                 CCInfo, DAG, dl, Chain, CurOrigArg,
2933                 CurByValIndex,
2934                 Ins[VA.getValNo()].PartOffset,
2935                 VA.getLocMemOffset(),
2936                 Flags.getByValSize(),
2937                 true /*force mutable frames*/);
2938             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
2939             CCInfo.nextInRegsParam();
2940           } else {
2941             unsigned FIOffset = VA.getLocMemOffset() +
2942                                 AFI->getStoredByValParamsPadding();
2943             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2944                                             FIOffset, true);
2945
2946             // Create load nodes to retrieve arguments from the stack.
2947             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2948             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2949                                          MachinePointerInfo::getFixedStack(FI),
2950                                          false, false, false, 0));
2951           }
2952           lastInsIndex = index;
2953         }
2954     }
2955   }
2956
2957   // varargs
2958   if (isVarArg)
2959     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
2960                          CCInfo.getNextStackOffset());
2961
2962   return Chain;
2963 }
2964
2965 /// isFloatingPointZero - Return true if this is +0.0.
2966 static bool isFloatingPointZero(SDValue Op) {
2967   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2968     return CFP->getValueAPF().isPosZero();
2969   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2970     // Maybe this has already been legalized into the constant pool?
2971     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2972       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2973       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2974         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2975           return CFP->getValueAPF().isPosZero();
2976     }
2977   }
2978   return false;
2979 }
2980
2981 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2982 /// the given operands.
2983 SDValue
2984 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2985                              SDValue &ARMcc, SelectionDAG &DAG,
2986                              SDLoc dl) const {
2987   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2988     unsigned C = RHSC->getZExtValue();
2989     if (!isLegalICmpImmediate(C)) {
2990       // Constant does not fit, try adjusting it by one?
2991       switch (CC) {
2992       default: break;
2993       case ISD::SETLT:
2994       case ISD::SETGE:
2995         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2996           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2997           RHS = DAG.getConstant(C-1, MVT::i32);
2998         }
2999         break;
3000       case ISD::SETULT:
3001       case ISD::SETUGE:
3002         if (C != 0 && isLegalICmpImmediate(C-1)) {
3003           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3004           RHS = DAG.getConstant(C-1, MVT::i32);
3005         }
3006         break;
3007       case ISD::SETLE:
3008       case ISD::SETGT:
3009         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3010           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3011           RHS = DAG.getConstant(C+1, MVT::i32);
3012         }
3013         break;
3014       case ISD::SETULE:
3015       case ISD::SETUGT:
3016         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3017           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3018           RHS = DAG.getConstant(C+1, MVT::i32);
3019         }
3020         break;
3021       }
3022     }
3023   }
3024
3025   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3026   ARMISD::NodeType CompareType;
3027   switch (CondCode) {
3028   default:
3029     CompareType = ARMISD::CMP;
3030     break;
3031   case ARMCC::EQ:
3032   case ARMCC::NE:
3033     // Uses only Z Flag
3034     CompareType = ARMISD::CMPZ;
3035     break;
3036   }
3037   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3038   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3039 }
3040
3041 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3042 SDValue
3043 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3044                              SDLoc dl) const {
3045   SDValue Cmp;
3046   if (!isFloatingPointZero(RHS))
3047     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3048   else
3049     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3050   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3051 }
3052
3053 /// duplicateCmp - Glue values can have only one use, so this function
3054 /// duplicates a comparison node.
3055 SDValue
3056 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3057   unsigned Opc = Cmp.getOpcode();
3058   SDLoc DL(Cmp);
3059   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3060     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3061
3062   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3063   Cmp = Cmp.getOperand(0);
3064   Opc = Cmp.getOpcode();
3065   if (Opc == ARMISD::CMPFP)
3066     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3067   else {
3068     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3069     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3070   }
3071   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3072 }
3073
3074 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3075   SDValue Cond = Op.getOperand(0);
3076   SDValue SelectTrue = Op.getOperand(1);
3077   SDValue SelectFalse = Op.getOperand(2);
3078   SDLoc dl(Op);
3079
3080   // Convert:
3081   //
3082   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3083   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3084   //
3085   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3086     const ConstantSDNode *CMOVTrue =
3087       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3088     const ConstantSDNode *CMOVFalse =
3089       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3090
3091     if (CMOVTrue && CMOVFalse) {
3092       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3093       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3094
3095       SDValue True;
3096       SDValue False;
3097       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3098         True = SelectTrue;
3099         False = SelectFalse;
3100       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3101         True = SelectFalse;
3102         False = SelectTrue;
3103       }
3104
3105       if (True.getNode() && False.getNode()) {
3106         EVT VT = Op.getValueType();
3107         SDValue ARMcc = Cond.getOperand(2);
3108         SDValue CCR = Cond.getOperand(3);
3109         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3110         assert(True.getValueType() == VT);
3111         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3112       }
3113     }
3114   }
3115
3116   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3117   // undefined bits before doing a full-word comparison with zero.
3118   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3119                      DAG.getConstant(1, Cond.getValueType()));
3120
3121   return DAG.getSelectCC(dl, Cond,
3122                          DAG.getConstant(0, Cond.getValueType()),
3123                          SelectTrue, SelectFalse, ISD::SETNE);
3124 }
3125
3126 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3127   EVT VT = Op.getValueType();
3128   SDValue LHS = Op.getOperand(0);
3129   SDValue RHS = Op.getOperand(1);
3130   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3131   SDValue TrueVal = Op.getOperand(2);
3132   SDValue FalseVal = Op.getOperand(3);
3133   SDLoc dl(Op);
3134
3135   if (LHS.getValueType() == MVT::i32) {
3136     SDValue ARMcc;
3137     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3138     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3139     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
3140   }
3141
3142   ARMCC::CondCodes CondCode, CondCode2;
3143   FPCCToARMCC(CC, CondCode, CondCode2);
3144
3145   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3146   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3147   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3148   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3149                                ARMcc, CCR, Cmp);
3150   if (CondCode2 != ARMCC::AL) {
3151     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3152     // FIXME: Needs another CMP because flag can have but one use.
3153     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3154     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3155                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3156   }
3157   return Result;
3158 }
3159
3160 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3161 /// to morph to an integer compare sequence.
3162 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3163                            const ARMSubtarget *Subtarget) {
3164   SDNode *N = Op.getNode();
3165   if (!N->hasOneUse())
3166     // Otherwise it requires moving the value from fp to integer registers.
3167     return false;
3168   if (!N->getNumValues())
3169     return false;
3170   EVT VT = Op.getValueType();
3171   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3172     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3173     // vmrs are very slow, e.g. cortex-a8.
3174     return false;
3175
3176   if (isFloatingPointZero(Op)) {
3177     SeenZero = true;
3178     return true;
3179   }
3180   return ISD::isNormalLoad(N);
3181 }
3182
3183 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3184   if (isFloatingPointZero(Op))
3185     return DAG.getConstant(0, MVT::i32);
3186
3187   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3188     return DAG.getLoad(MVT::i32, SDLoc(Op),
3189                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3190                        Ld->isVolatile(), Ld->isNonTemporal(),
3191                        Ld->isInvariant(), Ld->getAlignment());
3192
3193   llvm_unreachable("Unknown VFP cmp argument!");
3194 }
3195
3196 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3197                            SDValue &RetVal1, SDValue &RetVal2) {
3198   if (isFloatingPointZero(Op)) {
3199     RetVal1 = DAG.getConstant(0, MVT::i32);
3200     RetVal2 = DAG.getConstant(0, MVT::i32);
3201     return;
3202   }
3203
3204   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3205     SDValue Ptr = Ld->getBasePtr();
3206     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3207                           Ld->getChain(), Ptr,
3208                           Ld->getPointerInfo(),
3209                           Ld->isVolatile(), Ld->isNonTemporal(),
3210                           Ld->isInvariant(), Ld->getAlignment());
3211
3212     EVT PtrType = Ptr.getValueType();
3213     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3214     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3215                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3216     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3217                           Ld->getChain(), NewPtr,
3218                           Ld->getPointerInfo().getWithOffset(4),
3219                           Ld->isVolatile(), Ld->isNonTemporal(),
3220                           Ld->isInvariant(), NewAlign);
3221     return;
3222   }
3223
3224   llvm_unreachable("Unknown VFP cmp argument!");
3225 }
3226
3227 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3228 /// f32 and even f64 comparisons to integer ones.
3229 SDValue
3230 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3231   SDValue Chain = Op.getOperand(0);
3232   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3233   SDValue LHS = Op.getOperand(2);
3234   SDValue RHS = Op.getOperand(3);
3235   SDValue Dest = Op.getOperand(4);
3236   SDLoc dl(Op);
3237
3238   bool LHSSeenZero = false;
3239   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3240   bool RHSSeenZero = false;
3241   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3242   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3243     // If unsafe fp math optimization is enabled and there are no other uses of
3244     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3245     // to an integer comparison.
3246     if (CC == ISD::SETOEQ)
3247       CC = ISD::SETEQ;
3248     else if (CC == ISD::SETUNE)
3249       CC = ISD::SETNE;
3250
3251     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3252     SDValue ARMcc;
3253     if (LHS.getValueType() == MVT::f32) {
3254       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3255                         bitcastf32Toi32(LHS, DAG), Mask);
3256       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3257                         bitcastf32Toi32(RHS, DAG), Mask);
3258       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3259       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3260       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3261                          Chain, Dest, ARMcc, CCR, Cmp);
3262     }
3263
3264     SDValue LHS1, LHS2;
3265     SDValue RHS1, RHS2;
3266     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3267     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3268     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3269     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3270     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3271     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3272     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3273     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3274     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3275   }
3276
3277   return SDValue();
3278 }
3279
3280 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3281   SDValue Chain = Op.getOperand(0);
3282   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3283   SDValue LHS = Op.getOperand(2);
3284   SDValue RHS = Op.getOperand(3);
3285   SDValue Dest = Op.getOperand(4);
3286   SDLoc dl(Op);
3287
3288   if (LHS.getValueType() == MVT::i32) {
3289     SDValue ARMcc;
3290     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3291     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3292     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3293                        Chain, Dest, ARMcc, CCR, Cmp);
3294   }
3295
3296   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3297
3298   if (getTargetMachine().Options.UnsafeFPMath &&
3299       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3300        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3301     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3302     if (Result.getNode())
3303       return Result;
3304   }
3305
3306   ARMCC::CondCodes CondCode, CondCode2;
3307   FPCCToARMCC(CC, CondCode, CondCode2);
3308
3309   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3310   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3311   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3312   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3313   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3314   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3315   if (CondCode2 != ARMCC::AL) {
3316     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3317     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3318     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3319   }
3320   return Res;
3321 }
3322
3323 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3324   SDValue Chain = Op.getOperand(0);
3325   SDValue Table = Op.getOperand(1);
3326   SDValue Index = Op.getOperand(2);
3327   SDLoc dl(Op);
3328
3329   EVT PTy = getPointerTy();
3330   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3331   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3332   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3333   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3334   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3335   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3336   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3337   if (Subtarget->isThumb2()) {
3338     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3339     // which does another jump to the destination. This also makes it easier
3340     // to translate it to TBB / TBH later.
3341     // FIXME: This might not work if the function is extremely large.
3342     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3343                        Addr, Op.getOperand(2), JTI, UId);
3344   }
3345   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3346     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3347                        MachinePointerInfo::getJumpTable(),
3348                        false, false, false, 0);
3349     Chain = Addr.getValue(1);
3350     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3351     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3352   } else {
3353     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3354                        MachinePointerInfo::getJumpTable(),
3355                        false, false, false, 0);
3356     Chain = Addr.getValue(1);
3357     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3358   }
3359 }
3360
3361 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3362   EVT VT = Op.getValueType();
3363   SDLoc dl(Op);
3364
3365   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3366     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3367       return Op;
3368     return DAG.UnrollVectorOp(Op.getNode());
3369   }
3370
3371   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3372          "Invalid type for custom lowering!");
3373   if (VT != MVT::v4i16)
3374     return DAG.UnrollVectorOp(Op.getNode());
3375
3376   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3377   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3378 }
3379
3380 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3381   EVT VT = Op.getValueType();
3382   if (VT.isVector())
3383     return LowerVectorFP_TO_INT(Op, DAG);
3384
3385   SDLoc dl(Op);
3386   unsigned Opc;
3387
3388   switch (Op.getOpcode()) {
3389   default: llvm_unreachable("Invalid opcode!");
3390   case ISD::FP_TO_SINT:
3391     Opc = ARMISD::FTOSI;
3392     break;
3393   case ISD::FP_TO_UINT:
3394     Opc = ARMISD::FTOUI;
3395     break;
3396   }
3397   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3398   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3399 }
3400
3401 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3402   EVT VT = Op.getValueType();
3403   SDLoc dl(Op);
3404
3405   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3406     if (VT.getVectorElementType() == MVT::f32)
3407       return Op;
3408     return DAG.UnrollVectorOp(Op.getNode());
3409   }
3410
3411   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3412          "Invalid type for custom lowering!");
3413   if (VT != MVT::v4f32)
3414     return DAG.UnrollVectorOp(Op.getNode());
3415
3416   unsigned CastOpc;
3417   unsigned Opc;
3418   switch (Op.getOpcode()) {
3419   default: llvm_unreachable("Invalid opcode!");
3420   case ISD::SINT_TO_FP:
3421     CastOpc = ISD::SIGN_EXTEND;
3422     Opc = ISD::SINT_TO_FP;
3423     break;
3424   case ISD::UINT_TO_FP:
3425     CastOpc = ISD::ZERO_EXTEND;
3426     Opc = ISD::UINT_TO_FP;
3427     break;
3428   }
3429
3430   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3431   return DAG.getNode(Opc, dl, VT, Op);
3432 }
3433
3434 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3435   EVT VT = Op.getValueType();
3436   if (VT.isVector())
3437     return LowerVectorINT_TO_FP(Op, DAG);
3438
3439   SDLoc dl(Op);
3440   unsigned Opc;
3441
3442   switch (Op.getOpcode()) {
3443   default: llvm_unreachable("Invalid opcode!");
3444   case ISD::SINT_TO_FP:
3445     Opc = ARMISD::SITOF;
3446     break;
3447   case ISD::UINT_TO_FP:
3448     Opc = ARMISD::UITOF;
3449     break;
3450   }
3451
3452   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3453   return DAG.getNode(Opc, dl, VT, Op);
3454 }
3455
3456 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3457   // Implement fcopysign with a fabs and a conditional fneg.
3458   SDValue Tmp0 = Op.getOperand(0);
3459   SDValue Tmp1 = Op.getOperand(1);
3460   SDLoc dl(Op);
3461   EVT VT = Op.getValueType();
3462   EVT SrcVT = Tmp1.getValueType();
3463   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3464     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3465   bool UseNEON = !InGPR && Subtarget->hasNEON();
3466
3467   if (UseNEON) {
3468     // Use VBSL to copy the sign bit.
3469     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3470     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3471                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3472     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3473     if (VT == MVT::f64)
3474       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3475                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3476                          DAG.getConstant(32, MVT::i32));
3477     else /*if (VT == MVT::f32)*/
3478       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3479     if (SrcVT == MVT::f32) {
3480       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3481       if (VT == MVT::f64)
3482         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3483                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3484                            DAG.getConstant(32, MVT::i32));
3485     } else if (VT == MVT::f32)
3486       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3487                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3488                          DAG.getConstant(32, MVT::i32));
3489     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3490     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3491
3492     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3493                                             MVT::i32);
3494     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3495     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3496                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3497
3498     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3499                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3500                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3501     if (VT == MVT::f32) {
3502       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3503       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3504                         DAG.getConstant(0, MVT::i32));
3505     } else {
3506       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3507     }
3508
3509     return Res;
3510   }
3511
3512   // Bitcast operand 1 to i32.
3513   if (SrcVT == MVT::f64)
3514     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3515                        &Tmp1, 1).getValue(1);
3516   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3517
3518   // Or in the signbit with integer operations.
3519   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3520   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3521   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3522   if (VT == MVT::f32) {
3523     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3524                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3525     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3526                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3527   }
3528
3529   // f64: Or the high part with signbit and then combine two parts.
3530   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3531                      &Tmp0, 1);
3532   SDValue Lo = Tmp0.getValue(0);
3533   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3534   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3535   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3536 }
3537
3538 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3539   MachineFunction &MF = DAG.getMachineFunction();
3540   MachineFrameInfo *MFI = MF.getFrameInfo();
3541   MFI->setReturnAddressIsTaken(true);
3542
3543   EVT VT = Op.getValueType();
3544   SDLoc dl(Op);
3545   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3546   if (Depth) {
3547     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3548     SDValue Offset = DAG.getConstant(4, MVT::i32);
3549     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3550                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3551                        MachinePointerInfo(), false, false, false, 0);
3552   }
3553
3554   // Return LR, which contains the return address. Mark it an implicit live-in.
3555   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3556   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3557 }
3558
3559 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3560   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3561   MFI->setFrameAddressIsTaken(true);
3562
3563   EVT VT = Op.getValueType();
3564   SDLoc dl(Op);  // FIXME probably not meaningful
3565   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3566   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3567     ? ARM::R7 : ARM::R11;
3568   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3569   while (Depth--)
3570     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3571                             MachinePointerInfo(),
3572                             false, false, false, 0);
3573   return FrameAddr;
3574 }
3575
3576 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3577 /// and size(DestVec) > 128-bits.
3578 /// This is achieved by doing the one extension from the SrcVec, splitting the
3579 /// result, extending these parts, and then concatenating these into the
3580 /// destination.
3581 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3582   SDValue Op = N->getOperand(0);
3583   EVT SrcVT = Op.getValueType();
3584   EVT DestVT = N->getValueType(0);
3585
3586   assert(DestVT.getSizeInBits() > 128 &&
3587          "Custom sext/zext expansion needs >128-bit vector.");
3588   // If this is a normal length extension, use the default expansion.
3589   if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3590       SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3591     return SDValue();
3592
3593   SDLoc dl(N);
3594   unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3595   unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3596   unsigned NumElts = SrcVT.getVectorNumElements();
3597   LLVMContext &Ctx = *DAG.getContext();
3598   SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3599
3600   EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3601                                NumElts);
3602   EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3603                                  NumElts/2);
3604   EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3605                                NumElts/2);
3606
3607   Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3608   SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3609                         DAG.getIntPtrConstant(0));
3610   SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3611                         DAG.getIntPtrConstant(NumElts/2));
3612   ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3613   ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3614   return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3615 }
3616
3617 /// ExpandBITCAST - If the target supports VFP, this function is called to
3618 /// expand a bit convert where either the source or destination type is i64 to
3619 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3620 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3621 /// vectors), since the legalizer won't know what to do with that.
3622 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3623   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3624   SDLoc dl(N);
3625   SDValue Op = N->getOperand(0);
3626
3627   // This function is only supposed to be called for i64 types, either as the
3628   // source or destination of the bit convert.
3629   EVT SrcVT = Op.getValueType();
3630   EVT DstVT = N->getValueType(0);
3631   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3632          "ExpandBITCAST called for non-i64 type");
3633
3634   // Turn i64->f64 into VMOVDRR.
3635   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3636     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3637                              DAG.getConstant(0, MVT::i32));
3638     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3639                              DAG.getConstant(1, MVT::i32));
3640     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3641                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3642   }
3643
3644   // Turn f64->i64 into VMOVRRD.
3645   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3646     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3647                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3648     // Merge the pieces into a single i64 value.
3649     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3650   }
3651
3652   return SDValue();
3653 }
3654
3655 /// getZeroVector - Returns a vector of specified type with all zero elements.
3656 /// Zero vectors are used to represent vector negation and in those cases
3657 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3658 /// not support i64 elements, so sometimes the zero vectors will need to be
3659 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3660 /// zero vector.
3661 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3662   assert(VT.isVector() && "Expected a vector type");
3663   // The canonical modified immediate encoding of a zero vector is....0!
3664   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3665   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3666   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3667   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3668 }
3669
3670 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3671 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3672 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3673                                                 SelectionDAG &DAG) const {
3674   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3675   EVT VT = Op.getValueType();
3676   unsigned VTBits = VT.getSizeInBits();
3677   SDLoc dl(Op);
3678   SDValue ShOpLo = Op.getOperand(0);
3679   SDValue ShOpHi = Op.getOperand(1);
3680   SDValue ShAmt  = Op.getOperand(2);
3681   SDValue ARMcc;
3682   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3683
3684   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3685
3686   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3687                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3688   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3689   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3690                                    DAG.getConstant(VTBits, MVT::i32));
3691   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3692   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3693   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3694
3695   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3696   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3697                           ARMcc, DAG, dl);
3698   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3699   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3700                            CCR, Cmp);
3701
3702   SDValue Ops[2] = { Lo, Hi };
3703   return DAG.getMergeValues(Ops, 2, dl);
3704 }
3705
3706 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3707 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3708 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3709                                                SelectionDAG &DAG) const {
3710   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3711   EVT VT = Op.getValueType();
3712   unsigned VTBits = VT.getSizeInBits();
3713   SDLoc dl(Op);
3714   SDValue ShOpLo = Op.getOperand(0);
3715   SDValue ShOpHi = Op.getOperand(1);
3716   SDValue ShAmt  = Op.getOperand(2);
3717   SDValue ARMcc;
3718
3719   assert(Op.getOpcode() == ISD::SHL_PARTS);
3720   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3721                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3722   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3723   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3724                                    DAG.getConstant(VTBits, MVT::i32));
3725   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3726   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3727
3728   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3729   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3730   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3731                           ARMcc, DAG, dl);
3732   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3733   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3734                            CCR, Cmp);
3735
3736   SDValue Ops[2] = { Lo, Hi };
3737   return DAG.getMergeValues(Ops, 2, dl);
3738 }
3739
3740 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3741                                             SelectionDAG &DAG) const {
3742   // The rounding mode is in bits 23:22 of the FPSCR.
3743   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3744   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3745   // so that the shift + and get folded into a bitfield extract.
3746   SDLoc dl(Op);
3747   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3748                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3749                                               MVT::i32));
3750   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3751                                   DAG.getConstant(1U << 22, MVT::i32));
3752   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3753                               DAG.getConstant(22, MVT::i32));
3754   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3755                      DAG.getConstant(3, MVT::i32));
3756 }
3757
3758 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3759                          const ARMSubtarget *ST) {
3760   EVT VT = N->getValueType(0);
3761   SDLoc dl(N);
3762
3763   if (!ST->hasV6T2Ops())
3764     return SDValue();
3765
3766   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3767   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3768 }
3769
3770 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3771 /// for each 16-bit element from operand, repeated.  The basic idea is to
3772 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3773 ///
3774 /// Trace for v4i16:
3775 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3776 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3777 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3778 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3779 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3780 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3781 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3782 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3783 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3784   EVT VT = N->getValueType(0);
3785   SDLoc DL(N);
3786
3787   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3788   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3789   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3790   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3791   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3792   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3793 }
3794
3795 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3796 /// bit-count for each 16-bit element from the operand.  We need slightly
3797 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3798 /// 64/128-bit registers.
3799 ///
3800 /// Trace for v4i16:
3801 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3802 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3803 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3804 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3805 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3806   EVT VT = N->getValueType(0);
3807   SDLoc DL(N);
3808
3809   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3810   if (VT.is64BitVector()) {
3811     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3812     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3813                        DAG.getIntPtrConstant(0));
3814   } else {
3815     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3816                                     BitCounts, DAG.getIntPtrConstant(0));
3817     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3818   }
3819 }
3820
3821 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3822 /// bit-count for each 32-bit element from the operand.  The idea here is
3823 /// to split the vector into 16-bit elements, leverage the 16-bit count
3824 /// routine, and then combine the results.
3825 ///
3826 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3827 /// input    = [v0    v1    ] (vi: 32-bit elements)
3828 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3829 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
3830 /// vrev: N0 = [k1 k0 k3 k2 ]
3831 ///            [k0 k1 k2 k3 ]
3832 ///       N1 =+[k1 k0 k3 k2 ]
3833 ///            [k0 k2 k1 k3 ]
3834 ///       N2 =+[k1 k3 k0 k2 ]
3835 ///            [k0    k2    k1    k3    ]
3836 /// Extended =+[k1    k3    k0    k2    ]
3837 ///            [k0    k2    ]
3838 /// Extracted=+[k1    k3    ]
3839 ///
3840 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
3841   EVT VT = N->getValueType(0);
3842   SDLoc DL(N);
3843
3844   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
3845
3846   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
3847   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
3848   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
3849   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
3850   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
3851
3852   if (VT.is64BitVector()) {
3853     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
3854     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
3855                        DAG.getIntPtrConstant(0));
3856   } else {
3857     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
3858                                     DAG.getIntPtrConstant(0));
3859     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
3860   }
3861 }
3862
3863 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
3864                           const ARMSubtarget *ST) {
3865   EVT VT = N->getValueType(0);
3866
3867   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
3868   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
3869           VT == MVT::v4i16 || VT == MVT::v8i16) &&
3870          "Unexpected type for custom ctpop lowering");
3871
3872   if (VT.getVectorElementType() == MVT::i32)
3873     return lowerCTPOP32BitElements(N, DAG);
3874   else
3875     return lowerCTPOP16BitElements(N, DAG);
3876 }
3877
3878 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3879                           const ARMSubtarget *ST) {
3880   EVT VT = N->getValueType(0);
3881   SDLoc dl(N);
3882
3883   if (!VT.isVector())
3884     return SDValue();
3885
3886   // Lower vector shifts on NEON to use VSHL.
3887   assert(ST->hasNEON() && "unexpected vector shift");
3888
3889   // Left shifts translate directly to the vshiftu intrinsic.
3890   if (N->getOpcode() == ISD::SHL)
3891     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3892                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3893                        N->getOperand(0), N->getOperand(1));
3894
3895   assert((N->getOpcode() == ISD::SRA ||
3896           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3897
3898   // NEON uses the same intrinsics for both left and right shifts.  For
3899   // right shifts, the shift amounts are negative, so negate the vector of
3900   // shift amounts.
3901   EVT ShiftVT = N->getOperand(1).getValueType();
3902   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3903                                      getZeroVector(ShiftVT, DAG, dl),
3904                                      N->getOperand(1));
3905   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3906                              Intrinsic::arm_neon_vshifts :
3907                              Intrinsic::arm_neon_vshiftu);
3908   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3909                      DAG.getConstant(vshiftInt, MVT::i32),
3910                      N->getOperand(0), NegatedCount);
3911 }
3912
3913 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3914                                 const ARMSubtarget *ST) {
3915   EVT VT = N->getValueType(0);
3916   SDLoc dl(N);
3917
3918   // We can get here for a node like i32 = ISD::SHL i32, i64
3919   if (VT != MVT::i64)
3920     return SDValue();
3921
3922   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3923          "Unknown shift to lower!");
3924
3925   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3926   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3927       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3928     return SDValue();
3929
3930   // If we are in thumb mode, we don't have RRX.
3931   if (ST->isThumb1Only()) return SDValue();
3932
3933   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3934   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3935                            DAG.getConstant(0, MVT::i32));
3936   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3937                            DAG.getConstant(1, MVT::i32));
3938
3939   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3940   // captures the result into a carry flag.
3941   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3942   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3943
3944   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3945   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3946
3947   // Merge the pieces into a single i64 value.
3948  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3949 }
3950
3951 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3952   SDValue TmpOp0, TmpOp1;
3953   bool Invert = false;
3954   bool Swap = false;
3955   unsigned Opc = 0;
3956
3957   SDValue Op0 = Op.getOperand(0);
3958   SDValue Op1 = Op.getOperand(1);
3959   SDValue CC = Op.getOperand(2);
3960   EVT VT = Op.getValueType();
3961   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3962   SDLoc dl(Op);
3963
3964   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3965     switch (SetCCOpcode) {
3966     default: llvm_unreachable("Illegal FP comparison");
3967     case ISD::SETUNE:
3968     case ISD::SETNE:  Invert = true; // Fallthrough
3969     case ISD::SETOEQ:
3970     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3971     case ISD::SETOLT:
3972     case ISD::SETLT: Swap = true; // Fallthrough
3973     case ISD::SETOGT:
3974     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3975     case ISD::SETOLE:
3976     case ISD::SETLE:  Swap = true; // Fallthrough
3977     case ISD::SETOGE:
3978     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3979     case ISD::SETUGE: Swap = true; // Fallthrough
3980     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3981     case ISD::SETUGT: Swap = true; // Fallthrough
3982     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3983     case ISD::SETUEQ: Invert = true; // Fallthrough
3984     case ISD::SETONE:
3985       // Expand this to (OLT | OGT).
3986       TmpOp0 = Op0;
3987       TmpOp1 = Op1;
3988       Opc = ISD::OR;
3989       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3990       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3991       break;
3992     case ISD::SETUO: Invert = true; // Fallthrough
3993     case ISD::SETO:
3994       // Expand this to (OLT | OGE).
3995       TmpOp0 = Op0;
3996       TmpOp1 = Op1;
3997       Opc = ISD::OR;
3998       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3999       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4000       break;
4001     }
4002   } else {
4003     // Integer comparisons.
4004     switch (SetCCOpcode) {
4005     default: llvm_unreachable("Illegal integer comparison");
4006     case ISD::SETNE:  Invert = true;
4007     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4008     case ISD::SETLT:  Swap = true;
4009     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4010     case ISD::SETLE:  Swap = true;
4011     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4012     case ISD::SETULT: Swap = true;
4013     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4014     case ISD::SETULE: Swap = true;
4015     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4016     }
4017
4018     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4019     if (Opc == ARMISD::VCEQ) {
4020
4021       SDValue AndOp;
4022       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4023         AndOp = Op0;
4024       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4025         AndOp = Op1;
4026
4027       // Ignore bitconvert.
4028       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4029         AndOp = AndOp.getOperand(0);
4030
4031       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4032         Opc = ARMISD::VTST;
4033         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4034         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4035         Invert = !Invert;
4036       }
4037     }
4038   }
4039
4040   if (Swap)
4041     std::swap(Op0, Op1);
4042
4043   // If one of the operands is a constant vector zero, attempt to fold the
4044   // comparison to a specialized compare-against-zero form.
4045   SDValue SingleOp;
4046   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4047     SingleOp = Op0;
4048   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4049     if (Opc == ARMISD::VCGE)
4050       Opc = ARMISD::VCLEZ;
4051     else if (Opc == ARMISD::VCGT)
4052       Opc = ARMISD::VCLTZ;
4053     SingleOp = Op1;
4054   }
4055
4056   SDValue Result;
4057   if (SingleOp.getNode()) {
4058     switch (Opc) {
4059     case ARMISD::VCEQ:
4060       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4061     case ARMISD::VCGE:
4062       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4063     case ARMISD::VCLEZ:
4064       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4065     case ARMISD::VCGT:
4066       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4067     case ARMISD::VCLTZ:
4068       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4069     default:
4070       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4071     }
4072   } else {
4073      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4074   }
4075
4076   if (Invert)
4077     Result = DAG.getNOT(dl, Result, VT);
4078
4079   return Result;
4080 }
4081
4082 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4083 /// valid vector constant for a NEON instruction with a "modified immediate"
4084 /// operand (e.g., VMOV).  If so, return the encoded value.
4085 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4086                                  unsigned SplatBitSize, SelectionDAG &DAG,
4087                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4088   unsigned OpCmode, Imm;
4089
4090   // SplatBitSize is set to the smallest size that splats the vector, so a
4091   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4092   // immediate instructions others than VMOV do not support the 8-bit encoding
4093   // of a zero vector, and the default encoding of zero is supposed to be the
4094   // 32-bit version.
4095   if (SplatBits == 0)
4096     SplatBitSize = 32;
4097
4098   switch (SplatBitSize) {
4099   case 8:
4100     if (type != VMOVModImm)
4101       return SDValue();
4102     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4103     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4104     OpCmode = 0xe;
4105     Imm = SplatBits;
4106     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4107     break;
4108
4109   case 16:
4110     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4111     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4112     if ((SplatBits & ~0xff) == 0) {
4113       // Value = 0x00nn: Op=x, Cmode=100x.
4114       OpCmode = 0x8;
4115       Imm = SplatBits;
4116       break;
4117     }
4118     if ((SplatBits & ~0xff00) == 0) {
4119       // Value = 0xnn00: Op=x, Cmode=101x.
4120       OpCmode = 0xa;
4121       Imm = SplatBits >> 8;
4122       break;
4123     }
4124     return SDValue();
4125
4126   case 32:
4127     // NEON's 32-bit VMOV supports splat values where:
4128     // * only one byte is nonzero, or
4129     // * the least significant byte is 0xff and the second byte is nonzero, or
4130     // * the least significant 2 bytes are 0xff and the third is nonzero.
4131     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4132     if ((SplatBits & ~0xff) == 0) {
4133       // Value = 0x000000nn: Op=x, Cmode=000x.
4134       OpCmode = 0;
4135       Imm = SplatBits;
4136       break;
4137     }
4138     if ((SplatBits & ~0xff00) == 0) {
4139       // Value = 0x0000nn00: Op=x, Cmode=001x.
4140       OpCmode = 0x2;
4141       Imm = SplatBits >> 8;
4142       break;
4143     }
4144     if ((SplatBits & ~0xff0000) == 0) {
4145       // Value = 0x00nn0000: Op=x, Cmode=010x.
4146       OpCmode = 0x4;
4147       Imm = SplatBits >> 16;
4148       break;
4149     }
4150     if ((SplatBits & ~0xff000000) == 0) {
4151       // Value = 0xnn000000: Op=x, Cmode=011x.
4152       OpCmode = 0x6;
4153       Imm = SplatBits >> 24;
4154       break;
4155     }
4156
4157     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4158     if (type == OtherModImm) return SDValue();
4159
4160     if ((SplatBits & ~0xffff) == 0 &&
4161         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4162       // Value = 0x0000nnff: Op=x, Cmode=1100.
4163       OpCmode = 0xc;
4164       Imm = SplatBits >> 8;
4165       SplatBits |= 0xff;
4166       break;
4167     }
4168
4169     if ((SplatBits & ~0xffffff) == 0 &&
4170         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4171       // Value = 0x00nnffff: Op=x, Cmode=1101.
4172       OpCmode = 0xd;
4173       Imm = SplatBits >> 16;
4174       SplatBits |= 0xffff;
4175       break;
4176     }
4177
4178     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4179     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4180     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4181     // and fall through here to test for a valid 64-bit splat.  But, then the
4182     // caller would also need to check and handle the change in size.
4183     return SDValue();
4184
4185   case 64: {
4186     if (type != VMOVModImm)
4187       return SDValue();
4188     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4189     uint64_t BitMask = 0xff;
4190     uint64_t Val = 0;
4191     unsigned ImmMask = 1;
4192     Imm = 0;
4193     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4194       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4195         Val |= BitMask;
4196         Imm |= ImmMask;
4197       } else if ((SplatBits & BitMask) != 0) {
4198         return SDValue();
4199       }
4200       BitMask <<= 8;
4201       ImmMask <<= 1;
4202     }
4203     // Op=1, Cmode=1110.
4204     OpCmode = 0x1e;
4205     SplatBits = Val;
4206     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4207     break;
4208   }
4209
4210   default:
4211     llvm_unreachable("unexpected size for isNEONModifiedImm");
4212   }
4213
4214   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4215   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4216 }
4217
4218 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4219                                            const ARMSubtarget *ST) const {
4220   if (!ST->useNEONForSinglePrecisionFP() || !ST->hasVFP3() || ST->hasD16())
4221     return SDValue();
4222
4223   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4224   assert(Op.getValueType() == MVT::f32 &&
4225          "ConstantFP custom lowering should only occur for f32.");
4226
4227   // Try splatting with a VMOV.f32...
4228   APFloat FPVal = CFP->getValueAPF();
4229   int ImmVal = ARM_AM::getFP32Imm(FPVal);
4230   if (ImmVal != -1) {
4231     SDLoc DL(Op);
4232     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4233     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4234                                       NewVal);
4235     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4236                        DAG.getConstant(0, MVT::i32));
4237   }
4238
4239   // If that fails, try a VMOV.i32
4240   EVT VMovVT;
4241   unsigned iVal = FPVal.bitcastToAPInt().getZExtValue();
4242   SDValue NewVal = isNEONModifiedImm(iVal, 0, 32, DAG, VMovVT, false,
4243                                      VMOVModImm);
4244   if (NewVal != SDValue()) {
4245     SDLoc DL(Op);
4246     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4247                                       NewVal);
4248     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4249                                        VecConstant);
4250     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4251                        DAG.getConstant(0, MVT::i32));
4252   }
4253
4254   // Finally, try a VMVN.i32
4255   NewVal = isNEONModifiedImm(~iVal & 0xffffffff, 0, 32, DAG, VMovVT, false,
4256                              VMVNModImm);
4257   if (NewVal != SDValue()) {
4258     SDLoc DL(Op);
4259     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4260     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4261                                        VecConstant);
4262     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4263                        DAG.getConstant(0, MVT::i32));
4264   }
4265
4266   return SDValue();
4267 }
4268
4269 // check if an VEXT instruction can handle the shuffle mask when the
4270 // vector sources of the shuffle are the same.
4271 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4272   unsigned NumElts = VT.getVectorNumElements();
4273
4274   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4275   if (M[0] < 0)
4276     return false;
4277
4278   Imm = M[0];
4279
4280   // If this is a VEXT shuffle, the immediate value is the index of the first
4281   // element.  The other shuffle indices must be the successive elements after
4282   // the first one.
4283   unsigned ExpectedElt = Imm;
4284   for (unsigned i = 1; i < NumElts; ++i) {
4285     // Increment the expected index.  If it wraps around, just follow it
4286     // back to index zero and keep going.
4287     ++ExpectedElt;
4288     if (ExpectedElt == NumElts)
4289       ExpectedElt = 0;
4290
4291     if (M[i] < 0) continue; // ignore UNDEF indices
4292     if (ExpectedElt != static_cast<unsigned>(M[i]))
4293       return false;
4294   }
4295
4296   return true;
4297 }
4298
4299
4300 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4301                        bool &ReverseVEXT, unsigned &Imm) {
4302   unsigned NumElts = VT.getVectorNumElements();
4303   ReverseVEXT = false;
4304
4305   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4306   if (M[0] < 0)
4307     return false;
4308
4309   Imm = M[0];
4310
4311   // If this is a VEXT shuffle, the immediate value is the index of the first
4312   // element.  The other shuffle indices must be the successive elements after
4313   // the first one.
4314   unsigned ExpectedElt = Imm;
4315   for (unsigned i = 1; i < NumElts; ++i) {
4316     // Increment the expected index.  If it wraps around, it may still be
4317     // a VEXT but the source vectors must be swapped.
4318     ExpectedElt += 1;
4319     if (ExpectedElt == NumElts * 2) {
4320       ExpectedElt = 0;
4321       ReverseVEXT = true;
4322     }
4323
4324     if (M[i] < 0) continue; // ignore UNDEF indices
4325     if (ExpectedElt != static_cast<unsigned>(M[i]))
4326       return false;
4327   }
4328
4329   // Adjust the index value if the source operands will be swapped.
4330   if (ReverseVEXT)
4331     Imm -= NumElts;
4332
4333   return true;
4334 }
4335
4336 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4337 /// instruction with the specified blocksize.  (The order of the elements
4338 /// within each block of the vector is reversed.)
4339 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4340   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4341          "Only possible block sizes for VREV are: 16, 32, 64");
4342
4343   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4344   if (EltSz == 64)
4345     return false;
4346
4347   unsigned NumElts = VT.getVectorNumElements();
4348   unsigned BlockElts = M[0] + 1;
4349   // If the first shuffle index is UNDEF, be optimistic.
4350   if (M[0] < 0)
4351     BlockElts = BlockSize / EltSz;
4352
4353   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4354     return false;
4355
4356   for (unsigned i = 0; i < NumElts; ++i) {
4357     if (M[i] < 0) continue; // ignore UNDEF indices
4358     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4359       return false;
4360   }
4361
4362   return true;
4363 }
4364
4365 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4366   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4367   // range, then 0 is placed into the resulting vector. So pretty much any mask
4368   // of 8 elements can work here.
4369   return VT == MVT::v8i8 && M.size() == 8;
4370 }
4371
4372 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4373   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4374   if (EltSz == 64)
4375     return false;
4376
4377   unsigned NumElts = VT.getVectorNumElements();
4378   WhichResult = (M[0] == 0 ? 0 : 1);
4379   for (unsigned i = 0; i < NumElts; i += 2) {
4380     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4381         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4382       return false;
4383   }
4384   return true;
4385 }
4386
4387 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4388 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4389 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4390 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4391   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4392   if (EltSz == 64)
4393     return false;
4394
4395   unsigned NumElts = VT.getVectorNumElements();
4396   WhichResult = (M[0] == 0 ? 0 : 1);
4397   for (unsigned i = 0; i < NumElts; i += 2) {
4398     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4399         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4400       return false;
4401   }
4402   return true;
4403 }
4404
4405 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4406   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4407   if (EltSz == 64)
4408     return false;
4409
4410   unsigned NumElts = VT.getVectorNumElements();
4411   WhichResult = (M[0] == 0 ? 0 : 1);
4412   for (unsigned i = 0; i != NumElts; ++i) {
4413     if (M[i] < 0) continue; // ignore UNDEF indices
4414     if ((unsigned) M[i] != 2 * i + WhichResult)
4415       return false;
4416   }
4417
4418   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4419   if (VT.is64BitVector() && EltSz == 32)
4420     return false;
4421
4422   return true;
4423 }
4424
4425 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4426 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4427 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4428 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4429   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4430   if (EltSz == 64)
4431     return false;
4432
4433   unsigned Half = VT.getVectorNumElements() / 2;
4434   WhichResult = (M[0] == 0 ? 0 : 1);
4435   for (unsigned j = 0; j != 2; ++j) {
4436     unsigned Idx = WhichResult;
4437     for (unsigned i = 0; i != Half; ++i) {
4438       int MIdx = M[i + j * Half];
4439       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4440         return false;
4441       Idx += 2;
4442     }
4443   }
4444
4445   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4446   if (VT.is64BitVector() && EltSz == 32)
4447     return false;
4448
4449   return true;
4450 }
4451
4452 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4453   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4454   if (EltSz == 64)
4455     return false;
4456
4457   unsigned NumElts = VT.getVectorNumElements();
4458   WhichResult = (M[0] == 0 ? 0 : 1);
4459   unsigned Idx = WhichResult * NumElts / 2;
4460   for (unsigned i = 0; i != NumElts; i += 2) {
4461     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4462         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4463       return false;
4464     Idx += 1;
4465   }
4466
4467   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4468   if (VT.is64BitVector() && EltSz == 32)
4469     return false;
4470
4471   return true;
4472 }
4473
4474 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4475 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4476 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4477 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4478   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4479   if (EltSz == 64)
4480     return false;
4481
4482   unsigned NumElts = VT.getVectorNumElements();
4483   WhichResult = (M[0] == 0 ? 0 : 1);
4484   unsigned Idx = WhichResult * NumElts / 2;
4485   for (unsigned i = 0; i != NumElts; i += 2) {
4486     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4487         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4488       return false;
4489     Idx += 1;
4490   }
4491
4492   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4493   if (VT.is64BitVector() && EltSz == 32)
4494     return false;
4495
4496   return true;
4497 }
4498
4499 /// \return true if this is a reverse operation on an vector.
4500 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4501   unsigned NumElts = VT.getVectorNumElements();
4502   // Make sure the mask has the right size.
4503   if (NumElts != M.size())
4504       return false;
4505
4506   // Look for <15, ..., 3, -1, 1, 0>.
4507   for (unsigned i = 0; i != NumElts; ++i)
4508     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4509       return false;
4510
4511   return true;
4512 }
4513
4514 // If N is an integer constant that can be moved into a register in one
4515 // instruction, return an SDValue of such a constant (will become a MOV
4516 // instruction).  Otherwise return null.
4517 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4518                                      const ARMSubtarget *ST, SDLoc dl) {
4519   uint64_t Val;
4520   if (!isa<ConstantSDNode>(N))
4521     return SDValue();
4522   Val = cast<ConstantSDNode>(N)->getZExtValue();
4523
4524   if (ST->isThumb1Only()) {
4525     if (Val <= 255 || ~Val <= 255)
4526       return DAG.getConstant(Val, MVT::i32);
4527   } else {
4528     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4529       return DAG.getConstant(Val, MVT::i32);
4530   }
4531   return SDValue();
4532 }
4533
4534 // If this is a case we can't handle, return null and let the default
4535 // expansion code take care of it.
4536 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4537                                              const ARMSubtarget *ST) const {
4538   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4539   SDLoc dl(Op);
4540   EVT VT = Op.getValueType();
4541
4542   APInt SplatBits, SplatUndef;
4543   unsigned SplatBitSize;
4544   bool HasAnyUndefs;
4545   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4546     if (SplatBitSize <= 64) {
4547       // Check if an immediate VMOV works.
4548       EVT VmovVT;
4549       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4550                                       SplatUndef.getZExtValue(), SplatBitSize,
4551                                       DAG, VmovVT, VT.is128BitVector(),
4552                                       VMOVModImm);
4553       if (Val.getNode()) {
4554         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4555         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4556       }
4557
4558       // Try an immediate VMVN.
4559       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4560       Val = isNEONModifiedImm(NegatedImm,
4561                                       SplatUndef.getZExtValue(), SplatBitSize,
4562                                       DAG, VmovVT, VT.is128BitVector(),
4563                                       VMVNModImm);
4564       if (Val.getNode()) {
4565         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4566         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4567       }
4568
4569       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4570       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4571         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4572         if (ImmVal != -1) {
4573           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4574           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4575         }
4576       }
4577     }
4578   }
4579
4580   // Scan through the operands to see if only one value is used.
4581   //
4582   // As an optimisation, even if more than one value is used it may be more
4583   // profitable to splat with one value then change some lanes.
4584   //
4585   // Heuristically we decide to do this if the vector has a "dominant" value,
4586   // defined as splatted to more than half of the lanes.
4587   unsigned NumElts = VT.getVectorNumElements();
4588   bool isOnlyLowElement = true;
4589   bool usesOnlyOneValue = true;
4590   bool hasDominantValue = false;
4591   bool isConstant = true;
4592
4593   // Map of the number of times a particular SDValue appears in the
4594   // element list.
4595   DenseMap<SDValue, unsigned> ValueCounts;
4596   SDValue Value;
4597   for (unsigned i = 0; i < NumElts; ++i) {
4598     SDValue V = Op.getOperand(i);
4599     if (V.getOpcode() == ISD::UNDEF)
4600       continue;
4601     if (i > 0)
4602       isOnlyLowElement = false;
4603     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4604       isConstant = false;
4605
4606     ValueCounts.insert(std::make_pair(V, 0));
4607     unsigned &Count = ValueCounts[V];
4608
4609     // Is this value dominant? (takes up more than half of the lanes)
4610     if (++Count > (NumElts / 2)) {
4611       hasDominantValue = true;
4612       Value = V;
4613     }
4614   }
4615   if (ValueCounts.size() != 1)
4616     usesOnlyOneValue = false;
4617   if (!Value.getNode() && ValueCounts.size() > 0)
4618     Value = ValueCounts.begin()->first;
4619
4620   if (ValueCounts.size() == 0)
4621     return DAG.getUNDEF(VT);
4622
4623   if (isOnlyLowElement)
4624     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4625
4626   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4627
4628   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4629   // i32 and try again.
4630   if (hasDominantValue && EltSize <= 32) {
4631     if (!isConstant) {
4632       SDValue N;
4633
4634       // If we are VDUPing a value that comes directly from a vector, that will
4635       // cause an unnecessary move to and from a GPR, where instead we could
4636       // just use VDUPLANE. We can only do this if the lane being extracted
4637       // is at a constant index, as the VDUP from lane instructions only have
4638       // constant-index forms.
4639       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4640           isa<ConstantSDNode>(Value->getOperand(1))) {
4641         // We need to create a new undef vector to use for the VDUPLANE if the
4642         // size of the vector from which we get the value is different than the
4643         // size of the vector that we need to create. We will insert the element
4644         // such that the register coalescer will remove unnecessary copies.
4645         if (VT != Value->getOperand(0).getValueType()) {
4646           ConstantSDNode *constIndex;
4647           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4648           assert(constIndex && "The index is not a constant!");
4649           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4650                              VT.getVectorNumElements();
4651           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4652                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4653                         Value, DAG.getConstant(index, MVT::i32)),
4654                            DAG.getConstant(index, MVT::i32));
4655         } else
4656           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4657                         Value->getOperand(0), Value->getOperand(1));
4658       } else
4659         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4660
4661       if (!usesOnlyOneValue) {
4662         // The dominant value was splatted as 'N', but we now have to insert
4663         // all differing elements.
4664         for (unsigned I = 0; I < NumElts; ++I) {
4665           if (Op.getOperand(I) == Value)
4666             continue;
4667           SmallVector<SDValue, 3> Ops;
4668           Ops.push_back(N);
4669           Ops.push_back(Op.getOperand(I));
4670           Ops.push_back(DAG.getConstant(I, MVT::i32));
4671           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4672         }
4673       }
4674       return N;
4675     }
4676     if (VT.getVectorElementType().isFloatingPoint()) {
4677       SmallVector<SDValue, 8> Ops;
4678       for (unsigned i = 0; i < NumElts; ++i)
4679         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4680                                   Op.getOperand(i)));
4681       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4682       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4683       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4684       if (Val.getNode())
4685         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4686     }
4687     if (usesOnlyOneValue) {
4688       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4689       if (isConstant && Val.getNode())
4690         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4691     }
4692   }
4693
4694   // If all elements are constants and the case above didn't get hit, fall back
4695   // to the default expansion, which will generate a load from the constant
4696   // pool.
4697   if (isConstant)
4698     return SDValue();
4699
4700   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4701   if (NumElts >= 4) {
4702     SDValue shuffle = ReconstructShuffle(Op, DAG);
4703     if (shuffle != SDValue())
4704       return shuffle;
4705   }
4706
4707   // Vectors with 32- or 64-bit elements can be built by directly assigning
4708   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4709   // will be legalized.
4710   if (EltSize >= 32) {
4711     // Do the expansion with floating-point types, since that is what the VFP
4712     // registers are defined to use, and since i64 is not legal.
4713     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4714     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4715     SmallVector<SDValue, 8> Ops;
4716     for (unsigned i = 0; i < NumElts; ++i)
4717       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4718     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4719     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4720   }
4721
4722   return SDValue();
4723 }
4724
4725 // Gather data to see if the operation can be modelled as a
4726 // shuffle in combination with VEXTs.
4727 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4728                                               SelectionDAG &DAG) const {
4729   SDLoc dl(Op);
4730   EVT VT = Op.getValueType();
4731   unsigned NumElts = VT.getVectorNumElements();
4732
4733   SmallVector<SDValue, 2> SourceVecs;
4734   SmallVector<unsigned, 2> MinElts;
4735   SmallVector<unsigned, 2> MaxElts;
4736
4737   for (unsigned i = 0; i < NumElts; ++i) {
4738     SDValue V = Op.getOperand(i);
4739     if (V.getOpcode() == ISD::UNDEF)
4740       continue;
4741     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4742       // A shuffle can only come from building a vector from various
4743       // elements of other vectors.
4744       return SDValue();
4745     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4746                VT.getVectorElementType()) {
4747       // This code doesn't know how to handle shuffles where the vector
4748       // element types do not match (this happens because type legalization
4749       // promotes the return type of EXTRACT_VECTOR_ELT).
4750       // FIXME: It might be appropriate to extend this code to handle
4751       // mismatched types.
4752       return SDValue();
4753     }
4754
4755     // Record this extraction against the appropriate vector if possible...
4756     SDValue SourceVec = V.getOperand(0);
4757     // If the element number isn't a constant, we can't effectively
4758     // analyze what's going on.
4759     if (!isa<ConstantSDNode>(V.getOperand(1)))
4760       return SDValue();
4761     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4762     bool FoundSource = false;
4763     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4764       if (SourceVecs[j] == SourceVec) {
4765         if (MinElts[j] > EltNo)
4766           MinElts[j] = EltNo;
4767         if (MaxElts[j] < EltNo)
4768           MaxElts[j] = EltNo;
4769         FoundSource = true;
4770         break;
4771       }
4772     }
4773
4774     // Or record a new source if not...
4775     if (!FoundSource) {
4776       SourceVecs.push_back(SourceVec);
4777       MinElts.push_back(EltNo);
4778       MaxElts.push_back(EltNo);
4779     }
4780   }
4781
4782   // Currently only do something sane when at most two source vectors
4783   // involved.
4784   if (SourceVecs.size() > 2)
4785     return SDValue();
4786
4787   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4788   int VEXTOffsets[2] = {0, 0};
4789
4790   // This loop extracts the usage patterns of the source vectors
4791   // and prepares appropriate SDValues for a shuffle if possible.
4792   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4793     if (SourceVecs[i].getValueType() == VT) {
4794       // No VEXT necessary
4795       ShuffleSrcs[i] = SourceVecs[i];
4796       VEXTOffsets[i] = 0;
4797       continue;
4798     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4799       // It probably isn't worth padding out a smaller vector just to
4800       // break it down again in a shuffle.
4801       return SDValue();
4802     }
4803
4804     // Since only 64-bit and 128-bit vectors are legal on ARM and
4805     // we've eliminated the other cases...
4806     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4807            "unexpected vector sizes in ReconstructShuffle");
4808
4809     if (MaxElts[i] - MinElts[i] >= NumElts) {
4810       // Span too large for a VEXT to cope
4811       return SDValue();
4812     }
4813
4814     if (MinElts[i] >= NumElts) {
4815       // The extraction can just take the second half
4816       VEXTOffsets[i] = NumElts;
4817       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4818                                    SourceVecs[i],
4819                                    DAG.getIntPtrConstant(NumElts));
4820     } else if (MaxElts[i] < NumElts) {
4821       // The extraction can just take the first half
4822       VEXTOffsets[i] = 0;
4823       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4824                                    SourceVecs[i],
4825                                    DAG.getIntPtrConstant(0));
4826     } else {
4827       // An actual VEXT is needed
4828       VEXTOffsets[i] = MinElts[i];
4829       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4830                                      SourceVecs[i],
4831                                      DAG.getIntPtrConstant(0));
4832       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4833                                      SourceVecs[i],
4834                                      DAG.getIntPtrConstant(NumElts));
4835       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4836                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4837     }
4838   }
4839
4840   SmallVector<int, 8> Mask;
4841
4842   for (unsigned i = 0; i < NumElts; ++i) {
4843     SDValue Entry = Op.getOperand(i);
4844     if (Entry.getOpcode() == ISD::UNDEF) {
4845       Mask.push_back(-1);
4846       continue;
4847     }
4848
4849     SDValue ExtractVec = Entry.getOperand(0);
4850     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4851                                           .getOperand(1))->getSExtValue();
4852     if (ExtractVec == SourceVecs[0]) {
4853       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4854     } else {
4855       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4856     }
4857   }
4858
4859   // Final check before we try to produce nonsense...
4860   if (isShuffleMaskLegal(Mask, VT))
4861     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4862                                 &Mask[0]);
4863
4864   return SDValue();
4865 }
4866
4867 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4868 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4869 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4870 /// are assumed to be legal.
4871 bool
4872 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4873                                       EVT VT) const {
4874   if (VT.getVectorNumElements() == 4 &&
4875       (VT.is128BitVector() || VT.is64BitVector())) {
4876     unsigned PFIndexes[4];
4877     for (unsigned i = 0; i != 4; ++i) {
4878       if (M[i] < 0)
4879         PFIndexes[i] = 8;
4880       else
4881         PFIndexes[i] = M[i];
4882     }
4883
4884     // Compute the index in the perfect shuffle table.
4885     unsigned PFTableIndex =
4886       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4887     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4888     unsigned Cost = (PFEntry >> 30);
4889
4890     if (Cost <= 4)
4891       return true;
4892   }
4893
4894   bool ReverseVEXT;
4895   unsigned Imm, WhichResult;
4896
4897   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4898   return (EltSize >= 32 ||
4899           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4900           isVREVMask(M, VT, 64) ||
4901           isVREVMask(M, VT, 32) ||
4902           isVREVMask(M, VT, 16) ||
4903           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4904           isVTBLMask(M, VT) ||
4905           isVTRNMask(M, VT, WhichResult) ||
4906           isVUZPMask(M, VT, WhichResult) ||
4907           isVZIPMask(M, VT, WhichResult) ||
4908           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4909           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4910           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
4911           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
4912 }
4913
4914 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4915 /// the specified operations to build the shuffle.
4916 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4917                                       SDValue RHS, SelectionDAG &DAG,
4918                                       SDLoc dl) {
4919   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4920   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4921   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4922
4923   enum {
4924     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4925     OP_VREV,
4926     OP_VDUP0,
4927     OP_VDUP1,
4928     OP_VDUP2,
4929     OP_VDUP3,
4930     OP_VEXT1,
4931     OP_VEXT2,
4932     OP_VEXT3,
4933     OP_VUZPL, // VUZP, left result
4934     OP_VUZPR, // VUZP, right result
4935     OP_VZIPL, // VZIP, left result
4936     OP_VZIPR, // VZIP, right result
4937     OP_VTRNL, // VTRN, left result
4938     OP_VTRNR  // VTRN, right result
4939   };
4940
4941   if (OpNum == OP_COPY) {
4942     if (LHSID == (1*9+2)*9+3) return LHS;
4943     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4944     return RHS;
4945   }
4946
4947   SDValue OpLHS, OpRHS;
4948   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4949   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4950   EVT VT = OpLHS.getValueType();
4951
4952   switch (OpNum) {
4953   default: llvm_unreachable("Unknown shuffle opcode!");
4954   case OP_VREV:
4955     // VREV divides the vector in half and swaps within the half.
4956     if (VT.getVectorElementType() == MVT::i32 ||
4957         VT.getVectorElementType() == MVT::f32)
4958       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4959     // vrev <4 x i16> -> VREV32
4960     if (VT.getVectorElementType() == MVT::i16)
4961       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4962     // vrev <4 x i8> -> VREV16
4963     assert(VT.getVectorElementType() == MVT::i8);
4964     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4965   case OP_VDUP0:
4966   case OP_VDUP1:
4967   case OP_VDUP2:
4968   case OP_VDUP3:
4969     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4970                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4971   case OP_VEXT1:
4972   case OP_VEXT2:
4973   case OP_VEXT3:
4974     return DAG.getNode(ARMISD::VEXT, dl, VT,
4975                        OpLHS, OpRHS,
4976                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4977   case OP_VUZPL:
4978   case OP_VUZPR:
4979     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4980                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4981   case OP_VZIPL:
4982   case OP_VZIPR:
4983     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4984                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4985   case OP_VTRNL:
4986   case OP_VTRNR:
4987     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4988                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4989   }
4990 }
4991
4992 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4993                                        ArrayRef<int> ShuffleMask,
4994                                        SelectionDAG &DAG) {
4995   // Check to see if we can use the VTBL instruction.
4996   SDValue V1 = Op.getOperand(0);
4997   SDValue V2 = Op.getOperand(1);
4998   SDLoc DL(Op);
4999
5000   SmallVector<SDValue, 8> VTBLMask;
5001   for (ArrayRef<int>::iterator
5002          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5003     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5004
5005   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5006     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5007                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5008                                    &VTBLMask[0], 8));
5009
5010   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5011                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5012                                  &VTBLMask[0], 8));
5013 }
5014
5015 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5016                                                       SelectionDAG &DAG) {
5017   SDLoc DL(Op);
5018   SDValue OpLHS = Op.getOperand(0);
5019   EVT VT = OpLHS.getValueType();
5020
5021   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5022          "Expect an v8i16/v16i8 type");
5023   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5024   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5025   // extract the first 8 bytes into the top double word and the last 8 bytes
5026   // into the bottom double word. The v8i16 case is similar.
5027   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5028   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5029                      DAG.getConstant(ExtractNum, MVT::i32));
5030 }
5031
5032 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5033   SDValue V1 = Op.getOperand(0);
5034   SDValue V2 = Op.getOperand(1);
5035   SDLoc dl(Op);
5036   EVT VT = Op.getValueType();
5037   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5038
5039   // Convert shuffles that are directly supported on NEON to target-specific
5040   // DAG nodes, instead of keeping them as shuffles and matching them again
5041   // during code selection.  This is more efficient and avoids the possibility
5042   // of inconsistencies between legalization and selection.
5043   // FIXME: floating-point vectors should be canonicalized to integer vectors
5044   // of the same time so that they get CSEd properly.
5045   ArrayRef<int> ShuffleMask = SVN->getMask();
5046
5047   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5048   if (EltSize <= 32) {
5049     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5050       int Lane = SVN->getSplatIndex();
5051       // If this is undef splat, generate it via "just" vdup, if possible.
5052       if (Lane == -1) Lane = 0;
5053
5054       // Test if V1 is a SCALAR_TO_VECTOR.
5055       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5056         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5057       }
5058       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5059       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5060       // reaches it).
5061       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5062           !isa<ConstantSDNode>(V1.getOperand(0))) {
5063         bool IsScalarToVector = true;
5064         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5065           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5066             IsScalarToVector = false;
5067             break;
5068           }
5069         if (IsScalarToVector)
5070           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5071       }
5072       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5073                          DAG.getConstant(Lane, MVT::i32));
5074     }
5075
5076     bool ReverseVEXT;
5077     unsigned Imm;
5078     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5079       if (ReverseVEXT)
5080         std::swap(V1, V2);
5081       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5082                          DAG.getConstant(Imm, MVT::i32));
5083     }
5084
5085     if (isVREVMask(ShuffleMask, VT, 64))
5086       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5087     if (isVREVMask(ShuffleMask, VT, 32))
5088       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5089     if (isVREVMask(ShuffleMask, VT, 16))
5090       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5091
5092     if (V2->getOpcode() == ISD::UNDEF &&
5093         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5094       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5095                          DAG.getConstant(Imm, MVT::i32));
5096     }
5097
5098     // Check for Neon shuffles that modify both input vectors in place.
5099     // If both results are used, i.e., if there are two shuffles with the same
5100     // source operands and with masks corresponding to both results of one of
5101     // these operations, DAG memoization will ensure that a single node is
5102     // used for both shuffles.
5103     unsigned WhichResult;
5104     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5105       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5106                          V1, V2).getValue(WhichResult);
5107     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5108       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5109                          V1, V2).getValue(WhichResult);
5110     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5111       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5112                          V1, V2).getValue(WhichResult);
5113
5114     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5115       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5116                          V1, V1).getValue(WhichResult);
5117     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5118       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5119                          V1, V1).getValue(WhichResult);
5120     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5121       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5122                          V1, V1).getValue(WhichResult);
5123   }
5124
5125   // If the shuffle is not directly supported and it has 4 elements, use
5126   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5127   unsigned NumElts = VT.getVectorNumElements();
5128   if (NumElts == 4) {
5129     unsigned PFIndexes[4];
5130     for (unsigned i = 0; i != 4; ++i) {
5131       if (ShuffleMask[i] < 0)
5132         PFIndexes[i] = 8;
5133       else
5134         PFIndexes[i] = ShuffleMask[i];
5135     }
5136
5137     // Compute the index in the perfect shuffle table.
5138     unsigned PFTableIndex =
5139       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5140     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5141     unsigned Cost = (PFEntry >> 30);
5142
5143     if (Cost <= 4)
5144       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5145   }
5146
5147   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5148   if (EltSize >= 32) {
5149     // Do the expansion with floating-point types, since that is what the VFP
5150     // registers are defined to use, and since i64 is not legal.
5151     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5152     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5153     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5154     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5155     SmallVector<SDValue, 8> Ops;
5156     for (unsigned i = 0; i < NumElts; ++i) {
5157       if (ShuffleMask[i] < 0)
5158         Ops.push_back(DAG.getUNDEF(EltVT));
5159       else
5160         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5161                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5162                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5163                                                   MVT::i32)));
5164     }
5165     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5166     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5167   }
5168
5169   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5170     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5171
5172   if (VT == MVT::v8i8) {
5173     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5174     if (NewOp.getNode())
5175       return NewOp;
5176   }
5177
5178   return SDValue();
5179 }
5180
5181 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5182   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5183   SDValue Lane = Op.getOperand(2);
5184   if (!isa<ConstantSDNode>(Lane))
5185     return SDValue();
5186
5187   return Op;
5188 }
5189
5190 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5191   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5192   SDValue Lane = Op.getOperand(1);
5193   if (!isa<ConstantSDNode>(Lane))
5194     return SDValue();
5195
5196   SDValue Vec = Op.getOperand(0);
5197   if (Op.getValueType() == MVT::i32 &&
5198       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5199     SDLoc dl(Op);
5200     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5201   }
5202
5203   return Op;
5204 }
5205
5206 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5207   // The only time a CONCAT_VECTORS operation can have legal types is when
5208   // two 64-bit vectors are concatenated to a 128-bit vector.
5209   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5210          "unexpected CONCAT_VECTORS");
5211   SDLoc dl(Op);
5212   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5213   SDValue Op0 = Op.getOperand(0);
5214   SDValue Op1 = Op.getOperand(1);
5215   if (Op0.getOpcode() != ISD::UNDEF)
5216     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5217                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5218                       DAG.getIntPtrConstant(0));
5219   if (Op1.getOpcode() != ISD::UNDEF)
5220     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5221                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5222                       DAG.getIntPtrConstant(1));
5223   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5224 }
5225
5226 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5227 /// element has been zero/sign-extended, depending on the isSigned parameter,
5228 /// from an integer type half its size.
5229 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5230                                    bool isSigned) {
5231   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5232   EVT VT = N->getValueType(0);
5233   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5234     SDNode *BVN = N->getOperand(0).getNode();
5235     if (BVN->getValueType(0) != MVT::v4i32 ||
5236         BVN->getOpcode() != ISD::BUILD_VECTOR)
5237       return false;
5238     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5239     unsigned HiElt = 1 - LoElt;
5240     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5241     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5242     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5243     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5244     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5245       return false;
5246     if (isSigned) {
5247       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5248           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5249         return true;
5250     } else {
5251       if (Hi0->isNullValue() && Hi1->isNullValue())
5252         return true;
5253     }
5254     return false;
5255   }
5256
5257   if (N->getOpcode() != ISD::BUILD_VECTOR)
5258     return false;
5259
5260   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5261     SDNode *Elt = N->getOperand(i).getNode();
5262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5263       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5264       unsigned HalfSize = EltSize / 2;
5265       if (isSigned) {
5266         if (!isIntN(HalfSize, C->getSExtValue()))
5267           return false;
5268       } else {
5269         if (!isUIntN(HalfSize, C->getZExtValue()))
5270           return false;
5271       }
5272       continue;
5273     }
5274     return false;
5275   }
5276
5277   return true;
5278 }
5279
5280 /// isSignExtended - Check if a node is a vector value that is sign-extended
5281 /// or a constant BUILD_VECTOR with sign-extended elements.
5282 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5283   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5284     return true;
5285   if (isExtendedBUILD_VECTOR(N, DAG, true))
5286     return true;
5287   return false;
5288 }
5289
5290 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5291 /// or a constant BUILD_VECTOR with zero-extended elements.
5292 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5293   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5294     return true;
5295   if (isExtendedBUILD_VECTOR(N, DAG, false))
5296     return true;
5297   return false;
5298 }
5299
5300 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5301   if (OrigVT.getSizeInBits() >= 64)
5302     return OrigVT;
5303
5304   assert(OrigVT.isSimple() && "Expecting a simple value type");
5305
5306   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5307   switch (OrigSimpleTy) {
5308   default: llvm_unreachable("Unexpected Vector Type");
5309   case MVT::v2i8:
5310   case MVT::v2i16:
5311      return MVT::v2i32;
5312   case MVT::v4i8:
5313     return  MVT::v4i16;
5314   }
5315 }
5316
5317 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5318 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5319 /// We insert the required extension here to get the vector to fill a D register.
5320 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5321                                             const EVT &OrigTy,
5322                                             const EVT &ExtTy,
5323                                             unsigned ExtOpcode) {
5324   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5325   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5326   // 64-bits we need to insert a new extension so that it will be 64-bits.
5327   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5328   if (OrigTy.getSizeInBits() >= 64)
5329     return N;
5330
5331   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5332   EVT NewVT = getExtensionTo64Bits(OrigTy);
5333
5334   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5335 }
5336
5337 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5338 /// does not do any sign/zero extension. If the original vector is less
5339 /// than 64 bits, an appropriate extension will be added after the load to
5340 /// reach a total size of 64 bits. We have to add the extension separately
5341 /// because ARM does not have a sign/zero extending load for vectors.
5342 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5343   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5344
5345   // The load already has the right type.
5346   if (ExtendedTy == LD->getMemoryVT())
5347     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5348                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5349                 LD->isNonTemporal(), LD->isInvariant(),
5350                 LD->getAlignment());
5351
5352   // We need to create a zextload/sextload. We cannot just create a load
5353   // followed by a zext/zext node because LowerMUL is also run during normal
5354   // operation legalization where we can't create illegal types.
5355   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5356                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5357                         LD->getMemoryVT(), LD->isVolatile(),
5358                         LD->isNonTemporal(), LD->getAlignment());
5359 }
5360
5361 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5362 /// extending load, or BUILD_VECTOR with extended elements, return the
5363 /// unextended value. The unextended vector should be 64 bits so that it can
5364 /// be used as an operand to a VMULL instruction. If the original vector size
5365 /// before extension is less than 64 bits we add a an extension to resize
5366 /// the vector to 64 bits.
5367 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5368   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5369     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5370                                         N->getOperand(0)->getValueType(0),
5371                                         N->getValueType(0),
5372                                         N->getOpcode());
5373
5374   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5375     return SkipLoadExtensionForVMULL(LD, DAG);
5376
5377   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5378   // have been legalized as a BITCAST from v4i32.
5379   if (N->getOpcode() == ISD::BITCAST) {
5380     SDNode *BVN = N->getOperand(0).getNode();
5381     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5382            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5383     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5384     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5385                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5386   }
5387   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5388   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5389   EVT VT = N->getValueType(0);
5390   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5391   unsigned NumElts = VT.getVectorNumElements();
5392   MVT TruncVT = MVT::getIntegerVT(EltSize);
5393   SmallVector<SDValue, 8> Ops;
5394   for (unsigned i = 0; i != NumElts; ++i) {
5395     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5396     const APInt &CInt = C->getAPIntValue();
5397     // Element types smaller than 32 bits are not legal, so use i32 elements.
5398     // The values are implicitly truncated so sext vs. zext doesn't matter.
5399     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5400   }
5401   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5402                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5403 }
5404
5405 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5406   unsigned Opcode = N->getOpcode();
5407   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5408     SDNode *N0 = N->getOperand(0).getNode();
5409     SDNode *N1 = N->getOperand(1).getNode();
5410     return N0->hasOneUse() && N1->hasOneUse() &&
5411       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5412   }
5413   return false;
5414 }
5415
5416 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5417   unsigned Opcode = N->getOpcode();
5418   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5419     SDNode *N0 = N->getOperand(0).getNode();
5420     SDNode *N1 = N->getOperand(1).getNode();
5421     return N0->hasOneUse() && N1->hasOneUse() &&
5422       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5423   }
5424   return false;
5425 }
5426
5427 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5428   // Multiplications are only custom-lowered for 128-bit vectors so that
5429   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5430   EVT VT = Op.getValueType();
5431   assert(VT.is128BitVector() && VT.isInteger() &&
5432          "unexpected type for custom-lowering ISD::MUL");
5433   SDNode *N0 = Op.getOperand(0).getNode();
5434   SDNode *N1 = Op.getOperand(1).getNode();
5435   unsigned NewOpc = 0;
5436   bool isMLA = false;
5437   bool isN0SExt = isSignExtended(N0, DAG);
5438   bool isN1SExt = isSignExtended(N1, DAG);
5439   if (isN0SExt && isN1SExt)
5440     NewOpc = ARMISD::VMULLs;
5441   else {
5442     bool isN0ZExt = isZeroExtended(N0, DAG);
5443     bool isN1ZExt = isZeroExtended(N1, DAG);
5444     if (isN0ZExt && isN1ZExt)
5445       NewOpc = ARMISD::VMULLu;
5446     else if (isN1SExt || isN1ZExt) {
5447       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5448       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5449       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5450         NewOpc = ARMISD::VMULLs;
5451         isMLA = true;
5452       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5453         NewOpc = ARMISD::VMULLu;
5454         isMLA = true;
5455       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5456         std::swap(N0, N1);
5457         NewOpc = ARMISD::VMULLu;
5458         isMLA = true;
5459       }
5460     }
5461
5462     if (!NewOpc) {
5463       if (VT == MVT::v2i64)
5464         // Fall through to expand this.  It is not legal.
5465         return SDValue();
5466       else
5467         // Other vector multiplications are legal.
5468         return Op;
5469     }
5470   }
5471
5472   // Legalize to a VMULL instruction.
5473   SDLoc DL(Op);
5474   SDValue Op0;
5475   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5476   if (!isMLA) {
5477     Op0 = SkipExtensionForVMULL(N0, DAG);
5478     assert(Op0.getValueType().is64BitVector() &&
5479            Op1.getValueType().is64BitVector() &&
5480            "unexpected types for extended operands to VMULL");
5481     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5482   }
5483
5484   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5485   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5486   //   vmull q0, d4, d6
5487   //   vmlal q0, d5, d6
5488   // is faster than
5489   //   vaddl q0, d4, d5
5490   //   vmovl q1, d6
5491   //   vmul  q0, q0, q1
5492   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5493   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5494   EVT Op1VT = Op1.getValueType();
5495   return DAG.getNode(N0->getOpcode(), DL, VT,
5496                      DAG.getNode(NewOpc, DL, VT,
5497                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5498                      DAG.getNode(NewOpc, DL, VT,
5499                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5500 }
5501
5502 static SDValue
5503 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5504   // Convert to float
5505   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5506   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5507   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5508   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5509   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5510   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5511   // Get reciprocal estimate.
5512   // float4 recip = vrecpeq_f32(yf);
5513   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5514                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5515   // Because char has a smaller range than uchar, we can actually get away
5516   // without any newton steps.  This requires that we use a weird bias
5517   // of 0xb000, however (again, this has been exhaustively tested).
5518   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5519   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5520   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5521   Y = DAG.getConstant(0xb000, MVT::i32);
5522   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5523   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5524   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5525   // Convert back to short.
5526   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5527   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5528   return X;
5529 }
5530
5531 static SDValue
5532 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5533   SDValue N2;
5534   // Convert to float.
5535   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5536   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5537   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5538   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5539   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5540   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5541
5542   // Use reciprocal estimate and one refinement step.
5543   // float4 recip = vrecpeq_f32(yf);
5544   // recip *= vrecpsq_f32(yf, recip);
5545   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5546                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5547   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5548                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5549                    N1, N2);
5550   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5551   // Because short has a smaller range than ushort, we can actually get away
5552   // with only a single newton step.  This requires that we use a weird bias
5553   // of 89, however (again, this has been exhaustively tested).
5554   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5555   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5556   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5557   N1 = DAG.getConstant(0x89, MVT::i32);
5558   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5559   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5560   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5561   // Convert back to integer and return.
5562   // return vmovn_s32(vcvt_s32_f32(result));
5563   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5564   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5565   return N0;
5566 }
5567
5568 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5569   EVT VT = Op.getValueType();
5570   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5571          "unexpected type for custom-lowering ISD::SDIV");
5572
5573   SDLoc dl(Op);
5574   SDValue N0 = Op.getOperand(0);
5575   SDValue N1 = Op.getOperand(1);
5576   SDValue N2, N3;
5577
5578   if (VT == MVT::v8i8) {
5579     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5580     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5581
5582     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5583                      DAG.getIntPtrConstant(4));
5584     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5585                      DAG.getIntPtrConstant(4));
5586     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5587                      DAG.getIntPtrConstant(0));
5588     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5589                      DAG.getIntPtrConstant(0));
5590
5591     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5592     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5593
5594     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5595     N0 = LowerCONCAT_VECTORS(N0, DAG);
5596
5597     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5598     return N0;
5599   }
5600   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5601 }
5602
5603 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5604   EVT VT = Op.getValueType();
5605   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5606          "unexpected type for custom-lowering ISD::UDIV");
5607
5608   SDLoc dl(Op);
5609   SDValue N0 = Op.getOperand(0);
5610   SDValue N1 = Op.getOperand(1);
5611   SDValue N2, N3;
5612
5613   if (VT == MVT::v8i8) {
5614     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5615     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5616
5617     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5618                      DAG.getIntPtrConstant(4));
5619     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5620                      DAG.getIntPtrConstant(4));
5621     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5622                      DAG.getIntPtrConstant(0));
5623     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5624                      DAG.getIntPtrConstant(0));
5625
5626     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5627     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5628
5629     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5630     N0 = LowerCONCAT_VECTORS(N0, DAG);
5631
5632     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5633                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5634                      N0);
5635     return N0;
5636   }
5637
5638   // v4i16 sdiv ... Convert to float.
5639   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5640   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5641   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5642   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5643   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5644   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5645
5646   // Use reciprocal estimate and two refinement steps.
5647   // float4 recip = vrecpeq_f32(yf);
5648   // recip *= vrecpsq_f32(yf, recip);
5649   // recip *= vrecpsq_f32(yf, recip);
5650   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5651                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5652   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5653                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5654                    BN1, N2);
5655   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5656   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5657                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5658                    BN1, N2);
5659   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5660   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5661   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5662   // and that it will never cause us to return an answer too large).
5663   // float4 result = as_float4(as_int4(xf*recip) + 2);
5664   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5665   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5666   N1 = DAG.getConstant(2, MVT::i32);
5667   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5668   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5669   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5670   // Convert back to integer and return.
5671   // return vmovn_u32(vcvt_s32_f32(result));
5672   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5673   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5674   return N0;
5675 }
5676
5677 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5678   EVT VT = Op.getNode()->getValueType(0);
5679   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5680
5681   unsigned Opc;
5682   bool ExtraOp = false;
5683   switch (Op.getOpcode()) {
5684   default: llvm_unreachable("Invalid code");
5685   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5686   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5687   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5688   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5689   }
5690
5691   if (!ExtraOp)
5692     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5693                        Op.getOperand(1));
5694   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5695                      Op.getOperand(1), Op.getOperand(2));
5696 }
5697
5698 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5699   // Monotonic load/store is legal for all targets
5700   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5701     return Op;
5702
5703   // Aquire/Release load/store is not legal for targets without a
5704   // dmb or equivalent available.
5705   return SDValue();
5706 }
5707
5708 static void
5709 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5710                     SelectionDAG &DAG, unsigned NewOp) {
5711   SDLoc dl(Node);
5712   assert (Node->getValueType(0) == MVT::i64 &&
5713           "Only know how to expand i64 atomics");
5714
5715   SmallVector<SDValue, 6> Ops;
5716   Ops.push_back(Node->getOperand(0)); // Chain
5717   Ops.push_back(Node->getOperand(1)); // Ptr
5718   // Low part of Val1
5719   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5720                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5721   // High part of Val1
5722   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5723                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5724   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5725     // High part of Val1
5726     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5727                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5728     // High part of Val2
5729     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5730                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5731   }
5732   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5733   SDValue Result =
5734     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5735                             cast<MemSDNode>(Node)->getMemOperand());
5736   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5737   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5738   Results.push_back(Result.getValue(2));
5739 }
5740
5741 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5742                                     SmallVectorImpl<SDValue> &Results,
5743                                     SelectionDAG &DAG,
5744                                     const ARMSubtarget *Subtarget) {
5745   SDLoc DL(N);
5746   SDValue Cycles32, OutChain;
5747
5748   if (Subtarget->hasPerfMon()) {
5749     // Under Power Management extensions, the cycle-count is:
5750     //    mrc p15, #0, <Rt>, c9, c13, #0
5751     SDValue Ops[] = { N->getOperand(0), // Chain
5752                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5753                       DAG.getConstant(15, MVT::i32),
5754                       DAG.getConstant(0, MVT::i32),
5755                       DAG.getConstant(9, MVT::i32),
5756                       DAG.getConstant(13, MVT::i32),
5757                       DAG.getConstant(0, MVT::i32)
5758     };
5759
5760     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
5761                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
5762                            array_lengthof(Ops));
5763     OutChain = Cycles32.getValue(1);
5764   } else {
5765     // Intrinsic is defined to return 0 on unsupported platforms. Technically
5766     // there are older ARM CPUs that have implementation-specific ways of
5767     // obtaining this information (FIXME!).
5768     Cycles32 = DAG.getConstant(0, MVT::i32);
5769     OutChain = DAG.getEntryNode();
5770   }
5771
5772
5773   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
5774                                  Cycles32, DAG.getConstant(0, MVT::i32));
5775   Results.push_back(Cycles64);
5776   Results.push_back(OutChain);
5777 }
5778
5779 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5780   switch (Op.getOpcode()) {
5781   default: llvm_unreachable("Don't know how to custom lower this!");
5782   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5783   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5784   case ISD::GlobalAddress:
5785     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5786       LowerGlobalAddressELF(Op, DAG);
5787   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5788   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5789   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5790   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5791   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5792   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5793   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5794   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5795   case ISD::SINT_TO_FP:
5796   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5797   case ISD::FP_TO_SINT:
5798   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5799   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5800   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5801   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5802   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5803   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5804   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5805   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5806                                                                Subtarget);
5807   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5808   case ISD::SHL:
5809   case ISD::SRL:
5810   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5811   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5812   case ISD::SRL_PARTS:
5813   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5814   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5815   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
5816   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5817   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
5818   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5819   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5820   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5821   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5822   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5823   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5824   case ISD::MUL:           return LowerMUL(Op, DAG);
5825   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5826   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5827   case ISD::ADDC:
5828   case ISD::ADDE:
5829   case ISD::SUBC:
5830   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5831   case ISD::ATOMIC_LOAD:
5832   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5833   }
5834 }
5835
5836 /// ReplaceNodeResults - Replace the results of node with an illegal result
5837 /// type with new values built out of custom code.
5838 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5839                                            SmallVectorImpl<SDValue>&Results,
5840                                            SelectionDAG &DAG) const {
5841   SDValue Res;
5842   switch (N->getOpcode()) {
5843   default:
5844     llvm_unreachable("Don't know how to custom expand this!");
5845   case ISD::BITCAST:
5846     Res = ExpandBITCAST(N, DAG);
5847     break;
5848   case ISD::SIGN_EXTEND:
5849   case ISD::ZERO_EXTEND:
5850     Res = ExpandVectorExtension(N, DAG);
5851     break;
5852   case ISD::SRL:
5853   case ISD::SRA:
5854     Res = Expand64BitShift(N, DAG, Subtarget);
5855     break;
5856   case ISD::READCYCLECOUNTER:
5857     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
5858     return;
5859   case ISD::ATOMIC_LOAD_ADD:
5860     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5861     return;
5862   case ISD::ATOMIC_LOAD_AND:
5863     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5864     return;
5865   case ISD::ATOMIC_LOAD_NAND:
5866     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5867     return;
5868   case ISD::ATOMIC_LOAD_OR:
5869     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5870     return;
5871   case ISD::ATOMIC_LOAD_SUB:
5872     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5873     return;
5874   case ISD::ATOMIC_LOAD_XOR:
5875     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5876     return;
5877   case ISD::ATOMIC_SWAP:
5878     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5879     return;
5880   case ISD::ATOMIC_CMP_SWAP:
5881     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5882     return;
5883   case ISD::ATOMIC_LOAD_MIN:
5884     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMIN64_DAG);
5885     return;
5886   case ISD::ATOMIC_LOAD_UMIN:
5887     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMIN64_DAG);
5888     return;
5889   case ISD::ATOMIC_LOAD_MAX:
5890     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMMAX64_DAG);
5891     return;
5892   case ISD::ATOMIC_LOAD_UMAX:
5893     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMUMAX64_DAG);
5894     return;
5895   }
5896   if (Res.getNode())
5897     Results.push_back(Res);
5898 }
5899
5900 //===----------------------------------------------------------------------===//
5901 //                           ARM Scheduler Hooks
5902 //===----------------------------------------------------------------------===//
5903
5904 MachineBasicBlock *
5905 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5906                                      MachineBasicBlock *BB,
5907                                      unsigned Size) const {
5908   unsigned dest    = MI->getOperand(0).getReg();
5909   unsigned ptr     = MI->getOperand(1).getReg();
5910   unsigned oldval  = MI->getOperand(2).getReg();
5911   unsigned newval  = MI->getOperand(3).getReg();
5912   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5913   DebugLoc dl = MI->getDebugLoc();
5914   bool isThumb2 = Subtarget->isThumb2();
5915
5916   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5917   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
5918     (const TargetRegisterClass*)&ARM::rGPRRegClass :
5919     (const TargetRegisterClass*)&ARM::GPRRegClass);
5920
5921   if (isThumb2) {
5922     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
5923     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
5924     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
5925   }
5926
5927   unsigned ldrOpc, strOpc;
5928   switch (Size) {
5929   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5930   case 1:
5931     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5932     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5933     break;
5934   case 2:
5935     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5936     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5937     break;
5938   case 4:
5939     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5940     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5941     break;
5942   }
5943
5944   MachineFunction *MF = BB->getParent();
5945   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5946   MachineFunction::iterator It = BB;
5947   ++It; // insert the new blocks after the current block
5948
5949   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5950   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5951   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5952   MF->insert(It, loop1MBB);
5953   MF->insert(It, loop2MBB);
5954   MF->insert(It, exitMBB);
5955
5956   // Transfer the remainder of BB and its successor edges to exitMBB.
5957   exitMBB->splice(exitMBB->begin(), BB,
5958                   llvm::next(MachineBasicBlock::iterator(MI)),
5959                   BB->end());
5960   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5961
5962   //  thisMBB:
5963   //   ...
5964   //   fallthrough --> loop1MBB
5965   BB->addSuccessor(loop1MBB);
5966
5967   // loop1MBB:
5968   //   ldrex dest, [ptr]
5969   //   cmp dest, oldval
5970   //   bne exitMBB
5971   BB = loop1MBB;
5972   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5973   if (ldrOpc == ARM::t2LDREX)
5974     MIB.addImm(0);
5975   AddDefaultPred(MIB);
5976   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5977                  .addReg(dest).addReg(oldval));
5978   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5979     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5980   BB->addSuccessor(loop2MBB);
5981   BB->addSuccessor(exitMBB);
5982
5983   // loop2MBB:
5984   //   strex scratch, newval, [ptr]
5985   //   cmp scratch, #0
5986   //   bne loop1MBB
5987   BB = loop2MBB;
5988   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5989   if (strOpc == ARM::t2STREX)
5990     MIB.addImm(0);
5991   AddDefaultPred(MIB);
5992   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5993                  .addReg(scratch).addImm(0));
5994   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5995     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5996   BB->addSuccessor(loop1MBB);
5997   BB->addSuccessor(exitMBB);
5998
5999   //  exitMBB:
6000   //   ...
6001   BB = exitMBB;
6002
6003   MI->eraseFromParent();   // The instruction is gone now.
6004
6005   return BB;
6006 }
6007
6008 MachineBasicBlock *
6009 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6010                                     unsigned Size, unsigned BinOpcode) const {
6011   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6012   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6013
6014   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6015   MachineFunction *MF = BB->getParent();
6016   MachineFunction::iterator It = BB;
6017   ++It;
6018
6019   unsigned dest = MI->getOperand(0).getReg();
6020   unsigned ptr = MI->getOperand(1).getReg();
6021   unsigned incr = MI->getOperand(2).getReg();
6022   DebugLoc dl = MI->getDebugLoc();
6023   bool isThumb2 = Subtarget->isThumb2();
6024
6025   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6026   if (isThumb2) {
6027     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6028     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6029   }
6030
6031   unsigned ldrOpc, strOpc;
6032   switch (Size) {
6033   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6034   case 1:
6035     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6036     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6037     break;
6038   case 2:
6039     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6040     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6041     break;
6042   case 4:
6043     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6044     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6045     break;
6046   }
6047
6048   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6049   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6050   MF->insert(It, loopMBB);
6051   MF->insert(It, exitMBB);
6052
6053   // Transfer the remainder of BB and its successor edges to exitMBB.
6054   exitMBB->splice(exitMBB->begin(), BB,
6055                   llvm::next(MachineBasicBlock::iterator(MI)),
6056                   BB->end());
6057   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6058
6059   const TargetRegisterClass *TRC = isThumb2 ?
6060     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6061     (const TargetRegisterClass*)&ARM::GPRRegClass;
6062   unsigned scratch = MRI.createVirtualRegister(TRC);
6063   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6064
6065   //  thisMBB:
6066   //   ...
6067   //   fallthrough --> loopMBB
6068   BB->addSuccessor(loopMBB);
6069
6070   //  loopMBB:
6071   //   ldrex dest, ptr
6072   //   <binop> scratch2, dest, incr
6073   //   strex scratch, scratch2, ptr
6074   //   cmp scratch, #0
6075   //   bne- loopMBB
6076   //   fallthrough --> exitMBB
6077   BB = loopMBB;
6078   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6079   if (ldrOpc == ARM::t2LDREX)
6080     MIB.addImm(0);
6081   AddDefaultPred(MIB);
6082   if (BinOpcode) {
6083     // operand order needs to go the other way for NAND
6084     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6085       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6086                      addReg(incr).addReg(dest)).addReg(0);
6087     else
6088       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6089                      addReg(dest).addReg(incr)).addReg(0);
6090   }
6091
6092   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6093   if (strOpc == ARM::t2STREX)
6094     MIB.addImm(0);
6095   AddDefaultPred(MIB);
6096   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6097                  .addReg(scratch).addImm(0));
6098   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6099     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6100
6101   BB->addSuccessor(loopMBB);
6102   BB->addSuccessor(exitMBB);
6103
6104   //  exitMBB:
6105   //   ...
6106   BB = exitMBB;
6107
6108   MI->eraseFromParent();   // The instruction is gone now.
6109
6110   return BB;
6111 }
6112
6113 MachineBasicBlock *
6114 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6115                                           MachineBasicBlock *BB,
6116                                           unsigned Size,
6117                                           bool signExtend,
6118                                           ARMCC::CondCodes Cond) const {
6119   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6120
6121   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6122   MachineFunction *MF = BB->getParent();
6123   MachineFunction::iterator It = BB;
6124   ++It;
6125
6126   unsigned dest = MI->getOperand(0).getReg();
6127   unsigned ptr = MI->getOperand(1).getReg();
6128   unsigned incr = MI->getOperand(2).getReg();
6129   unsigned oldval = dest;
6130   DebugLoc dl = MI->getDebugLoc();
6131   bool isThumb2 = Subtarget->isThumb2();
6132
6133   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6134   if (isThumb2) {
6135     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6136     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6137   }
6138
6139   unsigned ldrOpc, strOpc, extendOpc;
6140   switch (Size) {
6141   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
6142   case 1:
6143     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
6144     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
6145     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6146     break;
6147   case 2:
6148     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
6149     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
6150     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6151     break;
6152   case 4:
6153     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
6154     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
6155     extendOpc = 0;
6156     break;
6157   }
6158
6159   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6160   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6161   MF->insert(It, loopMBB);
6162   MF->insert(It, exitMBB);
6163
6164   // Transfer the remainder of BB and its successor edges to exitMBB.
6165   exitMBB->splice(exitMBB->begin(), BB,
6166                   llvm::next(MachineBasicBlock::iterator(MI)),
6167                   BB->end());
6168   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6169
6170   const TargetRegisterClass *TRC = isThumb2 ?
6171     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6172     (const TargetRegisterClass*)&ARM::GPRRegClass;
6173   unsigned scratch = MRI.createVirtualRegister(TRC);
6174   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6175
6176   //  thisMBB:
6177   //   ...
6178   //   fallthrough --> loopMBB
6179   BB->addSuccessor(loopMBB);
6180
6181   //  loopMBB:
6182   //   ldrex dest, ptr
6183   //   (sign extend dest, if required)
6184   //   cmp dest, incr
6185   //   cmov.cond scratch2, incr, dest
6186   //   strex scratch, scratch2, ptr
6187   //   cmp scratch, #0
6188   //   bne- loopMBB
6189   //   fallthrough --> exitMBB
6190   BB = loopMBB;
6191   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6192   if (ldrOpc == ARM::t2LDREX)
6193     MIB.addImm(0);
6194   AddDefaultPred(MIB);
6195
6196   // Sign extend the value, if necessary.
6197   if (signExtend && extendOpc) {
6198     oldval = MRI.createVirtualRegister(&ARM::GPRRegClass);
6199     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6200                      .addReg(dest)
6201                      .addImm(0));
6202   }
6203
6204   // Build compare and cmov instructions.
6205   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6206                  .addReg(oldval).addReg(incr));
6207   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6208          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6209
6210   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6211   if (strOpc == ARM::t2STREX)
6212     MIB.addImm(0);
6213   AddDefaultPred(MIB);
6214   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6215                  .addReg(scratch).addImm(0));
6216   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6217     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6218
6219   BB->addSuccessor(loopMBB);
6220   BB->addSuccessor(exitMBB);
6221
6222   //  exitMBB:
6223   //   ...
6224   BB = exitMBB;
6225
6226   MI->eraseFromParent();   // The instruction is gone now.
6227
6228   return BB;
6229 }
6230
6231 MachineBasicBlock *
6232 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6233                                       unsigned Op1, unsigned Op2,
6234                                       bool NeedsCarry, bool IsCmpxchg,
6235                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6236   // This also handles ATOMIC_SWAP, indicated by Op1==0.
6237   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6238
6239   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6240   MachineFunction *MF = BB->getParent();
6241   MachineFunction::iterator It = BB;
6242   ++It;
6243
6244   unsigned destlo = MI->getOperand(0).getReg();
6245   unsigned desthi = MI->getOperand(1).getReg();
6246   unsigned ptr = MI->getOperand(2).getReg();
6247   unsigned vallo = MI->getOperand(3).getReg();
6248   unsigned valhi = MI->getOperand(4).getReg();
6249   DebugLoc dl = MI->getDebugLoc();
6250   bool isThumb2 = Subtarget->isThumb2();
6251
6252   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6253   if (isThumb2) {
6254     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6255     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6256     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6257   }
6258
6259   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6260   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6261   if (IsCmpxchg || IsMinMax)
6262     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6263   if (IsCmpxchg)
6264     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6265   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6266
6267   MF->insert(It, loopMBB);
6268   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6269   if (IsCmpxchg) MF->insert(It, cont2BB);
6270   MF->insert(It, exitMBB);
6271
6272   // Transfer the remainder of BB and its successor edges to exitMBB.
6273   exitMBB->splice(exitMBB->begin(), BB,
6274                   llvm::next(MachineBasicBlock::iterator(MI)),
6275                   BB->end());
6276   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6277
6278   const TargetRegisterClass *TRC = isThumb2 ?
6279     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6280     (const TargetRegisterClass*)&ARM::GPRRegClass;
6281   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6282
6283   //  thisMBB:
6284   //   ...
6285   //   fallthrough --> loopMBB
6286   BB->addSuccessor(loopMBB);
6287
6288   //  loopMBB:
6289   //   ldrexd r2, r3, ptr
6290   //   <binopa> r0, r2, incr
6291   //   <binopb> r1, r3, incr
6292   //   strexd storesuccess, r0, r1, ptr
6293   //   cmp storesuccess, #0
6294   //   bne- loopMBB
6295   //   fallthrough --> exitMBB
6296   BB = loopMBB;
6297
6298   // Load
6299   if (isThumb2) {
6300     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2LDREXD))
6301                    .addReg(destlo, RegState::Define)
6302                    .addReg(desthi, RegState::Define)
6303                    .addReg(ptr));
6304   } else {
6305     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6306     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDREXD))
6307                    .addReg(GPRPair0, RegState::Define).addReg(ptr));
6308     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6309     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6310       .addReg(GPRPair0, 0, ARM::gsub_0);
6311     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6312       .addReg(GPRPair0, 0, ARM::gsub_1);
6313   }
6314
6315   unsigned StoreLo, StoreHi;
6316   if (IsCmpxchg) {
6317     // Add early exit
6318     for (unsigned i = 0; i < 2; i++) {
6319       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6320                                                          ARM::CMPrr))
6321                      .addReg(i == 0 ? destlo : desthi)
6322                      .addReg(i == 0 ? vallo : valhi));
6323       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6324         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6325       BB->addSuccessor(exitMBB);
6326       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6327       BB = (i == 0 ? contBB : cont2BB);
6328     }
6329
6330     // Copy to physregs for strexd
6331     StoreLo = MI->getOperand(5).getReg();
6332     StoreHi = MI->getOperand(6).getReg();
6333   } else if (Op1) {
6334     // Perform binary operation
6335     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6336     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6337                    .addReg(destlo).addReg(vallo))
6338         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6339     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6340     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6341                    .addReg(desthi).addReg(valhi))
6342         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6343
6344     StoreLo = tmpRegLo;
6345     StoreHi = tmpRegHi;
6346   } else {
6347     // Copy to physregs for strexd
6348     StoreLo = vallo;
6349     StoreHi = valhi;
6350   }
6351   if (IsMinMax) {
6352     // Compare and branch to exit block.
6353     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6354       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6355     BB->addSuccessor(exitMBB);
6356     BB->addSuccessor(contBB);
6357     BB = contBB;
6358     StoreLo = vallo;
6359     StoreHi = valhi;
6360   }
6361
6362   // Store
6363   if (isThumb2) {
6364     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2STREXD), storesuccess)
6365                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6366   } else {
6367     // Marshal a pair...
6368     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6369     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6370     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6371     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6372     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6373       .addReg(UndefPair)
6374       .addReg(StoreLo)
6375       .addImm(ARM::gsub_0);
6376     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6377       .addReg(r1)
6378       .addReg(StoreHi)
6379       .addImm(ARM::gsub_1);
6380
6381     // ...and store it
6382     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::STREXD), storesuccess)
6383                    .addReg(StorePair).addReg(ptr));
6384   }
6385   // Cmp+jump
6386   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6387                  .addReg(storesuccess).addImm(0));
6388   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6389     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6390
6391   BB->addSuccessor(loopMBB);
6392   BB->addSuccessor(exitMBB);
6393
6394   //  exitMBB:
6395   //   ...
6396   BB = exitMBB;
6397
6398   MI->eraseFromParent();   // The instruction is gone now.
6399
6400   return BB;
6401 }
6402
6403 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6404 /// registers the function context.
6405 void ARMTargetLowering::
6406 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6407                        MachineBasicBlock *DispatchBB, int FI) const {
6408   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6409   DebugLoc dl = MI->getDebugLoc();
6410   MachineFunction *MF = MBB->getParent();
6411   MachineRegisterInfo *MRI = &MF->getRegInfo();
6412   MachineConstantPool *MCP = MF->getConstantPool();
6413   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6414   const Function *F = MF->getFunction();
6415
6416   bool isThumb = Subtarget->isThumb();
6417   bool isThumb2 = Subtarget->isThumb2();
6418
6419   unsigned PCLabelId = AFI->createPICLabelUId();
6420   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6421   ARMConstantPoolValue *CPV =
6422     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6423   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6424
6425   const TargetRegisterClass *TRC = isThumb ?
6426     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6427     (const TargetRegisterClass*)&ARM::GPRRegClass;
6428
6429   // Grab constant pool and fixed stack memory operands.
6430   MachineMemOperand *CPMMO =
6431     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6432                              MachineMemOperand::MOLoad, 4, 4);
6433
6434   MachineMemOperand *FIMMOSt =
6435     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6436                              MachineMemOperand::MOStore, 4, 4);
6437
6438   // Load the address of the dispatch MBB into the jump buffer.
6439   if (isThumb2) {
6440     // Incoming value: jbuf
6441     //   ldr.n  r5, LCPI1_1
6442     //   orr    r5, r5, #1
6443     //   add    r5, pc
6444     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6445     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6446     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6447                    .addConstantPoolIndex(CPI)
6448                    .addMemOperand(CPMMO));
6449     // Set the low bit because of thumb mode.
6450     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6451     AddDefaultCC(
6452       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6453                      .addReg(NewVReg1, RegState::Kill)
6454                      .addImm(0x01)));
6455     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6456     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6457       .addReg(NewVReg2, RegState::Kill)
6458       .addImm(PCLabelId);
6459     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6460                    .addReg(NewVReg3, RegState::Kill)
6461                    .addFrameIndex(FI)
6462                    .addImm(36)  // &jbuf[1] :: pc
6463                    .addMemOperand(FIMMOSt));
6464   } else if (isThumb) {
6465     // Incoming value: jbuf
6466     //   ldr.n  r1, LCPI1_4
6467     //   add    r1, pc
6468     //   mov    r2, #1
6469     //   orrs   r1, r2
6470     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6471     //   str    r1, [r2]
6472     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6473     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6474                    .addConstantPoolIndex(CPI)
6475                    .addMemOperand(CPMMO));
6476     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6477     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6478       .addReg(NewVReg1, RegState::Kill)
6479       .addImm(PCLabelId);
6480     // Set the low bit because of thumb mode.
6481     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6482     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6483                    .addReg(ARM::CPSR, RegState::Define)
6484                    .addImm(1));
6485     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6486     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6487                    .addReg(ARM::CPSR, RegState::Define)
6488                    .addReg(NewVReg2, RegState::Kill)
6489                    .addReg(NewVReg3, RegState::Kill));
6490     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6491     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6492                    .addFrameIndex(FI)
6493                    .addImm(36)); // &jbuf[1] :: pc
6494     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6495                    .addReg(NewVReg4, RegState::Kill)
6496                    .addReg(NewVReg5, RegState::Kill)
6497                    .addImm(0)
6498                    .addMemOperand(FIMMOSt));
6499   } else {
6500     // Incoming value: jbuf
6501     //   ldr  r1, LCPI1_1
6502     //   add  r1, pc, r1
6503     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6504     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6505     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6506                    .addConstantPoolIndex(CPI)
6507                    .addImm(0)
6508                    .addMemOperand(CPMMO));
6509     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6510     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6511                    .addReg(NewVReg1, RegState::Kill)
6512                    .addImm(PCLabelId));
6513     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6514                    .addReg(NewVReg2, RegState::Kill)
6515                    .addFrameIndex(FI)
6516                    .addImm(36)  // &jbuf[1] :: pc
6517                    .addMemOperand(FIMMOSt));
6518   }
6519 }
6520
6521 MachineBasicBlock *ARMTargetLowering::
6522 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6523   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6524   DebugLoc dl = MI->getDebugLoc();
6525   MachineFunction *MF = MBB->getParent();
6526   MachineRegisterInfo *MRI = &MF->getRegInfo();
6527   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6528   MachineFrameInfo *MFI = MF->getFrameInfo();
6529   int FI = MFI->getFunctionContextIndex();
6530
6531   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6532     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6533     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6534
6535   // Get a mapping of the call site numbers to all of the landing pads they're
6536   // associated with.
6537   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6538   unsigned MaxCSNum = 0;
6539   MachineModuleInfo &MMI = MF->getMMI();
6540   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6541        ++BB) {
6542     if (!BB->isLandingPad()) continue;
6543
6544     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6545     // pad.
6546     for (MachineBasicBlock::iterator
6547            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6548       if (!II->isEHLabel()) continue;
6549
6550       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6551       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6552
6553       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6554       for (SmallVectorImpl<unsigned>::iterator
6555              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6556            CSI != CSE; ++CSI) {
6557         CallSiteNumToLPad[*CSI].push_back(BB);
6558         MaxCSNum = std::max(MaxCSNum, *CSI);
6559       }
6560       break;
6561     }
6562   }
6563
6564   // Get an ordered list of the machine basic blocks for the jump table.
6565   std::vector<MachineBasicBlock*> LPadList;
6566   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6567   LPadList.reserve(CallSiteNumToLPad.size());
6568   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6569     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6570     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6571            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6572       LPadList.push_back(*II);
6573       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6574     }
6575   }
6576
6577   assert(!LPadList.empty() &&
6578          "No landing pad destinations for the dispatch jump table!");
6579
6580   // Create the jump table and associated information.
6581   MachineJumpTableInfo *JTI =
6582     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6583   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6584   unsigned UId = AFI->createJumpTableUId();
6585   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6586
6587   // Create the MBBs for the dispatch code.
6588
6589   // Shove the dispatch's address into the return slot in the function context.
6590   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6591   DispatchBB->setIsLandingPad();
6592
6593   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6594   unsigned trap_opcode;
6595   if (Subtarget->isThumb())
6596     trap_opcode = ARM::tTRAP;
6597   else
6598     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6599
6600   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6601   DispatchBB->addSuccessor(TrapBB);
6602
6603   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6604   DispatchBB->addSuccessor(DispContBB);
6605
6606   // Insert and MBBs.
6607   MF->insert(MF->end(), DispatchBB);
6608   MF->insert(MF->end(), DispContBB);
6609   MF->insert(MF->end(), TrapBB);
6610
6611   // Insert code into the entry block that creates and registers the function
6612   // context.
6613   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6614
6615   MachineMemOperand *FIMMOLd =
6616     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6617                              MachineMemOperand::MOLoad |
6618                              MachineMemOperand::MOVolatile, 4, 4);
6619
6620   MachineInstrBuilder MIB;
6621   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6622
6623   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6624   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6625
6626   // Add a register mask with no preserved registers.  This results in all
6627   // registers being marked as clobbered.
6628   MIB.addRegMask(RI.getNoPreservedMask());
6629
6630   unsigned NumLPads = LPadList.size();
6631   if (Subtarget->isThumb2()) {
6632     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6633     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6634                    .addFrameIndex(FI)
6635                    .addImm(4)
6636                    .addMemOperand(FIMMOLd));
6637
6638     if (NumLPads < 256) {
6639       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6640                      .addReg(NewVReg1)
6641                      .addImm(LPadList.size()));
6642     } else {
6643       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6644       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6645                      .addImm(NumLPads & 0xFFFF));
6646
6647       unsigned VReg2 = VReg1;
6648       if ((NumLPads & 0xFFFF0000) != 0) {
6649         VReg2 = MRI->createVirtualRegister(TRC);
6650         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6651                        .addReg(VReg1)
6652                        .addImm(NumLPads >> 16));
6653       }
6654
6655       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6656                      .addReg(NewVReg1)
6657                      .addReg(VReg2));
6658     }
6659
6660     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6661       .addMBB(TrapBB)
6662       .addImm(ARMCC::HI)
6663       .addReg(ARM::CPSR);
6664
6665     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6666     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6667                    .addJumpTableIndex(MJTI)
6668                    .addImm(UId));
6669
6670     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6671     AddDefaultCC(
6672       AddDefaultPred(
6673         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6674         .addReg(NewVReg3, RegState::Kill)
6675         .addReg(NewVReg1)
6676         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6677
6678     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6679       .addReg(NewVReg4, RegState::Kill)
6680       .addReg(NewVReg1)
6681       .addJumpTableIndex(MJTI)
6682       .addImm(UId);
6683   } else if (Subtarget->isThumb()) {
6684     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6685     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6686                    .addFrameIndex(FI)
6687                    .addImm(1)
6688                    .addMemOperand(FIMMOLd));
6689
6690     if (NumLPads < 256) {
6691       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6692                      .addReg(NewVReg1)
6693                      .addImm(NumLPads));
6694     } else {
6695       MachineConstantPool *ConstantPool = MF->getConstantPool();
6696       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6697       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6698
6699       // MachineConstantPool wants an explicit alignment.
6700       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6701       if (Align == 0)
6702         Align = getDataLayout()->getTypeAllocSize(C->getType());
6703       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6704
6705       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6706       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6707                      .addReg(VReg1, RegState::Define)
6708                      .addConstantPoolIndex(Idx));
6709       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6710                      .addReg(NewVReg1)
6711                      .addReg(VReg1));
6712     }
6713
6714     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6715       .addMBB(TrapBB)
6716       .addImm(ARMCC::HI)
6717       .addReg(ARM::CPSR);
6718
6719     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6720     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6721                    .addReg(ARM::CPSR, RegState::Define)
6722                    .addReg(NewVReg1)
6723                    .addImm(2));
6724
6725     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6726     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6727                    .addJumpTableIndex(MJTI)
6728                    .addImm(UId));
6729
6730     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6731     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6732                    .addReg(ARM::CPSR, RegState::Define)
6733                    .addReg(NewVReg2, RegState::Kill)
6734                    .addReg(NewVReg3));
6735
6736     MachineMemOperand *JTMMOLd =
6737       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6738                                MachineMemOperand::MOLoad, 4, 4);
6739
6740     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6741     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6742                    .addReg(NewVReg4, RegState::Kill)
6743                    .addImm(0)
6744                    .addMemOperand(JTMMOLd));
6745
6746     unsigned NewVReg6 = NewVReg5;
6747     if (RelocM == Reloc::PIC_) {
6748       NewVReg6 = MRI->createVirtualRegister(TRC);
6749       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6750                      .addReg(ARM::CPSR, RegState::Define)
6751                      .addReg(NewVReg5, RegState::Kill)
6752                      .addReg(NewVReg3));
6753     }
6754
6755     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6756       .addReg(NewVReg6, RegState::Kill)
6757       .addJumpTableIndex(MJTI)
6758       .addImm(UId);
6759   } else {
6760     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6761     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6762                    .addFrameIndex(FI)
6763                    .addImm(4)
6764                    .addMemOperand(FIMMOLd));
6765
6766     if (NumLPads < 256) {
6767       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6768                      .addReg(NewVReg1)
6769                      .addImm(NumLPads));
6770     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6771       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6772       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6773                      .addImm(NumLPads & 0xFFFF));
6774
6775       unsigned VReg2 = VReg1;
6776       if ((NumLPads & 0xFFFF0000) != 0) {
6777         VReg2 = MRI->createVirtualRegister(TRC);
6778         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6779                        .addReg(VReg1)
6780                        .addImm(NumLPads >> 16));
6781       }
6782
6783       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6784                      .addReg(NewVReg1)
6785                      .addReg(VReg2));
6786     } else {
6787       MachineConstantPool *ConstantPool = MF->getConstantPool();
6788       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6789       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6790
6791       // MachineConstantPool wants an explicit alignment.
6792       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6793       if (Align == 0)
6794         Align = getDataLayout()->getTypeAllocSize(C->getType());
6795       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6796
6797       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6798       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6799                      .addReg(VReg1, RegState::Define)
6800                      .addConstantPoolIndex(Idx)
6801                      .addImm(0));
6802       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6803                      .addReg(NewVReg1)
6804                      .addReg(VReg1, RegState::Kill));
6805     }
6806
6807     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6808       .addMBB(TrapBB)
6809       .addImm(ARMCC::HI)
6810       .addReg(ARM::CPSR);
6811
6812     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6813     AddDefaultCC(
6814       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6815                      .addReg(NewVReg1)
6816                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6817     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6818     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6819                    .addJumpTableIndex(MJTI)
6820                    .addImm(UId));
6821
6822     MachineMemOperand *JTMMOLd =
6823       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6824                                MachineMemOperand::MOLoad, 4, 4);
6825     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6826     AddDefaultPred(
6827       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6828       .addReg(NewVReg3, RegState::Kill)
6829       .addReg(NewVReg4)
6830       .addImm(0)
6831       .addMemOperand(JTMMOLd));
6832
6833     if (RelocM == Reloc::PIC_) {
6834       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6835         .addReg(NewVReg5, RegState::Kill)
6836         .addReg(NewVReg4)
6837         .addJumpTableIndex(MJTI)
6838         .addImm(UId);
6839     } else {
6840       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6841         .addReg(NewVReg5, RegState::Kill)
6842         .addJumpTableIndex(MJTI)
6843         .addImm(UId);
6844     }
6845   }
6846
6847   // Add the jump table entries as successors to the MBB.
6848   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6849   for (std::vector<MachineBasicBlock*>::iterator
6850          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6851     MachineBasicBlock *CurMBB = *I;
6852     if (SeenMBBs.insert(CurMBB))
6853       DispContBB->addSuccessor(CurMBB);
6854   }
6855
6856   // N.B. the order the invoke BBs are processed in doesn't matter here.
6857   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
6858   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6859   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6860          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6861     MachineBasicBlock *BB = *I;
6862
6863     // Remove the landing pad successor from the invoke block and replace it
6864     // with the new dispatch block.
6865     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6866                                                   BB->succ_end());
6867     while (!Successors.empty()) {
6868       MachineBasicBlock *SMBB = Successors.pop_back_val();
6869       if (SMBB->isLandingPad()) {
6870         BB->removeSuccessor(SMBB);
6871         MBBLPads.push_back(SMBB);
6872       }
6873     }
6874
6875     BB->addSuccessor(DispatchBB);
6876
6877     // Find the invoke call and mark all of the callee-saved registers as
6878     // 'implicit defined' so that they're spilled. This prevents code from
6879     // moving instructions to before the EH block, where they will never be
6880     // executed.
6881     for (MachineBasicBlock::reverse_iterator
6882            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6883       if (!II->isCall()) continue;
6884
6885       DenseMap<unsigned, bool> DefRegs;
6886       for (MachineInstr::mop_iterator
6887              OI = II->operands_begin(), OE = II->operands_end();
6888            OI != OE; ++OI) {
6889         if (!OI->isReg()) continue;
6890         DefRegs[OI->getReg()] = true;
6891       }
6892
6893       MachineInstrBuilder MIB(*MF, &*II);
6894
6895       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6896         unsigned Reg = SavedRegs[i];
6897         if (Subtarget->isThumb2() &&
6898             !ARM::tGPRRegClass.contains(Reg) &&
6899             !ARM::hGPRRegClass.contains(Reg))
6900           continue;
6901         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6902           continue;
6903         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6904           continue;
6905         if (!DefRegs[Reg])
6906           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6907       }
6908
6909       break;
6910     }
6911   }
6912
6913   // Mark all former landing pads as non-landing pads. The dispatch is the only
6914   // landing pad now.
6915   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6916          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6917     (*I)->setIsLandingPad(false);
6918
6919   // The instruction is gone now.
6920   MI->eraseFromParent();
6921
6922   return MBB;
6923 }
6924
6925 static
6926 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6927   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6928        E = MBB->succ_end(); I != E; ++I)
6929     if (*I != Succ)
6930       return *I;
6931   llvm_unreachable("Expecting a BB with two successors!");
6932 }
6933
6934 MachineBasicBlock *ARMTargetLowering::
6935 EmitStructByval(MachineInstr *MI, MachineBasicBlock *BB) const {
6936   // This pseudo instruction has 3 operands: dst, src, size
6937   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6938   // Otherwise, we will generate unrolled scalar copies.
6939   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6940   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6941   MachineFunction::iterator It = BB;
6942   ++It;
6943
6944   unsigned dest = MI->getOperand(0).getReg();
6945   unsigned src = MI->getOperand(1).getReg();
6946   unsigned SizeVal = MI->getOperand(2).getImm();
6947   unsigned Align = MI->getOperand(3).getImm();
6948   DebugLoc dl = MI->getDebugLoc();
6949
6950   bool isThumb2 = Subtarget->isThumb2();
6951   MachineFunction *MF = BB->getParent();
6952   MachineRegisterInfo &MRI = MF->getRegInfo();
6953   unsigned ldrOpc, strOpc, UnitSize = 0;
6954
6955   const TargetRegisterClass *TRC = isThumb2 ?
6956     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6957     (const TargetRegisterClass*)&ARM::GPRRegClass;
6958   const TargetRegisterClass *TRC_Vec = 0;
6959
6960   if (Align & 1) {
6961     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
6962     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
6963     UnitSize = 1;
6964   } else if (Align & 2) {
6965     ldrOpc = isThumb2 ? ARM::t2LDRH_POST : ARM::LDRH_POST;
6966     strOpc = isThumb2 ? ARM::t2STRH_POST : ARM::STRH_POST;
6967     UnitSize = 2;
6968   } else {
6969     // Check whether we can use NEON instructions.
6970     if (!MF->getFunction()->getAttributes().
6971           hasAttribute(AttributeSet::FunctionIndex,
6972                        Attribute::NoImplicitFloat) &&
6973         Subtarget->hasNEON()) {
6974       if ((Align % 16 == 0) && SizeVal >= 16) {
6975         ldrOpc = ARM::VLD1q32wb_fixed;
6976         strOpc = ARM::VST1q32wb_fixed;
6977         UnitSize = 16;
6978         TRC_Vec = (const TargetRegisterClass*)&ARM::DPairRegClass;
6979       }
6980       else if ((Align % 8 == 0) && SizeVal >= 8) {
6981         ldrOpc = ARM::VLD1d32wb_fixed;
6982         strOpc = ARM::VST1d32wb_fixed;
6983         UnitSize = 8;
6984         TRC_Vec = (const TargetRegisterClass*)&ARM::DPRRegClass;
6985       }
6986     }
6987     // Can't use NEON instructions.
6988     if (UnitSize == 0) {
6989       ldrOpc = isThumb2 ? ARM::t2LDR_POST : ARM::LDR_POST_IMM;
6990       strOpc = isThumb2 ? ARM::t2STR_POST : ARM::STR_POST_IMM;
6991       UnitSize = 4;
6992     }
6993   }
6994
6995   unsigned BytesLeft = SizeVal % UnitSize;
6996   unsigned LoopSize = SizeVal - BytesLeft;
6997
6998   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6999     // Use LDR and STR to copy.
7000     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7001     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7002     unsigned srcIn = src;
7003     unsigned destIn = dest;
7004     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7005       unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7006       unsigned srcOut = MRI.createVirtualRegister(TRC);
7007       unsigned destOut = MRI.createVirtualRegister(TRC);
7008       if (UnitSize >= 8) {
7009         AddDefaultPred(BuildMI(*BB, MI, dl,
7010           TII->get(ldrOpc), scratch)
7011           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(0));
7012
7013         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7014           .addReg(destIn).addImm(0).addReg(scratch));
7015       } else if (isThumb2) {
7016         AddDefaultPred(BuildMI(*BB, MI, dl,
7017           TII->get(ldrOpc), scratch)
7018           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(UnitSize));
7019
7020         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7021           .addReg(scratch).addReg(destIn)
7022           .addImm(UnitSize));
7023       } else {
7024         AddDefaultPred(BuildMI(*BB, MI, dl,
7025           TII->get(ldrOpc), scratch)
7026           .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0)
7027           .addImm(UnitSize));
7028
7029         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7030           .addReg(scratch).addReg(destIn)
7031           .addReg(0).addImm(UnitSize));
7032       }
7033       srcIn = srcOut;
7034       destIn = destOut;
7035     }
7036
7037     // Handle the leftover bytes with LDRB and STRB.
7038     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7039     // [destOut] = STRB_POST(scratch, destIn, 1)
7040     ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7041     strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7042     for (unsigned i = 0; i < BytesLeft; i++) {
7043       unsigned scratch = MRI.createVirtualRegister(TRC);
7044       unsigned srcOut = MRI.createVirtualRegister(TRC);
7045       unsigned destOut = MRI.createVirtualRegister(TRC);
7046       if (isThumb2) {
7047         AddDefaultPred(BuildMI(*BB, MI, dl,
7048           TII->get(ldrOpc),scratch)
7049           .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7050
7051         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7052           .addReg(scratch).addReg(destIn)
7053           .addReg(0).addImm(1));
7054       } else {
7055         AddDefaultPred(BuildMI(*BB, MI, dl,
7056           TII->get(ldrOpc),scratch)
7057           .addReg(srcOut, RegState::Define).addReg(srcIn)
7058           .addReg(0).addImm(1));
7059
7060         AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(strOpc), destOut)
7061           .addReg(scratch).addReg(destIn)
7062           .addReg(0).addImm(1));
7063       }
7064       srcIn = srcOut;
7065       destIn = destOut;
7066     }
7067     MI->eraseFromParent();   // The instruction is gone now.
7068     return BB;
7069   }
7070
7071   // Expand the pseudo op to a loop.
7072   // thisMBB:
7073   //   ...
7074   //   movw varEnd, # --> with thumb2
7075   //   movt varEnd, #
7076   //   ldrcp varEnd, idx --> without thumb2
7077   //   fallthrough --> loopMBB
7078   // loopMBB:
7079   //   PHI varPhi, varEnd, varLoop
7080   //   PHI srcPhi, src, srcLoop
7081   //   PHI destPhi, dst, destLoop
7082   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7083   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7084   //   subs varLoop, varPhi, #UnitSize
7085   //   bne loopMBB
7086   //   fallthrough --> exitMBB
7087   // exitMBB:
7088   //   epilogue to handle left-over bytes
7089   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7090   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7091   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7092   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7093   MF->insert(It, loopMBB);
7094   MF->insert(It, exitMBB);
7095
7096   // Transfer the remainder of BB and its successor edges to exitMBB.
7097   exitMBB->splice(exitMBB->begin(), BB,
7098                   llvm::next(MachineBasicBlock::iterator(MI)),
7099                   BB->end());
7100   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7101
7102   // Load an immediate to varEnd.
7103   unsigned varEnd = MRI.createVirtualRegister(TRC);
7104   if (isThumb2) {
7105     unsigned VReg1 = varEnd;
7106     if ((LoopSize & 0xFFFF0000) != 0)
7107       VReg1 = MRI.createVirtualRegister(TRC);
7108     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), VReg1)
7109                    .addImm(LoopSize & 0xFFFF));
7110
7111     if ((LoopSize & 0xFFFF0000) != 0)
7112       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7113                      .addReg(VReg1)
7114                      .addImm(LoopSize >> 16));
7115   } else {
7116     MachineConstantPool *ConstantPool = MF->getConstantPool();
7117     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7118     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7119
7120     // MachineConstantPool wants an explicit alignment.
7121     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7122     if (Align == 0)
7123       Align = getDataLayout()->getTypeAllocSize(C->getType());
7124     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7125
7126     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::LDRcp))
7127                    .addReg(varEnd, RegState::Define)
7128                    .addConstantPoolIndex(Idx)
7129                    .addImm(0));
7130   }
7131   BB->addSuccessor(loopMBB);
7132
7133   // Generate the loop body:
7134   //   varPhi = PHI(varLoop, varEnd)
7135   //   srcPhi = PHI(srcLoop, src)
7136   //   destPhi = PHI(destLoop, dst)
7137   MachineBasicBlock *entryBB = BB;
7138   BB = loopMBB;
7139   unsigned varLoop = MRI.createVirtualRegister(TRC);
7140   unsigned varPhi = MRI.createVirtualRegister(TRC);
7141   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7142   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7143   unsigned destLoop = MRI.createVirtualRegister(TRC);
7144   unsigned destPhi = MRI.createVirtualRegister(TRC);
7145
7146   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7147     .addReg(varLoop).addMBB(loopMBB)
7148     .addReg(varEnd).addMBB(entryBB);
7149   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7150     .addReg(srcLoop).addMBB(loopMBB)
7151     .addReg(src).addMBB(entryBB);
7152   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7153     .addReg(destLoop).addMBB(loopMBB)
7154     .addReg(dest).addMBB(entryBB);
7155
7156   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7157   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7158   unsigned scratch = MRI.createVirtualRegister(UnitSize >= 8 ? TRC_Vec:TRC);
7159   if (UnitSize >= 8) {
7160     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7161       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(0));
7162
7163     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7164       .addReg(destPhi).addImm(0).addReg(scratch));
7165   } else if (isThumb2) {
7166     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7167       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addImm(UnitSize));
7168
7169     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7170       .addReg(scratch).addReg(destPhi)
7171       .addImm(UnitSize));
7172   } else {
7173     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc), scratch)
7174       .addReg(srcLoop, RegState::Define).addReg(srcPhi).addReg(0)
7175       .addImm(UnitSize));
7176
7177     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), destLoop)
7178       .addReg(scratch).addReg(destPhi)
7179       .addReg(0).addImm(UnitSize));
7180   }
7181
7182   // Decrement loop variable by UnitSize.
7183   MachineInstrBuilder MIB = BuildMI(BB, dl,
7184     TII->get(isThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7185   AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7186   MIB->getOperand(5).setReg(ARM::CPSR);
7187   MIB->getOperand(5).setIsDef(true);
7188
7189   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7190     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7191
7192   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7193   BB->addSuccessor(loopMBB);
7194   BB->addSuccessor(exitMBB);
7195
7196   // Add epilogue to handle BytesLeft.
7197   BB = exitMBB;
7198   MachineInstr *StartOfExit = exitMBB->begin();
7199   ldrOpc = isThumb2 ? ARM::t2LDRB_POST : ARM::LDRB_POST_IMM;
7200   strOpc = isThumb2 ? ARM::t2STRB_POST : ARM::STRB_POST_IMM;
7201
7202   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7203   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7204   unsigned srcIn = srcLoop;
7205   unsigned destIn = destLoop;
7206   for (unsigned i = 0; i < BytesLeft; i++) {
7207     unsigned scratch = MRI.createVirtualRegister(TRC);
7208     unsigned srcOut = MRI.createVirtualRegister(TRC);
7209     unsigned destOut = MRI.createVirtualRegister(TRC);
7210     if (isThumb2) {
7211       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7212         TII->get(ldrOpc),scratch)
7213         .addReg(srcOut, RegState::Define).addReg(srcIn).addImm(1));
7214
7215       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7216         .addReg(scratch).addReg(destIn)
7217         .addImm(1));
7218     } else {
7219       AddDefaultPred(BuildMI(*BB, StartOfExit, dl,
7220         TII->get(ldrOpc),scratch)
7221         .addReg(srcOut, RegState::Define).addReg(srcIn).addReg(0).addImm(1));
7222
7223       AddDefaultPred(BuildMI(*BB, StartOfExit, dl, TII->get(strOpc), destOut)
7224         .addReg(scratch).addReg(destIn)
7225         .addReg(0).addImm(1));
7226     }
7227     srcIn = srcOut;
7228     destIn = destOut;
7229   }
7230
7231   MI->eraseFromParent();   // The instruction is gone now.
7232   return BB;
7233 }
7234
7235 MachineBasicBlock *
7236 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7237                                                MachineBasicBlock *BB) const {
7238   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7239   DebugLoc dl = MI->getDebugLoc();
7240   bool isThumb2 = Subtarget->isThumb2();
7241   switch (MI->getOpcode()) {
7242   default: {
7243     MI->dump();
7244     llvm_unreachable("Unexpected instr type to insert");
7245   }
7246   // The Thumb2 pre-indexed stores have the same MI operands, they just
7247   // define them differently in the .td files from the isel patterns, so
7248   // they need pseudos.
7249   case ARM::t2STR_preidx:
7250     MI->setDesc(TII->get(ARM::t2STR_PRE));
7251     return BB;
7252   case ARM::t2STRB_preidx:
7253     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7254     return BB;
7255   case ARM::t2STRH_preidx:
7256     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7257     return BB;
7258
7259   case ARM::STRi_preidx:
7260   case ARM::STRBi_preidx: {
7261     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7262       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7263     // Decode the offset.
7264     unsigned Offset = MI->getOperand(4).getImm();
7265     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7266     Offset = ARM_AM::getAM2Offset(Offset);
7267     if (isSub)
7268       Offset = -Offset;
7269
7270     MachineMemOperand *MMO = *MI->memoperands_begin();
7271     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7272       .addOperand(MI->getOperand(0))  // Rn_wb
7273       .addOperand(MI->getOperand(1))  // Rt
7274       .addOperand(MI->getOperand(2))  // Rn
7275       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7276       .addOperand(MI->getOperand(5))  // pred
7277       .addOperand(MI->getOperand(6))
7278       .addMemOperand(MMO);
7279     MI->eraseFromParent();
7280     return BB;
7281   }
7282   case ARM::STRr_preidx:
7283   case ARM::STRBr_preidx:
7284   case ARM::STRH_preidx: {
7285     unsigned NewOpc;
7286     switch (MI->getOpcode()) {
7287     default: llvm_unreachable("unexpected opcode!");
7288     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7289     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7290     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7291     }
7292     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7293     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7294       MIB.addOperand(MI->getOperand(i));
7295     MI->eraseFromParent();
7296     return BB;
7297   }
7298   case ARM::ATOMIC_LOAD_ADD_I8:
7299      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7300   case ARM::ATOMIC_LOAD_ADD_I16:
7301      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7302   case ARM::ATOMIC_LOAD_ADD_I32:
7303      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7304
7305   case ARM::ATOMIC_LOAD_AND_I8:
7306      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7307   case ARM::ATOMIC_LOAD_AND_I16:
7308      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7309   case ARM::ATOMIC_LOAD_AND_I32:
7310      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7311
7312   case ARM::ATOMIC_LOAD_OR_I8:
7313      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7314   case ARM::ATOMIC_LOAD_OR_I16:
7315      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7316   case ARM::ATOMIC_LOAD_OR_I32:
7317      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7318
7319   case ARM::ATOMIC_LOAD_XOR_I8:
7320      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7321   case ARM::ATOMIC_LOAD_XOR_I16:
7322      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7323   case ARM::ATOMIC_LOAD_XOR_I32:
7324      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7325
7326   case ARM::ATOMIC_LOAD_NAND_I8:
7327      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7328   case ARM::ATOMIC_LOAD_NAND_I16:
7329      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7330   case ARM::ATOMIC_LOAD_NAND_I32:
7331      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7332
7333   case ARM::ATOMIC_LOAD_SUB_I8:
7334      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7335   case ARM::ATOMIC_LOAD_SUB_I16:
7336      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7337   case ARM::ATOMIC_LOAD_SUB_I32:
7338      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7339
7340   case ARM::ATOMIC_LOAD_MIN_I8:
7341      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7342   case ARM::ATOMIC_LOAD_MIN_I16:
7343      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7344   case ARM::ATOMIC_LOAD_MIN_I32:
7345      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7346
7347   case ARM::ATOMIC_LOAD_MAX_I8:
7348      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7349   case ARM::ATOMIC_LOAD_MAX_I16:
7350      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7351   case ARM::ATOMIC_LOAD_MAX_I32:
7352      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7353
7354   case ARM::ATOMIC_LOAD_UMIN_I8:
7355      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7356   case ARM::ATOMIC_LOAD_UMIN_I16:
7357      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7358   case ARM::ATOMIC_LOAD_UMIN_I32:
7359      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7360
7361   case ARM::ATOMIC_LOAD_UMAX_I8:
7362      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7363   case ARM::ATOMIC_LOAD_UMAX_I16:
7364      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7365   case ARM::ATOMIC_LOAD_UMAX_I32:
7366      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7367
7368   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7369   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7370   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7371
7372   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7373   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7374   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7375
7376
7377   case ARM::ATOMADD6432:
7378     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7379                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7380                               /*NeedsCarry*/ true);
7381   case ARM::ATOMSUB6432:
7382     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7383                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7384                               /*NeedsCarry*/ true);
7385   case ARM::ATOMOR6432:
7386     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7387                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7388   case ARM::ATOMXOR6432:
7389     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7390                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7391   case ARM::ATOMAND6432:
7392     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7393                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7394   case ARM::ATOMSWAP6432:
7395     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7396   case ARM::ATOMCMPXCHG6432:
7397     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7398                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7399                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7400   case ARM::ATOMMIN6432:
7401     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7402                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7403                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7404                               /*IsMinMax*/ true, ARMCC::LT);
7405   case ARM::ATOMMAX6432:
7406     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7407                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7408                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7409                               /*IsMinMax*/ true, ARMCC::GE);
7410   case ARM::ATOMUMIN6432:
7411     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7412                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7413                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7414                               /*IsMinMax*/ true, ARMCC::LO);
7415   case ARM::ATOMUMAX6432:
7416     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7417                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7418                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7419                               /*IsMinMax*/ true, ARMCC::HS);
7420
7421   case ARM::tMOVCCr_pseudo: {
7422     // To "insert" a SELECT_CC instruction, we actually have to insert the
7423     // diamond control-flow pattern.  The incoming instruction knows the
7424     // destination vreg to set, the condition code register to branch on, the
7425     // true/false values to select between, and a branch opcode to use.
7426     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7427     MachineFunction::iterator It = BB;
7428     ++It;
7429
7430     //  thisMBB:
7431     //  ...
7432     //   TrueVal = ...
7433     //   cmpTY ccX, r1, r2
7434     //   bCC copy1MBB
7435     //   fallthrough --> copy0MBB
7436     MachineBasicBlock *thisMBB  = BB;
7437     MachineFunction *F = BB->getParent();
7438     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7439     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7440     F->insert(It, copy0MBB);
7441     F->insert(It, sinkMBB);
7442
7443     // Transfer the remainder of BB and its successor edges to sinkMBB.
7444     sinkMBB->splice(sinkMBB->begin(), BB,
7445                     llvm::next(MachineBasicBlock::iterator(MI)),
7446                     BB->end());
7447     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7448
7449     BB->addSuccessor(copy0MBB);
7450     BB->addSuccessor(sinkMBB);
7451
7452     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7453       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7454
7455     //  copy0MBB:
7456     //   %FalseValue = ...
7457     //   # fallthrough to sinkMBB
7458     BB = copy0MBB;
7459
7460     // Update machine-CFG edges
7461     BB->addSuccessor(sinkMBB);
7462
7463     //  sinkMBB:
7464     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7465     //  ...
7466     BB = sinkMBB;
7467     BuildMI(*BB, BB->begin(), dl,
7468             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7469       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7470       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7471
7472     MI->eraseFromParent();   // The pseudo instruction is gone now.
7473     return BB;
7474   }
7475
7476   case ARM::BCCi64:
7477   case ARM::BCCZi64: {
7478     // If there is an unconditional branch to the other successor, remove it.
7479     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
7480
7481     // Compare both parts that make up the double comparison separately for
7482     // equality.
7483     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7484
7485     unsigned LHS1 = MI->getOperand(1).getReg();
7486     unsigned LHS2 = MI->getOperand(2).getReg();
7487     if (RHSisZero) {
7488       AddDefaultPred(BuildMI(BB, dl,
7489                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7490                      .addReg(LHS1).addImm(0));
7491       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7492         .addReg(LHS2).addImm(0)
7493         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7494     } else {
7495       unsigned RHS1 = MI->getOperand(3).getReg();
7496       unsigned RHS2 = MI->getOperand(4).getReg();
7497       AddDefaultPred(BuildMI(BB, dl,
7498                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7499                      .addReg(LHS1).addReg(RHS1));
7500       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7501         .addReg(LHS2).addReg(RHS2)
7502         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7503     }
7504
7505     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7506     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7507     if (MI->getOperand(0).getImm() == ARMCC::NE)
7508       std::swap(destMBB, exitMBB);
7509
7510     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7511       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7512     if (isThumb2)
7513       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7514     else
7515       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7516
7517     MI->eraseFromParent();   // The pseudo instruction is gone now.
7518     return BB;
7519   }
7520
7521   case ARM::Int_eh_sjlj_setjmp:
7522   case ARM::Int_eh_sjlj_setjmp_nofp:
7523   case ARM::tInt_eh_sjlj_setjmp:
7524   case ARM::t2Int_eh_sjlj_setjmp:
7525   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7526     EmitSjLjDispatchBlock(MI, BB);
7527     return BB;
7528
7529   case ARM::ABS:
7530   case ARM::t2ABS: {
7531     // To insert an ABS instruction, we have to insert the
7532     // diamond control-flow pattern.  The incoming instruction knows the
7533     // source vreg to test against 0, the destination vreg to set,
7534     // the condition code register to branch on, the
7535     // true/false values to select between, and a branch opcode to use.
7536     // It transforms
7537     //     V1 = ABS V0
7538     // into
7539     //     V2 = MOVS V0
7540     //     BCC                      (branch to SinkBB if V0 >= 0)
7541     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7542     //     SinkBB: V1 = PHI(V2, V3)
7543     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7544     MachineFunction::iterator BBI = BB;
7545     ++BBI;
7546     MachineFunction *Fn = BB->getParent();
7547     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7548     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7549     Fn->insert(BBI, RSBBB);
7550     Fn->insert(BBI, SinkBB);
7551
7552     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7553     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7554     bool isThumb2 = Subtarget->isThumb2();
7555     MachineRegisterInfo &MRI = Fn->getRegInfo();
7556     // In Thumb mode S must not be specified if source register is the SP or
7557     // PC and if destination register is the SP, so restrict register class
7558     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7559       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7560       (const TargetRegisterClass*)&ARM::GPRRegClass);
7561
7562     // Transfer the remainder of BB and its successor edges to sinkMBB.
7563     SinkBB->splice(SinkBB->begin(), BB,
7564       llvm::next(MachineBasicBlock::iterator(MI)),
7565       BB->end());
7566     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7567
7568     BB->addSuccessor(RSBBB);
7569     BB->addSuccessor(SinkBB);
7570
7571     // fall through to SinkMBB
7572     RSBBB->addSuccessor(SinkBB);
7573
7574     // insert a cmp at the end of BB
7575     AddDefaultPred(BuildMI(BB, dl,
7576                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7577                    .addReg(ABSSrcReg).addImm(0));
7578
7579     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7580     BuildMI(BB, dl,
7581       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7582       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7583
7584     // insert rsbri in RSBBB
7585     // Note: BCC and rsbri will be converted into predicated rsbmi
7586     // by if-conversion pass
7587     BuildMI(*RSBBB, RSBBB->begin(), dl,
7588       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7589       .addReg(ABSSrcReg, RegState::Kill)
7590       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7591
7592     // insert PHI in SinkBB,
7593     // reuse ABSDstReg to not change uses of ABS instruction
7594     BuildMI(*SinkBB, SinkBB->begin(), dl,
7595       TII->get(ARM::PHI), ABSDstReg)
7596       .addReg(NewRsbDstReg).addMBB(RSBBB)
7597       .addReg(ABSSrcReg).addMBB(BB);
7598
7599     // remove ABS instruction
7600     MI->eraseFromParent();
7601
7602     // return last added BB
7603     return SinkBB;
7604   }
7605   case ARM::COPY_STRUCT_BYVAL_I32:
7606     ++NumLoopByVals;
7607     return EmitStructByval(MI, BB);
7608   }
7609 }
7610
7611 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7612                                                       SDNode *Node) const {
7613   if (!MI->hasPostISelHook()) {
7614     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7615            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7616     return;
7617   }
7618
7619   const MCInstrDesc *MCID = &MI->getDesc();
7620   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7621   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7622   // operand is still set to noreg. If needed, set the optional operand's
7623   // register to CPSR, and remove the redundant implicit def.
7624   //
7625   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7626
7627   // Rename pseudo opcodes.
7628   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7629   if (NewOpc) {
7630     const ARMBaseInstrInfo *TII =
7631       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7632     MCID = &TII->get(NewOpc);
7633
7634     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7635            "converted opcode should be the same except for cc_out");
7636
7637     MI->setDesc(*MCID);
7638
7639     // Add the optional cc_out operand
7640     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7641   }
7642   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7643
7644   // Any ARM instruction that sets the 's' bit should specify an optional
7645   // "cc_out" operand in the last operand position.
7646   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7647     assert(!NewOpc && "Optional cc_out operand required");
7648     return;
7649   }
7650   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7651   // since we already have an optional CPSR def.
7652   bool definesCPSR = false;
7653   bool deadCPSR = false;
7654   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7655        i != e; ++i) {
7656     const MachineOperand &MO = MI->getOperand(i);
7657     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7658       definesCPSR = true;
7659       if (MO.isDead())
7660         deadCPSR = true;
7661       MI->RemoveOperand(i);
7662       break;
7663     }
7664   }
7665   if (!definesCPSR) {
7666     assert(!NewOpc && "Optional cc_out operand required");
7667     return;
7668   }
7669   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7670   if (deadCPSR) {
7671     assert(!MI->getOperand(ccOutIdx).getReg() &&
7672            "expect uninitialized optional cc_out operand");
7673     return;
7674   }
7675
7676   // If this instruction was defined with an optional CPSR def and its dag node
7677   // had a live implicit CPSR def, then activate the optional CPSR def.
7678   MachineOperand &MO = MI->getOperand(ccOutIdx);
7679   MO.setReg(ARM::CPSR);
7680   MO.setIsDef(true);
7681 }
7682
7683 //===----------------------------------------------------------------------===//
7684 //                           ARM Optimization Hooks
7685 //===----------------------------------------------------------------------===//
7686
7687 // Helper function that checks if N is a null or all ones constant.
7688 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7689   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7690   if (!C)
7691     return false;
7692   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7693 }
7694
7695 // Return true if N is conditionally 0 or all ones.
7696 // Detects these expressions where cc is an i1 value:
7697 //
7698 //   (select cc 0, y)   [AllOnes=0]
7699 //   (select cc y, 0)   [AllOnes=0]
7700 //   (zext cc)          [AllOnes=0]
7701 //   (sext cc)          [AllOnes=0/1]
7702 //   (select cc -1, y)  [AllOnes=1]
7703 //   (select cc y, -1)  [AllOnes=1]
7704 //
7705 // Invert is set when N is the null/all ones constant when CC is false.
7706 // OtherOp is set to the alternative value of N.
7707 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7708                                        SDValue &CC, bool &Invert,
7709                                        SDValue &OtherOp,
7710                                        SelectionDAG &DAG) {
7711   switch (N->getOpcode()) {
7712   default: return false;
7713   case ISD::SELECT: {
7714     CC = N->getOperand(0);
7715     SDValue N1 = N->getOperand(1);
7716     SDValue N2 = N->getOperand(2);
7717     if (isZeroOrAllOnes(N1, AllOnes)) {
7718       Invert = false;
7719       OtherOp = N2;
7720       return true;
7721     }
7722     if (isZeroOrAllOnes(N2, AllOnes)) {
7723       Invert = true;
7724       OtherOp = N1;
7725       return true;
7726     }
7727     return false;
7728   }
7729   case ISD::ZERO_EXTEND:
7730     // (zext cc) can never be the all ones value.
7731     if (AllOnes)
7732       return false;
7733     // Fall through.
7734   case ISD::SIGN_EXTEND: {
7735     EVT VT = N->getValueType(0);
7736     CC = N->getOperand(0);
7737     if (CC.getValueType() != MVT::i1)
7738       return false;
7739     Invert = !AllOnes;
7740     if (AllOnes)
7741       // When looking for an AllOnes constant, N is an sext, and the 'other'
7742       // value is 0.
7743       OtherOp = DAG.getConstant(0, VT);
7744     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7745       // When looking for a 0 constant, N can be zext or sext.
7746       OtherOp = DAG.getConstant(1, VT);
7747     else
7748       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7749     return true;
7750   }
7751   }
7752 }
7753
7754 // Combine a constant select operand into its use:
7755 //
7756 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7757 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7758 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7759 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7760 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7761 //
7762 // The transform is rejected if the select doesn't have a constant operand that
7763 // is null, or all ones when AllOnes is set.
7764 //
7765 // Also recognize sext/zext from i1:
7766 //
7767 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7768 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7769 //
7770 // These transformations eventually create predicated instructions.
7771 //
7772 // @param N       The node to transform.
7773 // @param Slct    The N operand that is a select.
7774 // @param OtherOp The other N operand (x above).
7775 // @param DCI     Context.
7776 // @param AllOnes Require the select constant to be all ones instead of null.
7777 // @returns The new node, or SDValue() on failure.
7778 static
7779 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7780                             TargetLowering::DAGCombinerInfo &DCI,
7781                             bool AllOnes = false) {
7782   SelectionDAG &DAG = DCI.DAG;
7783   EVT VT = N->getValueType(0);
7784   SDValue NonConstantVal;
7785   SDValue CCOp;
7786   bool SwapSelectOps;
7787   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7788                                   NonConstantVal, DAG))
7789     return SDValue();
7790
7791   // Slct is now know to be the desired identity constant when CC is true.
7792   SDValue TrueVal = OtherOp;
7793   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7794                                  OtherOp, NonConstantVal);
7795   // Unless SwapSelectOps says CC should be false.
7796   if (SwapSelectOps)
7797     std::swap(TrueVal, FalseVal);
7798
7799   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7800                      CCOp, TrueVal, FalseVal);
7801 }
7802
7803 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7804 static
7805 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7806                                        TargetLowering::DAGCombinerInfo &DCI) {
7807   SDValue N0 = N->getOperand(0);
7808   SDValue N1 = N->getOperand(1);
7809   if (N0.getNode()->hasOneUse()) {
7810     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7811     if (Result.getNode())
7812       return Result;
7813   }
7814   if (N1.getNode()->hasOneUse()) {
7815     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7816     if (Result.getNode())
7817       return Result;
7818   }
7819   return SDValue();
7820 }
7821
7822 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7823 // (only after legalization).
7824 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7825                                  TargetLowering::DAGCombinerInfo &DCI,
7826                                  const ARMSubtarget *Subtarget) {
7827
7828   // Only perform optimization if after legalize, and if NEON is available. We
7829   // also expected both operands to be BUILD_VECTORs.
7830   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7831       || N0.getOpcode() != ISD::BUILD_VECTOR
7832       || N1.getOpcode() != ISD::BUILD_VECTOR)
7833     return SDValue();
7834
7835   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7836   EVT VT = N->getValueType(0);
7837   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7838     return SDValue();
7839
7840   // Check that the vector operands are of the right form.
7841   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7842   // operands, where N is the size of the formed vector.
7843   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7844   // index such that we have a pair wise add pattern.
7845
7846   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7847   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7848     return SDValue();
7849   SDValue Vec = N0->getOperand(0)->getOperand(0);
7850   SDNode *V = Vec.getNode();
7851   unsigned nextIndex = 0;
7852
7853   // For each operands to the ADD which are BUILD_VECTORs,
7854   // check to see if each of their operands are an EXTRACT_VECTOR with
7855   // the same vector and appropriate index.
7856   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7857     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7858         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7859
7860       SDValue ExtVec0 = N0->getOperand(i);
7861       SDValue ExtVec1 = N1->getOperand(i);
7862
7863       // First operand is the vector, verify its the same.
7864       if (V != ExtVec0->getOperand(0).getNode() ||
7865           V != ExtVec1->getOperand(0).getNode())
7866         return SDValue();
7867
7868       // Second is the constant, verify its correct.
7869       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7870       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7871
7872       // For the constant, we want to see all the even or all the odd.
7873       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7874           || C1->getZExtValue() != nextIndex+1)
7875         return SDValue();
7876
7877       // Increment index.
7878       nextIndex+=2;
7879     } else
7880       return SDValue();
7881   }
7882
7883   // Create VPADDL node.
7884   SelectionDAG &DAG = DCI.DAG;
7885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7886
7887   // Build operand list.
7888   SmallVector<SDValue, 8> Ops;
7889   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7890                                 TLI.getPointerTy()));
7891
7892   // Input is the vector.
7893   Ops.push_back(Vec);
7894
7895   // Get widened type and narrowed type.
7896   MVT widenType;
7897   unsigned numElem = VT.getVectorNumElements();
7898   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
7899     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7900     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7901     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7902     default:
7903       llvm_unreachable("Invalid vector element type for padd optimization.");
7904   }
7905
7906   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
7907                             widenType, &Ops[0], Ops.size());
7908   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
7909 }
7910
7911 static SDValue findMUL_LOHI(SDValue V) {
7912   if (V->getOpcode() == ISD::UMUL_LOHI ||
7913       V->getOpcode() == ISD::SMUL_LOHI)
7914     return V;
7915   return SDValue();
7916 }
7917
7918 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7919                                      TargetLowering::DAGCombinerInfo &DCI,
7920                                      const ARMSubtarget *Subtarget) {
7921
7922   if (Subtarget->isThumb1Only()) return SDValue();
7923
7924   // Only perform the checks after legalize when the pattern is available.
7925   if (DCI.isBeforeLegalize()) return SDValue();
7926
7927   // Look for multiply add opportunities.
7928   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7929   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7930   // a glue link from the first add to the second add.
7931   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7932   // a S/UMLAL instruction.
7933   //          loAdd   UMUL_LOHI
7934   //            \    / :lo    \ :hi
7935   //             \  /          \          [no multiline comment]
7936   //              ADDC         |  hiAdd
7937   //                 \ :glue  /  /
7938   //                  \      /  /
7939   //                    ADDE
7940   //
7941   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7942   SDValue AddcOp0 = AddcNode->getOperand(0);
7943   SDValue AddcOp1 = AddcNode->getOperand(1);
7944
7945   // Check if the two operands are from the same mul_lohi node.
7946   if (AddcOp0.getNode() == AddcOp1.getNode())
7947     return SDValue();
7948
7949   assert(AddcNode->getNumValues() == 2 &&
7950          AddcNode->getValueType(0) == MVT::i32 &&
7951          "Expect ADDC with two result values. First: i32");
7952
7953   // Check that we have a glued ADDC node.
7954   if (AddcNode->getValueType(1) != MVT::Glue)
7955     return SDValue();
7956
7957   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7958   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7959       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7960       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7961       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7962     return SDValue();
7963
7964   // Look for the glued ADDE.
7965   SDNode* AddeNode = AddcNode->getGluedUser();
7966   if (AddeNode == NULL)
7967     return SDValue();
7968
7969   // Make sure it is really an ADDE.
7970   if (AddeNode->getOpcode() != ISD::ADDE)
7971     return SDValue();
7972
7973   assert(AddeNode->getNumOperands() == 3 &&
7974          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7975          "ADDE node has the wrong inputs");
7976
7977   // Check for the triangle shape.
7978   SDValue AddeOp0 = AddeNode->getOperand(0);
7979   SDValue AddeOp1 = AddeNode->getOperand(1);
7980
7981   // Make sure that the ADDE operands are not coming from the same node.
7982   if (AddeOp0.getNode() == AddeOp1.getNode())
7983     return SDValue();
7984
7985   // Find the MUL_LOHI node walking up ADDE's operands.
7986   bool IsLeftOperandMUL = false;
7987   SDValue MULOp = findMUL_LOHI(AddeOp0);
7988   if (MULOp == SDValue())
7989    MULOp = findMUL_LOHI(AddeOp1);
7990   else
7991     IsLeftOperandMUL = true;
7992   if (MULOp == SDValue())
7993      return SDValue();
7994
7995   // Figure out the right opcode.
7996   unsigned Opc = MULOp->getOpcode();
7997   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7998
7999   // Figure out the high and low input values to the MLAL node.
8000   SDValue* HiMul = &MULOp;
8001   SDValue* HiAdd = NULL;
8002   SDValue* LoMul = NULL;
8003   SDValue* LowAdd = NULL;
8004
8005   if (IsLeftOperandMUL)
8006     HiAdd = &AddeOp1;
8007   else
8008     HiAdd = &AddeOp0;
8009
8010
8011   if (AddcOp0->getOpcode() == Opc) {
8012     LoMul = &AddcOp0;
8013     LowAdd = &AddcOp1;
8014   }
8015   if (AddcOp1->getOpcode() == Opc) {
8016     LoMul = &AddcOp1;
8017     LowAdd = &AddcOp0;
8018   }
8019
8020   if (LoMul == NULL)
8021     return SDValue();
8022
8023   if (LoMul->getNode() != HiMul->getNode())
8024     return SDValue();
8025
8026   // Create the merged node.
8027   SelectionDAG &DAG = DCI.DAG;
8028
8029   // Build operand list.
8030   SmallVector<SDValue, 8> Ops;
8031   Ops.push_back(LoMul->getOperand(0));
8032   Ops.push_back(LoMul->getOperand(1));
8033   Ops.push_back(*LowAdd);
8034   Ops.push_back(*HiAdd);
8035
8036   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8037                                  DAG.getVTList(MVT::i32, MVT::i32),
8038                                  &Ops[0], Ops.size());
8039
8040   // Replace the ADDs' nodes uses by the MLA node's values.
8041   SDValue HiMLALResult(MLALNode.getNode(), 1);
8042   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8043
8044   SDValue LoMLALResult(MLALNode.getNode(), 0);
8045   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8046
8047   // Return original node to notify the driver to stop replacing.
8048   SDValue resNode(AddcNode, 0);
8049   return resNode;
8050 }
8051
8052 /// PerformADDCCombine - Target-specific dag combine transform from
8053 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8054 static SDValue PerformADDCCombine(SDNode *N,
8055                                  TargetLowering::DAGCombinerInfo &DCI,
8056                                  const ARMSubtarget *Subtarget) {
8057
8058   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8059
8060 }
8061
8062 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8063 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8064 /// called with the default operands, and if that fails, with commuted
8065 /// operands.
8066 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8067                                           TargetLowering::DAGCombinerInfo &DCI,
8068                                           const ARMSubtarget *Subtarget){
8069
8070   // Attempt to create vpaddl for this add.
8071   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8072   if (Result.getNode())
8073     return Result;
8074
8075   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8076   if (N0.getNode()->hasOneUse()) {
8077     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8078     if (Result.getNode()) return Result;
8079   }
8080   return SDValue();
8081 }
8082
8083 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8084 ///
8085 static SDValue PerformADDCombine(SDNode *N,
8086                                  TargetLowering::DAGCombinerInfo &DCI,
8087                                  const ARMSubtarget *Subtarget) {
8088   SDValue N0 = N->getOperand(0);
8089   SDValue N1 = N->getOperand(1);
8090
8091   // First try with the default operand order.
8092   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8093   if (Result.getNode())
8094     return Result;
8095
8096   // If that didn't work, try again with the operands commuted.
8097   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8098 }
8099
8100 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8101 ///
8102 static SDValue PerformSUBCombine(SDNode *N,
8103                                  TargetLowering::DAGCombinerInfo &DCI) {
8104   SDValue N0 = N->getOperand(0);
8105   SDValue N1 = N->getOperand(1);
8106
8107   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8108   if (N1.getNode()->hasOneUse()) {
8109     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8110     if (Result.getNode()) return Result;
8111   }
8112
8113   return SDValue();
8114 }
8115
8116 /// PerformVMULCombine
8117 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8118 /// special multiplier accumulator forwarding.
8119 ///   vmul d3, d0, d2
8120 ///   vmla d3, d1, d2
8121 /// is faster than
8122 ///   vadd d3, d0, d1
8123 ///   vmul d3, d3, d2
8124 static SDValue PerformVMULCombine(SDNode *N,
8125                                   TargetLowering::DAGCombinerInfo &DCI,
8126                                   const ARMSubtarget *Subtarget) {
8127   if (!Subtarget->hasVMLxForwarding())
8128     return SDValue();
8129
8130   SelectionDAG &DAG = DCI.DAG;
8131   SDValue N0 = N->getOperand(0);
8132   SDValue N1 = N->getOperand(1);
8133   unsigned Opcode = N0.getOpcode();
8134   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8135       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8136     Opcode = N1.getOpcode();
8137     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8138         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8139       return SDValue();
8140     std::swap(N0, N1);
8141   }
8142
8143   EVT VT = N->getValueType(0);
8144   SDLoc DL(N);
8145   SDValue N00 = N0->getOperand(0);
8146   SDValue N01 = N0->getOperand(1);
8147   return DAG.getNode(Opcode, DL, VT,
8148                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8149                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8150 }
8151
8152 static SDValue PerformMULCombine(SDNode *N,
8153                                  TargetLowering::DAGCombinerInfo &DCI,
8154                                  const ARMSubtarget *Subtarget) {
8155   SelectionDAG &DAG = DCI.DAG;
8156
8157   if (Subtarget->isThumb1Only())
8158     return SDValue();
8159
8160   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8161     return SDValue();
8162
8163   EVT VT = N->getValueType(0);
8164   if (VT.is64BitVector() || VT.is128BitVector())
8165     return PerformVMULCombine(N, DCI, Subtarget);
8166   if (VT != MVT::i32)
8167     return SDValue();
8168
8169   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8170   if (!C)
8171     return SDValue();
8172
8173   int64_t MulAmt = C->getSExtValue();
8174   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8175
8176   ShiftAmt = ShiftAmt & (32 - 1);
8177   SDValue V = N->getOperand(0);
8178   SDLoc DL(N);
8179
8180   SDValue Res;
8181   MulAmt >>= ShiftAmt;
8182
8183   if (MulAmt >= 0) {
8184     if (isPowerOf2_32(MulAmt - 1)) {
8185       // (mul x, 2^N + 1) => (add (shl x, N), x)
8186       Res = DAG.getNode(ISD::ADD, DL, VT,
8187                         V,
8188                         DAG.getNode(ISD::SHL, DL, VT,
8189                                     V,
8190                                     DAG.getConstant(Log2_32(MulAmt - 1),
8191                                                     MVT::i32)));
8192     } else if (isPowerOf2_32(MulAmt + 1)) {
8193       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8194       Res = DAG.getNode(ISD::SUB, DL, VT,
8195                         DAG.getNode(ISD::SHL, DL, VT,
8196                                     V,
8197                                     DAG.getConstant(Log2_32(MulAmt + 1),
8198                                                     MVT::i32)),
8199                         V);
8200     } else
8201       return SDValue();
8202   } else {
8203     uint64_t MulAmtAbs = -MulAmt;
8204     if (isPowerOf2_32(MulAmtAbs + 1)) {
8205       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8206       Res = DAG.getNode(ISD::SUB, DL, VT,
8207                         V,
8208                         DAG.getNode(ISD::SHL, DL, VT,
8209                                     V,
8210                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8211                                                     MVT::i32)));
8212     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8213       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8214       Res = DAG.getNode(ISD::ADD, DL, VT,
8215                         V,
8216                         DAG.getNode(ISD::SHL, DL, VT,
8217                                     V,
8218                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8219                                                     MVT::i32)));
8220       Res = DAG.getNode(ISD::SUB, DL, VT,
8221                         DAG.getConstant(0, MVT::i32),Res);
8222
8223     } else
8224       return SDValue();
8225   }
8226
8227   if (ShiftAmt != 0)
8228     Res = DAG.getNode(ISD::SHL, DL, VT,
8229                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8230
8231   // Do not add new nodes to DAG combiner worklist.
8232   DCI.CombineTo(N, Res, false);
8233   return SDValue();
8234 }
8235
8236 static SDValue PerformANDCombine(SDNode *N,
8237                                  TargetLowering::DAGCombinerInfo &DCI,
8238                                  const ARMSubtarget *Subtarget) {
8239
8240   // Attempt to use immediate-form VBIC
8241   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8242   SDLoc dl(N);
8243   EVT VT = N->getValueType(0);
8244   SelectionDAG &DAG = DCI.DAG;
8245
8246   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8247     return SDValue();
8248
8249   APInt SplatBits, SplatUndef;
8250   unsigned SplatBitSize;
8251   bool HasAnyUndefs;
8252   if (BVN &&
8253       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8254     if (SplatBitSize <= 64) {
8255       EVT VbicVT;
8256       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8257                                       SplatUndef.getZExtValue(), SplatBitSize,
8258                                       DAG, VbicVT, VT.is128BitVector(),
8259                                       OtherModImm);
8260       if (Val.getNode()) {
8261         SDValue Input =
8262           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8263         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8264         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8265       }
8266     }
8267   }
8268
8269   if (!Subtarget->isThumb1Only()) {
8270     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8271     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8272     if (Result.getNode())
8273       return Result;
8274   }
8275
8276   return SDValue();
8277 }
8278
8279 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8280 static SDValue PerformORCombine(SDNode *N,
8281                                 TargetLowering::DAGCombinerInfo &DCI,
8282                                 const ARMSubtarget *Subtarget) {
8283   // Attempt to use immediate-form VORR
8284   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8285   SDLoc dl(N);
8286   EVT VT = N->getValueType(0);
8287   SelectionDAG &DAG = DCI.DAG;
8288
8289   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8290     return SDValue();
8291
8292   APInt SplatBits, SplatUndef;
8293   unsigned SplatBitSize;
8294   bool HasAnyUndefs;
8295   if (BVN && Subtarget->hasNEON() &&
8296       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8297     if (SplatBitSize <= 64) {
8298       EVT VorrVT;
8299       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8300                                       SplatUndef.getZExtValue(), SplatBitSize,
8301                                       DAG, VorrVT, VT.is128BitVector(),
8302                                       OtherModImm);
8303       if (Val.getNode()) {
8304         SDValue Input =
8305           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8306         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8307         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8308       }
8309     }
8310   }
8311
8312   if (!Subtarget->isThumb1Only()) {
8313     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8314     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8315     if (Result.getNode())
8316       return Result;
8317   }
8318
8319   // The code below optimizes (or (and X, Y), Z).
8320   // The AND operand needs to have a single user to make these optimizations
8321   // profitable.
8322   SDValue N0 = N->getOperand(0);
8323   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8324     return SDValue();
8325   SDValue N1 = N->getOperand(1);
8326
8327   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8328   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8329       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8330     APInt SplatUndef;
8331     unsigned SplatBitSize;
8332     bool HasAnyUndefs;
8333
8334     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8335     APInt SplatBits0;
8336     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8337                                   HasAnyUndefs) && !HasAnyUndefs) {
8338       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8339       APInt SplatBits1;
8340       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8341                                     HasAnyUndefs) && !HasAnyUndefs &&
8342           SplatBits0 == ~SplatBits1) {
8343         // Canonicalize the vector type to make instruction selection simpler.
8344         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8345         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8346                                      N0->getOperand(1), N0->getOperand(0),
8347                                      N1->getOperand(0));
8348         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8349       }
8350     }
8351   }
8352
8353   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8354   // reasonable.
8355
8356   // BFI is only available on V6T2+
8357   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8358     return SDValue();
8359
8360   SDLoc DL(N);
8361   // 1) or (and A, mask), val => ARMbfi A, val, mask
8362   //      iff (val & mask) == val
8363   //
8364   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8365   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8366   //          && mask == ~mask2
8367   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8368   //          && ~mask == mask2
8369   //  (i.e., copy a bitfield value into another bitfield of the same width)
8370
8371   if (VT != MVT::i32)
8372     return SDValue();
8373
8374   SDValue N00 = N0.getOperand(0);
8375
8376   // The value and the mask need to be constants so we can verify this is
8377   // actually a bitfield set. If the mask is 0xffff, we can do better
8378   // via a movt instruction, so don't use BFI in that case.
8379   SDValue MaskOp = N0.getOperand(1);
8380   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8381   if (!MaskC)
8382     return SDValue();
8383   unsigned Mask = MaskC->getZExtValue();
8384   if (Mask == 0xffff)
8385     return SDValue();
8386   SDValue Res;
8387   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8388   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8389   if (N1C) {
8390     unsigned Val = N1C->getZExtValue();
8391     if ((Val & ~Mask) != Val)
8392       return SDValue();
8393
8394     if (ARM::isBitFieldInvertedMask(Mask)) {
8395       Val >>= countTrailingZeros(~Mask);
8396
8397       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8398                         DAG.getConstant(Val, MVT::i32),
8399                         DAG.getConstant(Mask, MVT::i32));
8400
8401       // Do not add new nodes to DAG combiner worklist.
8402       DCI.CombineTo(N, Res, false);
8403       return SDValue();
8404     }
8405   } else if (N1.getOpcode() == ISD::AND) {
8406     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8407     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8408     if (!N11C)
8409       return SDValue();
8410     unsigned Mask2 = N11C->getZExtValue();
8411
8412     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8413     // as is to match.
8414     if (ARM::isBitFieldInvertedMask(Mask) &&
8415         (Mask == ~Mask2)) {
8416       // The pack halfword instruction works better for masks that fit it,
8417       // so use that when it's available.
8418       if (Subtarget->hasT2ExtractPack() &&
8419           (Mask == 0xffff || Mask == 0xffff0000))
8420         return SDValue();
8421       // 2a
8422       unsigned amt = countTrailingZeros(Mask2);
8423       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8424                         DAG.getConstant(amt, MVT::i32));
8425       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8426                         DAG.getConstant(Mask, MVT::i32));
8427       // Do not add new nodes to DAG combiner worklist.
8428       DCI.CombineTo(N, Res, false);
8429       return SDValue();
8430     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8431                (~Mask == Mask2)) {
8432       // The pack halfword instruction works better for masks that fit it,
8433       // so use that when it's available.
8434       if (Subtarget->hasT2ExtractPack() &&
8435           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8436         return SDValue();
8437       // 2b
8438       unsigned lsb = countTrailingZeros(Mask);
8439       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8440                         DAG.getConstant(lsb, MVT::i32));
8441       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8442                         DAG.getConstant(Mask2, MVT::i32));
8443       // Do not add new nodes to DAG combiner worklist.
8444       DCI.CombineTo(N, Res, false);
8445       return SDValue();
8446     }
8447   }
8448
8449   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8450       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8451       ARM::isBitFieldInvertedMask(~Mask)) {
8452     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8453     // where lsb(mask) == #shamt and masked bits of B are known zero.
8454     SDValue ShAmt = N00.getOperand(1);
8455     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8456     unsigned LSB = countTrailingZeros(Mask);
8457     if (ShAmtC != LSB)
8458       return SDValue();
8459
8460     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8461                       DAG.getConstant(~Mask, MVT::i32));
8462
8463     // Do not add new nodes to DAG combiner worklist.
8464     DCI.CombineTo(N, Res, false);
8465   }
8466
8467   return SDValue();
8468 }
8469
8470 static SDValue PerformXORCombine(SDNode *N,
8471                                  TargetLowering::DAGCombinerInfo &DCI,
8472                                  const ARMSubtarget *Subtarget) {
8473   EVT VT = N->getValueType(0);
8474   SelectionDAG &DAG = DCI.DAG;
8475
8476   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8477     return SDValue();
8478
8479   if (!Subtarget->isThumb1Only()) {
8480     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8481     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8482     if (Result.getNode())
8483       return Result;
8484   }
8485
8486   return SDValue();
8487 }
8488
8489 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8490 /// the bits being cleared by the AND are not demanded by the BFI.
8491 static SDValue PerformBFICombine(SDNode *N,
8492                                  TargetLowering::DAGCombinerInfo &DCI) {
8493   SDValue N1 = N->getOperand(1);
8494   if (N1.getOpcode() == ISD::AND) {
8495     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8496     if (!N11C)
8497       return SDValue();
8498     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8499     unsigned LSB = countTrailingZeros(~InvMask);
8500     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8501     unsigned Mask = (1 << Width)-1;
8502     unsigned Mask2 = N11C->getZExtValue();
8503     if ((Mask & (~Mask2)) == 0)
8504       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8505                              N->getOperand(0), N1.getOperand(0),
8506                              N->getOperand(2));
8507   }
8508   return SDValue();
8509 }
8510
8511 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8512 /// ARMISD::VMOVRRD.
8513 static SDValue PerformVMOVRRDCombine(SDNode *N,
8514                                      TargetLowering::DAGCombinerInfo &DCI) {
8515   // vmovrrd(vmovdrr x, y) -> x,y
8516   SDValue InDouble = N->getOperand(0);
8517   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8518     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8519
8520   // vmovrrd(load f64) -> (load i32), (load i32)
8521   SDNode *InNode = InDouble.getNode();
8522   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8523       InNode->getValueType(0) == MVT::f64 &&
8524       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8525       !cast<LoadSDNode>(InNode)->isVolatile()) {
8526     // TODO: Should this be done for non-FrameIndex operands?
8527     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8528
8529     SelectionDAG &DAG = DCI.DAG;
8530     SDLoc DL(LD);
8531     SDValue BasePtr = LD->getBasePtr();
8532     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8533                                  LD->getPointerInfo(), LD->isVolatile(),
8534                                  LD->isNonTemporal(), LD->isInvariant(),
8535                                  LD->getAlignment());
8536
8537     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8538                                     DAG.getConstant(4, MVT::i32));
8539     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8540                                  LD->getPointerInfo(), LD->isVolatile(),
8541                                  LD->isNonTemporal(), LD->isInvariant(),
8542                                  std::min(4U, LD->getAlignment() / 2));
8543
8544     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8545     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8546     DCI.RemoveFromWorklist(LD);
8547     DAG.DeleteNode(LD);
8548     return Result;
8549   }
8550
8551   return SDValue();
8552 }
8553
8554 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8555 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8556 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8557   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8558   SDValue Op0 = N->getOperand(0);
8559   SDValue Op1 = N->getOperand(1);
8560   if (Op0.getOpcode() == ISD::BITCAST)
8561     Op0 = Op0.getOperand(0);
8562   if (Op1.getOpcode() == ISD::BITCAST)
8563     Op1 = Op1.getOperand(0);
8564   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8565       Op0.getNode() == Op1.getNode() &&
8566       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8567     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8568                        N->getValueType(0), Op0.getOperand(0));
8569   return SDValue();
8570 }
8571
8572 /// PerformSTORECombine - Target-specific dag combine xforms for
8573 /// ISD::STORE.
8574 static SDValue PerformSTORECombine(SDNode *N,
8575                                    TargetLowering::DAGCombinerInfo &DCI) {
8576   StoreSDNode *St = cast<StoreSDNode>(N);
8577   if (St->isVolatile())
8578     return SDValue();
8579
8580   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8581   // pack all of the elements in one place.  Next, store to memory in fewer
8582   // chunks.
8583   SDValue StVal = St->getValue();
8584   EVT VT = StVal.getValueType();
8585   if (St->isTruncatingStore() && VT.isVector()) {
8586     SelectionDAG &DAG = DCI.DAG;
8587     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8588     EVT StVT = St->getMemoryVT();
8589     unsigned NumElems = VT.getVectorNumElements();
8590     assert(StVT != VT && "Cannot truncate to the same type");
8591     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8592     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8593
8594     // From, To sizes and ElemCount must be pow of two
8595     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8596
8597     // We are going to use the original vector elt for storing.
8598     // Accumulated smaller vector elements must be a multiple of the store size.
8599     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8600
8601     unsigned SizeRatio  = FromEltSz / ToEltSz;
8602     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8603
8604     // Create a type on which we perform the shuffle.
8605     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8606                                      NumElems*SizeRatio);
8607     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8608
8609     SDLoc DL(St);
8610     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8611     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8612     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8613
8614     // Can't shuffle using an illegal type.
8615     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8616
8617     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8618                                 DAG.getUNDEF(WideVec.getValueType()),
8619                                 ShuffleVec.data());
8620     // At this point all of the data is stored at the bottom of the
8621     // register. We now need to save it to mem.
8622
8623     // Find the largest store unit
8624     MVT StoreType = MVT::i8;
8625     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8626          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8627       MVT Tp = (MVT::SimpleValueType)tp;
8628       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8629         StoreType = Tp;
8630     }
8631     // Didn't find a legal store type.
8632     if (!TLI.isTypeLegal(StoreType))
8633       return SDValue();
8634
8635     // Bitcast the original vector into a vector of store-size units
8636     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8637             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8638     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8639     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8640     SmallVector<SDValue, 8> Chains;
8641     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8642                                         TLI.getPointerTy());
8643     SDValue BasePtr = St->getBasePtr();
8644
8645     // Perform one or more big stores into memory.
8646     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8647     for (unsigned I = 0; I < E; I++) {
8648       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8649                                    StoreType, ShuffWide,
8650                                    DAG.getIntPtrConstant(I));
8651       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8652                                 St->getPointerInfo(), St->isVolatile(),
8653                                 St->isNonTemporal(), St->getAlignment());
8654       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8655                             Increment);
8656       Chains.push_back(Ch);
8657     }
8658     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
8659                        Chains.size());
8660   }
8661
8662   if (!ISD::isNormalStore(St))
8663     return SDValue();
8664
8665   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8666   // ARM stores of arguments in the same cache line.
8667   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8668       StVal.getNode()->hasOneUse()) {
8669     SelectionDAG  &DAG = DCI.DAG;
8670     SDLoc DL(St);
8671     SDValue BasePtr = St->getBasePtr();
8672     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8673                                   StVal.getNode()->getOperand(0), BasePtr,
8674                                   St->getPointerInfo(), St->isVolatile(),
8675                                   St->isNonTemporal(), St->getAlignment());
8676
8677     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8678                                     DAG.getConstant(4, MVT::i32));
8679     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8680                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8681                         St->isNonTemporal(),
8682                         std::min(4U, St->getAlignment() / 2));
8683   }
8684
8685   if (StVal.getValueType() != MVT::i64 ||
8686       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8687     return SDValue();
8688
8689   // Bitcast an i64 store extracted from a vector to f64.
8690   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8691   SelectionDAG &DAG = DCI.DAG;
8692   SDLoc dl(StVal);
8693   SDValue IntVec = StVal.getOperand(0);
8694   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8695                                  IntVec.getValueType().getVectorNumElements());
8696   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8697   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8698                                Vec, StVal.getOperand(1));
8699   dl = SDLoc(N);
8700   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8701   // Make the DAGCombiner fold the bitcasts.
8702   DCI.AddToWorklist(Vec.getNode());
8703   DCI.AddToWorklist(ExtElt.getNode());
8704   DCI.AddToWorklist(V.getNode());
8705   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8706                       St->getPointerInfo(), St->isVolatile(),
8707                       St->isNonTemporal(), St->getAlignment(),
8708                       St->getTBAAInfo());
8709 }
8710
8711 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8712 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8713 /// i64 vector to have f64 elements, since the value can then be loaded
8714 /// directly into a VFP register.
8715 static bool hasNormalLoadOperand(SDNode *N) {
8716   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8717   for (unsigned i = 0; i < NumElts; ++i) {
8718     SDNode *Elt = N->getOperand(i).getNode();
8719     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8720       return true;
8721   }
8722   return false;
8723 }
8724
8725 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8726 /// ISD::BUILD_VECTOR.
8727 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8728                                           TargetLowering::DAGCombinerInfo &DCI){
8729   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8730   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8731   // into a pair of GPRs, which is fine when the value is used as a scalar,
8732   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8733   SelectionDAG &DAG = DCI.DAG;
8734   if (N->getNumOperands() == 2) {
8735     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8736     if (RV.getNode())
8737       return RV;
8738   }
8739
8740   // Load i64 elements as f64 values so that type legalization does not split
8741   // them up into i32 values.
8742   EVT VT = N->getValueType(0);
8743   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8744     return SDValue();
8745   SDLoc dl(N);
8746   SmallVector<SDValue, 8> Ops;
8747   unsigned NumElts = VT.getVectorNumElements();
8748   for (unsigned i = 0; i < NumElts; ++i) {
8749     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8750     Ops.push_back(V);
8751     // Make the DAGCombiner fold the bitcast.
8752     DCI.AddToWorklist(V.getNode());
8753   }
8754   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8755   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
8756   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8757 }
8758
8759 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8760 /// ISD::INSERT_VECTOR_ELT.
8761 static SDValue PerformInsertEltCombine(SDNode *N,
8762                                        TargetLowering::DAGCombinerInfo &DCI) {
8763   // Bitcast an i64 load inserted into a vector to f64.
8764   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8765   EVT VT = N->getValueType(0);
8766   SDNode *Elt = N->getOperand(1).getNode();
8767   if (VT.getVectorElementType() != MVT::i64 ||
8768       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8769     return SDValue();
8770
8771   SelectionDAG &DAG = DCI.DAG;
8772   SDLoc dl(N);
8773   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8774                                  VT.getVectorNumElements());
8775   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8776   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8777   // Make the DAGCombiner fold the bitcasts.
8778   DCI.AddToWorklist(Vec.getNode());
8779   DCI.AddToWorklist(V.getNode());
8780   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8781                                Vec, V, N->getOperand(2));
8782   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8783 }
8784
8785 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8786 /// ISD::VECTOR_SHUFFLE.
8787 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8788   // The LLVM shufflevector instruction does not require the shuffle mask
8789   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8790   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8791   // operands do not match the mask length, they are extended by concatenating
8792   // them with undef vectors.  That is probably the right thing for other
8793   // targets, but for NEON it is better to concatenate two double-register
8794   // size vector operands into a single quad-register size vector.  Do that
8795   // transformation here:
8796   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8797   //   shuffle(concat(v1, v2), undef)
8798   SDValue Op0 = N->getOperand(0);
8799   SDValue Op1 = N->getOperand(1);
8800   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8801       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8802       Op0.getNumOperands() != 2 ||
8803       Op1.getNumOperands() != 2)
8804     return SDValue();
8805   SDValue Concat0Op1 = Op0.getOperand(1);
8806   SDValue Concat1Op1 = Op1.getOperand(1);
8807   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8808       Concat1Op1.getOpcode() != ISD::UNDEF)
8809     return SDValue();
8810   // Skip the transformation if any of the types are illegal.
8811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8812   EVT VT = N->getValueType(0);
8813   if (!TLI.isTypeLegal(VT) ||
8814       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8815       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8816     return SDValue();
8817
8818   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8819                                   Op0.getOperand(0), Op1.getOperand(0));
8820   // Translate the shuffle mask.
8821   SmallVector<int, 16> NewMask;
8822   unsigned NumElts = VT.getVectorNumElements();
8823   unsigned HalfElts = NumElts/2;
8824   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8825   for (unsigned n = 0; n < NumElts; ++n) {
8826     int MaskElt = SVN->getMaskElt(n);
8827     int NewElt = -1;
8828     if (MaskElt < (int)HalfElts)
8829       NewElt = MaskElt;
8830     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8831       NewElt = HalfElts + MaskElt - NumElts;
8832     NewMask.push_back(NewElt);
8833   }
8834   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8835                               DAG.getUNDEF(VT), NewMask.data());
8836 }
8837
8838 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8839 /// NEON load/store intrinsics to merge base address updates.
8840 static SDValue CombineBaseUpdate(SDNode *N,
8841                                  TargetLowering::DAGCombinerInfo &DCI) {
8842   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8843     return SDValue();
8844
8845   SelectionDAG &DAG = DCI.DAG;
8846   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8847                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8848   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8849   SDValue Addr = N->getOperand(AddrOpIdx);
8850
8851   // Search for a use of the address operand that is an increment.
8852   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8853          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8854     SDNode *User = *UI;
8855     if (User->getOpcode() != ISD::ADD ||
8856         UI.getUse().getResNo() != Addr.getResNo())
8857       continue;
8858
8859     // Check that the add is independent of the load/store.  Otherwise, folding
8860     // it would create a cycle.
8861     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8862       continue;
8863
8864     // Find the new opcode for the updating load/store.
8865     bool isLoad = true;
8866     bool isLaneOp = false;
8867     unsigned NewOpc = 0;
8868     unsigned NumVecs = 0;
8869     if (isIntrinsic) {
8870       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8871       switch (IntNo) {
8872       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8873       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8874         NumVecs = 1; break;
8875       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8876         NumVecs = 2; break;
8877       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8878         NumVecs = 3; break;
8879       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8880         NumVecs = 4; break;
8881       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8882         NumVecs = 2; isLaneOp = true; break;
8883       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8884         NumVecs = 3; isLaneOp = true; break;
8885       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8886         NumVecs = 4; isLaneOp = true; break;
8887       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8888         NumVecs = 1; isLoad = false; break;
8889       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8890         NumVecs = 2; isLoad = false; break;
8891       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8892         NumVecs = 3; isLoad = false; break;
8893       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8894         NumVecs = 4; isLoad = false; break;
8895       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8896         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8897       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8898         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8899       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8900         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8901       }
8902     } else {
8903       isLaneOp = true;
8904       switch (N->getOpcode()) {
8905       default: llvm_unreachable("unexpected opcode for Neon base update");
8906       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8907       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8908       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8909       }
8910     }
8911
8912     // Find the size of memory referenced by the load/store.
8913     EVT VecTy;
8914     if (isLoad)
8915       VecTy = N->getValueType(0);
8916     else
8917       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8918     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8919     if (isLaneOp)
8920       NumBytes /= VecTy.getVectorNumElements();
8921
8922     // If the increment is a constant, it must match the memory ref size.
8923     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8924     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8925       uint64_t IncVal = CInc->getZExtValue();
8926       if (IncVal != NumBytes)
8927         continue;
8928     } else if (NumBytes >= 3 * 16) {
8929       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8930       // separate instructions that make it harder to use a non-constant update.
8931       continue;
8932     }
8933
8934     // Create the new updating load/store node.
8935     EVT Tys[6];
8936     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8937     unsigned n;
8938     for (n = 0; n < NumResultVecs; ++n)
8939       Tys[n] = VecTy;
8940     Tys[n++] = MVT::i32;
8941     Tys[n] = MVT::Other;
8942     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
8943     SmallVector<SDValue, 8> Ops;
8944     Ops.push_back(N->getOperand(0)); // incoming chain
8945     Ops.push_back(N->getOperand(AddrOpIdx));
8946     Ops.push_back(Inc);
8947     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8948       Ops.push_back(N->getOperand(i));
8949     }
8950     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8951     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8952                                            Ops.data(), Ops.size(),
8953                                            MemInt->getMemoryVT(),
8954                                            MemInt->getMemOperand());
8955
8956     // Update the uses.
8957     std::vector<SDValue> NewResults;
8958     for (unsigned i = 0; i < NumResultVecs; ++i) {
8959       NewResults.push_back(SDValue(UpdN.getNode(), i));
8960     }
8961     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8962     DCI.CombineTo(N, NewResults);
8963     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8964
8965     break;
8966   }
8967   return SDValue();
8968 }
8969
8970 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8971 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8972 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8973 /// return true.
8974 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8975   SelectionDAG &DAG = DCI.DAG;
8976   EVT VT = N->getValueType(0);
8977   // vldN-dup instructions only support 64-bit vectors for N > 1.
8978   if (!VT.is64BitVector())
8979     return false;
8980
8981   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8982   SDNode *VLD = N->getOperand(0).getNode();
8983   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8984     return false;
8985   unsigned NumVecs = 0;
8986   unsigned NewOpc = 0;
8987   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8988   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8989     NumVecs = 2;
8990     NewOpc = ARMISD::VLD2DUP;
8991   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8992     NumVecs = 3;
8993     NewOpc = ARMISD::VLD3DUP;
8994   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8995     NumVecs = 4;
8996     NewOpc = ARMISD::VLD4DUP;
8997   } else {
8998     return false;
8999   }
9000
9001   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9002   // numbers match the load.
9003   unsigned VLDLaneNo =
9004     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9005   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9006        UI != UE; ++UI) {
9007     // Ignore uses of the chain result.
9008     if (UI.getUse().getResNo() == NumVecs)
9009       continue;
9010     SDNode *User = *UI;
9011     if (User->getOpcode() != ARMISD::VDUPLANE ||
9012         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9013       return false;
9014   }
9015
9016   // Create the vldN-dup node.
9017   EVT Tys[5];
9018   unsigned n;
9019   for (n = 0; n < NumVecs; ++n)
9020     Tys[n] = VT;
9021   Tys[n] = MVT::Other;
9022   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9023   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9024   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9025   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9026                                            Ops, 2, VLDMemInt->getMemoryVT(),
9027                                            VLDMemInt->getMemOperand());
9028
9029   // Update the uses.
9030   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9031        UI != UE; ++UI) {
9032     unsigned ResNo = UI.getUse().getResNo();
9033     // Ignore uses of the chain result.
9034     if (ResNo == NumVecs)
9035       continue;
9036     SDNode *User = *UI;
9037     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9038   }
9039
9040   // Now the vldN-lane intrinsic is dead except for its chain result.
9041   // Update uses of the chain.
9042   std::vector<SDValue> VLDDupResults;
9043   for (unsigned n = 0; n < NumVecs; ++n)
9044     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9045   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9046   DCI.CombineTo(VLD, VLDDupResults);
9047
9048   return true;
9049 }
9050
9051 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9052 /// ARMISD::VDUPLANE.
9053 static SDValue PerformVDUPLANECombine(SDNode *N,
9054                                       TargetLowering::DAGCombinerInfo &DCI) {
9055   SDValue Op = N->getOperand(0);
9056
9057   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9058   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9059   if (CombineVLDDUP(N, DCI))
9060     return SDValue(N, 0);
9061
9062   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9063   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9064   while (Op.getOpcode() == ISD::BITCAST)
9065     Op = Op.getOperand(0);
9066   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9067     return SDValue();
9068
9069   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9070   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9071   // The canonical VMOV for a zero vector uses a 32-bit element size.
9072   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9073   unsigned EltBits;
9074   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9075     EltSize = 8;
9076   EVT VT = N->getValueType(0);
9077   if (EltSize > VT.getVectorElementType().getSizeInBits())
9078     return SDValue();
9079
9080   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9081 }
9082
9083 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9084 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9085 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9086 {
9087   integerPart cN;
9088   integerPart c0 = 0;
9089   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9090        I != E; I++) {
9091     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9092     if (!C)
9093       return false;
9094
9095     bool isExact;
9096     APFloat APF = C->getValueAPF();
9097     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9098         != APFloat::opOK || !isExact)
9099       return false;
9100
9101     c0 = (I == 0) ? cN : c0;
9102     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9103       return false;
9104   }
9105   C = c0;
9106   return true;
9107 }
9108
9109 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9110 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9111 /// when the VMUL has a constant operand that is a power of 2.
9112 ///
9113 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9114 ///  vmul.f32        d16, d17, d16
9115 ///  vcvt.s32.f32    d16, d16
9116 /// becomes:
9117 ///  vcvt.s32.f32    d16, d16, #3
9118 static SDValue PerformVCVTCombine(SDNode *N,
9119                                   TargetLowering::DAGCombinerInfo &DCI,
9120                                   const ARMSubtarget *Subtarget) {
9121   SelectionDAG &DAG = DCI.DAG;
9122   SDValue Op = N->getOperand(0);
9123
9124   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9125       Op.getOpcode() != ISD::FMUL)
9126     return SDValue();
9127
9128   uint64_t C;
9129   SDValue N0 = Op->getOperand(0);
9130   SDValue ConstVec = Op->getOperand(1);
9131   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9132
9133   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9134       !isConstVecPow2(ConstVec, isSigned, C))
9135     return SDValue();
9136
9137   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9138     Intrinsic::arm_neon_vcvtfp2fxu;
9139   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9140                      N->getValueType(0),
9141                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9142                      DAG.getConstant(Log2_64(C), MVT::i32));
9143 }
9144
9145 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9146 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9147 /// when the VDIV has a constant operand that is a power of 2.
9148 ///
9149 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9150 ///  vcvt.f32.s32    d16, d16
9151 ///  vdiv.f32        d16, d17, d16
9152 /// becomes:
9153 ///  vcvt.f32.s32    d16, d16, #3
9154 static SDValue PerformVDIVCombine(SDNode *N,
9155                                   TargetLowering::DAGCombinerInfo &DCI,
9156                                   const ARMSubtarget *Subtarget) {
9157   SelectionDAG &DAG = DCI.DAG;
9158   SDValue Op = N->getOperand(0);
9159   unsigned OpOpcode = Op.getNode()->getOpcode();
9160
9161   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9162       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9163     return SDValue();
9164
9165   uint64_t C;
9166   SDValue ConstVec = N->getOperand(1);
9167   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9168
9169   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9170       !isConstVecPow2(ConstVec, isSigned, C))
9171     return SDValue();
9172
9173   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9174     Intrinsic::arm_neon_vcvtfxu2fp;
9175   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9176                      Op.getValueType(),
9177                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9178                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
9179 }
9180
9181 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9182 /// operand of a vector shift operation, where all the elements of the
9183 /// build_vector must have the same constant integer value.
9184 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9185   // Ignore bit_converts.
9186   while (Op.getOpcode() == ISD::BITCAST)
9187     Op = Op.getOperand(0);
9188   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9189   APInt SplatBits, SplatUndef;
9190   unsigned SplatBitSize;
9191   bool HasAnyUndefs;
9192   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9193                                       HasAnyUndefs, ElementBits) ||
9194       SplatBitSize > ElementBits)
9195     return false;
9196   Cnt = SplatBits.getSExtValue();
9197   return true;
9198 }
9199
9200 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9201 /// operand of a vector shift left operation.  That value must be in the range:
9202 ///   0 <= Value < ElementBits for a left shift; or
9203 ///   0 <= Value <= ElementBits for a long left shift.
9204 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9205   assert(VT.isVector() && "vector shift count is not a vector type");
9206   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9207   if (! getVShiftImm(Op, ElementBits, Cnt))
9208     return false;
9209   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9210 }
9211
9212 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9213 /// operand of a vector shift right operation.  For a shift opcode, the value
9214 /// is positive, but for an intrinsic the value count must be negative. The
9215 /// absolute value must be in the range:
9216 ///   1 <= |Value| <= ElementBits for a right shift; or
9217 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9218 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9219                          int64_t &Cnt) {
9220   assert(VT.isVector() && "vector shift count is not a vector type");
9221   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9222   if (! getVShiftImm(Op, ElementBits, Cnt))
9223     return false;
9224   if (isIntrinsic)
9225     Cnt = -Cnt;
9226   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9227 }
9228
9229 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9230 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9231   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9232   switch (IntNo) {
9233   default:
9234     // Don't do anything for most intrinsics.
9235     break;
9236
9237   // Vector shifts: check for immediate versions and lower them.
9238   // Note: This is done during DAG combining instead of DAG legalizing because
9239   // the build_vectors for 64-bit vector element shift counts are generally
9240   // not legal, and it is hard to see their values after they get legalized to
9241   // loads from a constant pool.
9242   case Intrinsic::arm_neon_vshifts:
9243   case Intrinsic::arm_neon_vshiftu:
9244   case Intrinsic::arm_neon_vshiftls:
9245   case Intrinsic::arm_neon_vshiftlu:
9246   case Intrinsic::arm_neon_vshiftn:
9247   case Intrinsic::arm_neon_vrshifts:
9248   case Intrinsic::arm_neon_vrshiftu:
9249   case Intrinsic::arm_neon_vrshiftn:
9250   case Intrinsic::arm_neon_vqshifts:
9251   case Intrinsic::arm_neon_vqshiftu:
9252   case Intrinsic::arm_neon_vqshiftsu:
9253   case Intrinsic::arm_neon_vqshiftns:
9254   case Intrinsic::arm_neon_vqshiftnu:
9255   case Intrinsic::arm_neon_vqshiftnsu:
9256   case Intrinsic::arm_neon_vqrshiftns:
9257   case Intrinsic::arm_neon_vqrshiftnu:
9258   case Intrinsic::arm_neon_vqrshiftnsu: {
9259     EVT VT = N->getOperand(1).getValueType();
9260     int64_t Cnt;
9261     unsigned VShiftOpc = 0;
9262
9263     switch (IntNo) {
9264     case Intrinsic::arm_neon_vshifts:
9265     case Intrinsic::arm_neon_vshiftu:
9266       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9267         VShiftOpc = ARMISD::VSHL;
9268         break;
9269       }
9270       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9271         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9272                      ARMISD::VSHRs : ARMISD::VSHRu);
9273         break;
9274       }
9275       return SDValue();
9276
9277     case Intrinsic::arm_neon_vshiftls:
9278     case Intrinsic::arm_neon_vshiftlu:
9279       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
9280         break;
9281       llvm_unreachable("invalid shift count for vshll intrinsic");
9282
9283     case Intrinsic::arm_neon_vrshifts:
9284     case Intrinsic::arm_neon_vrshiftu:
9285       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9286         break;
9287       return SDValue();
9288
9289     case Intrinsic::arm_neon_vqshifts:
9290     case Intrinsic::arm_neon_vqshiftu:
9291       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9292         break;
9293       return SDValue();
9294
9295     case Intrinsic::arm_neon_vqshiftsu:
9296       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9297         break;
9298       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9299
9300     case Intrinsic::arm_neon_vshiftn:
9301     case Intrinsic::arm_neon_vrshiftn:
9302     case Intrinsic::arm_neon_vqshiftns:
9303     case Intrinsic::arm_neon_vqshiftnu:
9304     case Intrinsic::arm_neon_vqshiftnsu:
9305     case Intrinsic::arm_neon_vqrshiftns:
9306     case Intrinsic::arm_neon_vqrshiftnu:
9307     case Intrinsic::arm_neon_vqrshiftnsu:
9308       // Narrowing shifts require an immediate right shift.
9309       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9310         break;
9311       llvm_unreachable("invalid shift count for narrowing vector shift "
9312                        "intrinsic");
9313
9314     default:
9315       llvm_unreachable("unhandled vector shift");
9316     }
9317
9318     switch (IntNo) {
9319     case Intrinsic::arm_neon_vshifts:
9320     case Intrinsic::arm_neon_vshiftu:
9321       // Opcode already set above.
9322       break;
9323     case Intrinsic::arm_neon_vshiftls:
9324     case Intrinsic::arm_neon_vshiftlu:
9325       if (Cnt == VT.getVectorElementType().getSizeInBits())
9326         VShiftOpc = ARMISD::VSHLLi;
9327       else
9328         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
9329                      ARMISD::VSHLLs : ARMISD::VSHLLu);
9330       break;
9331     case Intrinsic::arm_neon_vshiftn:
9332       VShiftOpc = ARMISD::VSHRN; break;
9333     case Intrinsic::arm_neon_vrshifts:
9334       VShiftOpc = ARMISD::VRSHRs; break;
9335     case Intrinsic::arm_neon_vrshiftu:
9336       VShiftOpc = ARMISD::VRSHRu; break;
9337     case Intrinsic::arm_neon_vrshiftn:
9338       VShiftOpc = ARMISD::VRSHRN; break;
9339     case Intrinsic::arm_neon_vqshifts:
9340       VShiftOpc = ARMISD::VQSHLs; break;
9341     case Intrinsic::arm_neon_vqshiftu:
9342       VShiftOpc = ARMISD::VQSHLu; break;
9343     case Intrinsic::arm_neon_vqshiftsu:
9344       VShiftOpc = ARMISD::VQSHLsu; break;
9345     case Intrinsic::arm_neon_vqshiftns:
9346       VShiftOpc = ARMISD::VQSHRNs; break;
9347     case Intrinsic::arm_neon_vqshiftnu:
9348       VShiftOpc = ARMISD::VQSHRNu; break;
9349     case Intrinsic::arm_neon_vqshiftnsu:
9350       VShiftOpc = ARMISD::VQSHRNsu; break;
9351     case Intrinsic::arm_neon_vqrshiftns:
9352       VShiftOpc = ARMISD::VQRSHRNs; break;
9353     case Intrinsic::arm_neon_vqrshiftnu:
9354       VShiftOpc = ARMISD::VQRSHRNu; break;
9355     case Intrinsic::arm_neon_vqrshiftnsu:
9356       VShiftOpc = ARMISD::VQRSHRNsu; break;
9357     }
9358
9359     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9360                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9361   }
9362
9363   case Intrinsic::arm_neon_vshiftins: {
9364     EVT VT = N->getOperand(1).getValueType();
9365     int64_t Cnt;
9366     unsigned VShiftOpc = 0;
9367
9368     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9369       VShiftOpc = ARMISD::VSLI;
9370     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9371       VShiftOpc = ARMISD::VSRI;
9372     else {
9373       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9374     }
9375
9376     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9377                        N->getOperand(1), N->getOperand(2),
9378                        DAG.getConstant(Cnt, MVT::i32));
9379   }
9380
9381   case Intrinsic::arm_neon_vqrshifts:
9382   case Intrinsic::arm_neon_vqrshiftu:
9383     // No immediate versions of these to check for.
9384     break;
9385   }
9386
9387   return SDValue();
9388 }
9389
9390 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9391 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9392 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9393 /// vector element shift counts are generally not legal, and it is hard to see
9394 /// their values after they get legalized to loads from a constant pool.
9395 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9396                                    const ARMSubtarget *ST) {
9397   EVT VT = N->getValueType(0);
9398   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9399     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9400     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9401     SDValue N1 = N->getOperand(1);
9402     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9403       SDValue N0 = N->getOperand(0);
9404       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9405           DAG.MaskedValueIsZero(N0.getOperand(0),
9406                                 APInt::getHighBitsSet(32, 16)))
9407         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9408     }
9409   }
9410
9411   // Nothing to be done for scalar shifts.
9412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9413   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9414     return SDValue();
9415
9416   assert(ST->hasNEON() && "unexpected vector shift");
9417   int64_t Cnt;
9418
9419   switch (N->getOpcode()) {
9420   default: llvm_unreachable("unexpected shift opcode");
9421
9422   case ISD::SHL:
9423     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9424       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9425                          DAG.getConstant(Cnt, MVT::i32));
9426     break;
9427
9428   case ISD::SRA:
9429   case ISD::SRL:
9430     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9431       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9432                             ARMISD::VSHRs : ARMISD::VSHRu);
9433       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9434                          DAG.getConstant(Cnt, MVT::i32));
9435     }
9436   }
9437   return SDValue();
9438 }
9439
9440 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9441 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9442 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9443                                     const ARMSubtarget *ST) {
9444   SDValue N0 = N->getOperand(0);
9445
9446   // Check for sign- and zero-extensions of vector extract operations of 8-
9447   // and 16-bit vector elements.  NEON supports these directly.  They are
9448   // handled during DAG combining because type legalization will promote them
9449   // to 32-bit types and it is messy to recognize the operations after that.
9450   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9451     SDValue Vec = N0.getOperand(0);
9452     SDValue Lane = N0.getOperand(1);
9453     EVT VT = N->getValueType(0);
9454     EVT EltVT = N0.getValueType();
9455     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9456
9457     if (VT == MVT::i32 &&
9458         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9459         TLI.isTypeLegal(Vec.getValueType()) &&
9460         isa<ConstantSDNode>(Lane)) {
9461
9462       unsigned Opc = 0;
9463       switch (N->getOpcode()) {
9464       default: llvm_unreachable("unexpected opcode");
9465       case ISD::SIGN_EXTEND:
9466         Opc = ARMISD::VGETLANEs;
9467         break;
9468       case ISD::ZERO_EXTEND:
9469       case ISD::ANY_EXTEND:
9470         Opc = ARMISD::VGETLANEu;
9471         break;
9472       }
9473       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9474     }
9475   }
9476
9477   return SDValue();
9478 }
9479
9480 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9481 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9482 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9483                                        const ARMSubtarget *ST) {
9484   // If the target supports NEON, try to use vmax/vmin instructions for f32
9485   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9486   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9487   // a NaN; only do the transformation when it matches that behavior.
9488
9489   // For now only do this when using NEON for FP operations; if using VFP, it
9490   // is not obvious that the benefit outweighs the cost of switching to the
9491   // NEON pipeline.
9492   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9493       N->getValueType(0) != MVT::f32)
9494     return SDValue();
9495
9496   SDValue CondLHS = N->getOperand(0);
9497   SDValue CondRHS = N->getOperand(1);
9498   SDValue LHS = N->getOperand(2);
9499   SDValue RHS = N->getOperand(3);
9500   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9501
9502   unsigned Opcode = 0;
9503   bool IsReversed;
9504   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9505     IsReversed = false; // x CC y ? x : y
9506   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9507     IsReversed = true ; // x CC y ? y : x
9508   } else {
9509     return SDValue();
9510   }
9511
9512   bool IsUnordered;
9513   switch (CC) {
9514   default: break;
9515   case ISD::SETOLT:
9516   case ISD::SETOLE:
9517   case ISD::SETLT:
9518   case ISD::SETLE:
9519   case ISD::SETULT:
9520   case ISD::SETULE:
9521     // If LHS is NaN, an ordered comparison will be false and the result will
9522     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9523     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9524     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9525     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9526       break;
9527     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9528     // will return -0, so vmin can only be used for unsafe math or if one of
9529     // the operands is known to be nonzero.
9530     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9531         !DAG.getTarget().Options.UnsafeFPMath &&
9532         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9533       break;
9534     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9535     break;
9536
9537   case ISD::SETOGT:
9538   case ISD::SETOGE:
9539   case ISD::SETGT:
9540   case ISD::SETGE:
9541   case ISD::SETUGT:
9542   case ISD::SETUGE:
9543     // If LHS is NaN, an ordered comparison will be false and the result will
9544     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9545     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9546     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9547     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9548       break;
9549     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9550     // will return +0, so vmax can only be used for unsafe math or if one of
9551     // the operands is known to be nonzero.
9552     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9553         !DAG.getTarget().Options.UnsafeFPMath &&
9554         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9555       break;
9556     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9557     break;
9558   }
9559
9560   if (!Opcode)
9561     return SDValue();
9562   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9563 }
9564
9565 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9566 SDValue
9567 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9568   SDValue Cmp = N->getOperand(4);
9569   if (Cmp.getOpcode() != ARMISD::CMPZ)
9570     // Only looking at EQ and NE cases.
9571     return SDValue();
9572
9573   EVT VT = N->getValueType(0);
9574   SDLoc dl(N);
9575   SDValue LHS = Cmp.getOperand(0);
9576   SDValue RHS = Cmp.getOperand(1);
9577   SDValue FalseVal = N->getOperand(0);
9578   SDValue TrueVal = N->getOperand(1);
9579   SDValue ARMcc = N->getOperand(2);
9580   ARMCC::CondCodes CC =
9581     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9582
9583   // Simplify
9584   //   mov     r1, r0
9585   //   cmp     r1, x
9586   //   mov     r0, y
9587   //   moveq   r0, x
9588   // to
9589   //   cmp     r0, x
9590   //   movne   r0, y
9591   //
9592   //   mov     r1, r0
9593   //   cmp     r1, x
9594   //   mov     r0, x
9595   //   movne   r0, y
9596   // to
9597   //   cmp     r0, x
9598   //   movne   r0, y
9599   /// FIXME: Turn this into a target neutral optimization?
9600   SDValue Res;
9601   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9602     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9603                       N->getOperand(3), Cmp);
9604   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9605     SDValue ARMcc;
9606     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9607     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9608                       N->getOperand(3), NewCmp);
9609   }
9610
9611   if (Res.getNode()) {
9612     APInt KnownZero, KnownOne;
9613     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9614     // Capture demanded bits information that would be otherwise lost.
9615     if (KnownZero == 0xfffffffe)
9616       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9617                         DAG.getValueType(MVT::i1));
9618     else if (KnownZero == 0xffffff00)
9619       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9620                         DAG.getValueType(MVT::i8));
9621     else if (KnownZero == 0xffff0000)
9622       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9623                         DAG.getValueType(MVT::i16));
9624   }
9625
9626   return Res;
9627 }
9628
9629 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9630                                              DAGCombinerInfo &DCI) const {
9631   switch (N->getOpcode()) {
9632   default: break;
9633   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9634   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9635   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9636   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9637   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9638   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9639   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9640   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9641   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9642   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9643   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9644   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9645   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9646   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9647   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9648   case ISD::FP_TO_SINT:
9649   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9650   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9651   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9652   case ISD::SHL:
9653   case ISD::SRA:
9654   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9655   case ISD::SIGN_EXTEND:
9656   case ISD::ZERO_EXTEND:
9657   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9658   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9659   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9660   case ARMISD::VLD2DUP:
9661   case ARMISD::VLD3DUP:
9662   case ARMISD::VLD4DUP:
9663     return CombineBaseUpdate(N, DCI);
9664   case ISD::INTRINSIC_VOID:
9665   case ISD::INTRINSIC_W_CHAIN:
9666     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9667     case Intrinsic::arm_neon_vld1:
9668     case Intrinsic::arm_neon_vld2:
9669     case Intrinsic::arm_neon_vld3:
9670     case Intrinsic::arm_neon_vld4:
9671     case Intrinsic::arm_neon_vld2lane:
9672     case Intrinsic::arm_neon_vld3lane:
9673     case Intrinsic::arm_neon_vld4lane:
9674     case Intrinsic::arm_neon_vst1:
9675     case Intrinsic::arm_neon_vst2:
9676     case Intrinsic::arm_neon_vst3:
9677     case Intrinsic::arm_neon_vst4:
9678     case Intrinsic::arm_neon_vst2lane:
9679     case Intrinsic::arm_neon_vst3lane:
9680     case Intrinsic::arm_neon_vst4lane:
9681       return CombineBaseUpdate(N, DCI);
9682     default: break;
9683     }
9684     break;
9685   }
9686   return SDValue();
9687 }
9688
9689 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9690                                                           EVT VT) const {
9691   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9692 }
9693
9694 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
9695   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9696   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9697
9698   switch (VT.getSimpleVT().SimpleTy) {
9699   default:
9700     return false;
9701   case MVT::i8:
9702   case MVT::i16:
9703   case MVT::i32: {
9704     // Unaligned access can use (for example) LRDB, LRDH, LDR
9705     if (AllowsUnaligned) {
9706       if (Fast)
9707         *Fast = Subtarget->hasV7Ops();
9708       return true;
9709     }
9710     return false;
9711   }
9712   case MVT::f64:
9713   case MVT::v2f64: {
9714     // For any little-endian targets with neon, we can support unaligned ld/st
9715     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9716     // A big-endian target may also explictly support unaligned accesses
9717     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9718       if (Fast)
9719         *Fast = true;
9720       return true;
9721     }
9722     return false;
9723   }
9724   }
9725 }
9726
9727 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9728                        unsigned AlignCheck) {
9729   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9730           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9731 }
9732
9733 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9734                                            unsigned DstAlign, unsigned SrcAlign,
9735                                            bool IsMemset, bool ZeroMemset,
9736                                            bool MemcpyStrSrc,
9737                                            MachineFunction &MF) const {
9738   const Function *F = MF.getFunction();
9739
9740   // See if we can use NEON instructions for this...
9741   if ((!IsMemset || ZeroMemset) &&
9742       Subtarget->hasNEON() &&
9743       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9744                                        Attribute::NoImplicitFloat)) {
9745     bool Fast;
9746     if (Size >= 16 &&
9747         (memOpAlign(SrcAlign, DstAlign, 16) ||
9748          (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
9749       return MVT::v2f64;
9750     } else if (Size >= 8 &&
9751                (memOpAlign(SrcAlign, DstAlign, 8) ||
9752                 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
9753       return MVT::f64;
9754     }
9755   }
9756
9757   // Lowering to i32/i16 if the size permits.
9758   if (Size >= 4)
9759     return MVT::i32;
9760   else if (Size >= 2)
9761     return MVT::i16;
9762
9763   // Let the target-independent logic figure it out.
9764   return MVT::Other;
9765 }
9766
9767 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9768   if (Val.getOpcode() != ISD::LOAD)
9769     return false;
9770
9771   EVT VT1 = Val.getValueType();
9772   if (!VT1.isSimple() || !VT1.isInteger() ||
9773       !VT2.isSimple() || !VT2.isInteger())
9774     return false;
9775
9776   switch (VT1.getSimpleVT().SimpleTy) {
9777   default: break;
9778   case MVT::i1:
9779   case MVT::i8:
9780   case MVT::i16:
9781     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9782     return true;
9783   }
9784
9785   return false;
9786 }
9787
9788 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9789   if (V < 0)
9790     return false;
9791
9792   unsigned Scale = 1;
9793   switch (VT.getSimpleVT().SimpleTy) {
9794   default: return false;
9795   case MVT::i1:
9796   case MVT::i8:
9797     // Scale == 1;
9798     break;
9799   case MVT::i16:
9800     // Scale == 2;
9801     Scale = 2;
9802     break;
9803   case MVT::i32:
9804     // Scale == 4;
9805     Scale = 4;
9806     break;
9807   }
9808
9809   if ((V & (Scale - 1)) != 0)
9810     return false;
9811   V /= Scale;
9812   return V == (V & ((1LL << 5) - 1));
9813 }
9814
9815 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9816                                       const ARMSubtarget *Subtarget) {
9817   bool isNeg = false;
9818   if (V < 0) {
9819     isNeg = true;
9820     V = - V;
9821   }
9822
9823   switch (VT.getSimpleVT().SimpleTy) {
9824   default: return false;
9825   case MVT::i1:
9826   case MVT::i8:
9827   case MVT::i16:
9828   case MVT::i32:
9829     // + imm12 or - imm8
9830     if (isNeg)
9831       return V == (V & ((1LL << 8) - 1));
9832     return V == (V & ((1LL << 12) - 1));
9833   case MVT::f32:
9834   case MVT::f64:
9835     // Same as ARM mode. FIXME: NEON?
9836     if (!Subtarget->hasVFP2())
9837       return false;
9838     if ((V & 3) != 0)
9839       return false;
9840     V >>= 2;
9841     return V == (V & ((1LL << 8) - 1));
9842   }
9843 }
9844
9845 /// isLegalAddressImmediate - Return true if the integer value can be used
9846 /// as the offset of the target addressing mode for load / store of the
9847 /// given type.
9848 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9849                                     const ARMSubtarget *Subtarget) {
9850   if (V == 0)
9851     return true;
9852
9853   if (!VT.isSimple())
9854     return false;
9855
9856   if (Subtarget->isThumb1Only())
9857     return isLegalT1AddressImmediate(V, VT);
9858   else if (Subtarget->isThumb2())
9859     return isLegalT2AddressImmediate(V, VT, Subtarget);
9860
9861   // ARM mode.
9862   if (V < 0)
9863     V = - V;
9864   switch (VT.getSimpleVT().SimpleTy) {
9865   default: return false;
9866   case MVT::i1:
9867   case MVT::i8:
9868   case MVT::i32:
9869     // +- imm12
9870     return V == (V & ((1LL << 12) - 1));
9871   case MVT::i16:
9872     // +- imm8
9873     return V == (V & ((1LL << 8) - 1));
9874   case MVT::f32:
9875   case MVT::f64:
9876     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9877       return false;
9878     if ((V & 3) != 0)
9879       return false;
9880     V >>= 2;
9881     return V == (V & ((1LL << 8) - 1));
9882   }
9883 }
9884
9885 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9886                                                       EVT VT) const {
9887   int Scale = AM.Scale;
9888   if (Scale < 0)
9889     return false;
9890
9891   switch (VT.getSimpleVT().SimpleTy) {
9892   default: return false;
9893   case MVT::i1:
9894   case MVT::i8:
9895   case MVT::i16:
9896   case MVT::i32:
9897     if (Scale == 1)
9898       return true;
9899     // r + r << imm
9900     Scale = Scale & ~1;
9901     return Scale == 2 || Scale == 4 || Scale == 8;
9902   case MVT::i64:
9903     // r + r
9904     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9905       return true;
9906     return false;
9907   case MVT::isVoid:
9908     // Note, we allow "void" uses (basically, uses that aren't loads or
9909     // stores), because arm allows folding a scale into many arithmetic
9910     // operations.  This should be made more precise and revisited later.
9911
9912     // Allow r << imm, but the imm has to be a multiple of two.
9913     if (Scale & 1) return false;
9914     return isPowerOf2_32(Scale);
9915   }
9916 }
9917
9918 /// isLegalAddressingMode - Return true if the addressing mode represented
9919 /// by AM is legal for this target, for a load/store of the specified type.
9920 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9921                                               Type *Ty) const {
9922   EVT VT = getValueType(Ty, true);
9923   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9924     return false;
9925
9926   // Can never fold addr of global into load/store.
9927   if (AM.BaseGV)
9928     return false;
9929
9930   switch (AM.Scale) {
9931   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9932     break;
9933   case 1:
9934     if (Subtarget->isThumb1Only())
9935       return false;
9936     // FALL THROUGH.
9937   default:
9938     // ARM doesn't support any R+R*scale+imm addr modes.
9939     if (AM.BaseOffs)
9940       return false;
9941
9942     if (!VT.isSimple())
9943       return false;
9944
9945     if (Subtarget->isThumb2())
9946       return isLegalT2ScaledAddressingMode(AM, VT);
9947
9948     int Scale = AM.Scale;
9949     switch (VT.getSimpleVT().SimpleTy) {
9950     default: return false;
9951     case MVT::i1:
9952     case MVT::i8:
9953     case MVT::i32:
9954       if (Scale < 0) Scale = -Scale;
9955       if (Scale == 1)
9956         return true;
9957       // r + r << imm
9958       return isPowerOf2_32(Scale & ~1);
9959     case MVT::i16:
9960     case MVT::i64:
9961       // r + r
9962       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9963         return true;
9964       return false;
9965
9966     case MVT::isVoid:
9967       // Note, we allow "void" uses (basically, uses that aren't loads or
9968       // stores), because arm allows folding a scale into many arithmetic
9969       // operations.  This should be made more precise and revisited later.
9970
9971       // Allow r << imm, but the imm has to be a multiple of two.
9972       if (Scale & 1) return false;
9973       return isPowerOf2_32(Scale);
9974     }
9975   }
9976   return true;
9977 }
9978
9979 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9980 /// icmp immediate, that is the target has icmp instructions which can compare
9981 /// a register against the immediate without having to materialize the
9982 /// immediate into a register.
9983 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9984   // Thumb2 and ARM modes can use cmn for negative immediates.
9985   if (!Subtarget->isThumb())
9986     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9987   if (Subtarget->isThumb2())
9988     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9989   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9990   return Imm >= 0 && Imm <= 255;
9991 }
9992
9993 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9994 /// *or sub* immediate, that is the target has add or sub instructions which can
9995 /// add a register with the immediate without having to materialize the
9996 /// immediate into a register.
9997 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9998   // Same encoding for add/sub, just flip the sign.
9999   int64_t AbsImm = llvm::abs64(Imm);
10000   if (!Subtarget->isThumb())
10001     return ARM_AM::getSOImmVal(AbsImm) != -1;
10002   if (Subtarget->isThumb2())
10003     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10004   // Thumb1 only has 8-bit unsigned immediate.
10005   return AbsImm >= 0 && AbsImm <= 255;
10006 }
10007
10008 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10009                                       bool isSEXTLoad, SDValue &Base,
10010                                       SDValue &Offset, bool &isInc,
10011                                       SelectionDAG &DAG) {
10012   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10013     return false;
10014
10015   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10016     // AddressingMode 3
10017     Base = Ptr->getOperand(0);
10018     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10019       int RHSC = (int)RHS->getZExtValue();
10020       if (RHSC < 0 && RHSC > -256) {
10021         assert(Ptr->getOpcode() == ISD::ADD);
10022         isInc = false;
10023         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10024         return true;
10025       }
10026     }
10027     isInc = (Ptr->getOpcode() == ISD::ADD);
10028     Offset = Ptr->getOperand(1);
10029     return true;
10030   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10031     // AddressingMode 2
10032     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10033       int RHSC = (int)RHS->getZExtValue();
10034       if (RHSC < 0 && RHSC > -0x1000) {
10035         assert(Ptr->getOpcode() == ISD::ADD);
10036         isInc = false;
10037         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10038         Base = Ptr->getOperand(0);
10039         return true;
10040       }
10041     }
10042
10043     if (Ptr->getOpcode() == ISD::ADD) {
10044       isInc = true;
10045       ARM_AM::ShiftOpc ShOpcVal=
10046         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10047       if (ShOpcVal != ARM_AM::no_shift) {
10048         Base = Ptr->getOperand(1);
10049         Offset = Ptr->getOperand(0);
10050       } else {
10051         Base = Ptr->getOperand(0);
10052         Offset = Ptr->getOperand(1);
10053       }
10054       return true;
10055     }
10056
10057     isInc = (Ptr->getOpcode() == ISD::ADD);
10058     Base = Ptr->getOperand(0);
10059     Offset = Ptr->getOperand(1);
10060     return true;
10061   }
10062
10063   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10064   return false;
10065 }
10066
10067 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10068                                      bool isSEXTLoad, SDValue &Base,
10069                                      SDValue &Offset, bool &isInc,
10070                                      SelectionDAG &DAG) {
10071   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10072     return false;
10073
10074   Base = Ptr->getOperand(0);
10075   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10076     int RHSC = (int)RHS->getZExtValue();
10077     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10078       assert(Ptr->getOpcode() == ISD::ADD);
10079       isInc = false;
10080       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10081       return true;
10082     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10083       isInc = Ptr->getOpcode() == ISD::ADD;
10084       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10085       return true;
10086     }
10087   }
10088
10089   return false;
10090 }
10091
10092 /// getPreIndexedAddressParts - returns true by value, base pointer and
10093 /// offset pointer and addressing mode by reference if the node's address
10094 /// can be legally represented as pre-indexed load / store address.
10095 bool
10096 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10097                                              SDValue &Offset,
10098                                              ISD::MemIndexedMode &AM,
10099                                              SelectionDAG &DAG) const {
10100   if (Subtarget->isThumb1Only())
10101     return false;
10102
10103   EVT VT;
10104   SDValue Ptr;
10105   bool isSEXTLoad = false;
10106   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10107     Ptr = LD->getBasePtr();
10108     VT  = LD->getMemoryVT();
10109     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10110   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10111     Ptr = ST->getBasePtr();
10112     VT  = ST->getMemoryVT();
10113   } else
10114     return false;
10115
10116   bool isInc;
10117   bool isLegal = false;
10118   if (Subtarget->isThumb2())
10119     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10120                                        Offset, isInc, DAG);
10121   else
10122     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10123                                         Offset, isInc, DAG);
10124   if (!isLegal)
10125     return false;
10126
10127   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10128   return true;
10129 }
10130
10131 /// getPostIndexedAddressParts - returns true by value, base pointer and
10132 /// offset pointer and addressing mode by reference if this node can be
10133 /// combined with a load / store to form a post-indexed load / store.
10134 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10135                                                    SDValue &Base,
10136                                                    SDValue &Offset,
10137                                                    ISD::MemIndexedMode &AM,
10138                                                    SelectionDAG &DAG) const {
10139   if (Subtarget->isThumb1Only())
10140     return false;
10141
10142   EVT VT;
10143   SDValue Ptr;
10144   bool isSEXTLoad = false;
10145   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10146     VT  = LD->getMemoryVT();
10147     Ptr = LD->getBasePtr();
10148     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10149   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10150     VT  = ST->getMemoryVT();
10151     Ptr = ST->getBasePtr();
10152   } else
10153     return false;
10154
10155   bool isInc;
10156   bool isLegal = false;
10157   if (Subtarget->isThumb2())
10158     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10159                                        isInc, DAG);
10160   else
10161     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10162                                         isInc, DAG);
10163   if (!isLegal)
10164     return false;
10165
10166   if (Ptr != Base) {
10167     // Swap base ptr and offset to catch more post-index load / store when
10168     // it's legal. In Thumb2 mode, offset must be an immediate.
10169     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10170         !Subtarget->isThumb2())
10171       std::swap(Base, Offset);
10172
10173     // Post-indexed load / store update the base pointer.
10174     if (Ptr != Base)
10175       return false;
10176   }
10177
10178   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10179   return true;
10180 }
10181
10182 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10183                                                        APInt &KnownZero,
10184                                                        APInt &KnownOne,
10185                                                        const SelectionDAG &DAG,
10186                                                        unsigned Depth) const {
10187   unsigned BitWidth = KnownOne.getBitWidth();
10188   KnownZero = KnownOne = APInt(BitWidth, 0);
10189   switch (Op.getOpcode()) {
10190   default: break;
10191   case ARMISD::ADDC:
10192   case ARMISD::ADDE:
10193   case ARMISD::SUBC:
10194   case ARMISD::SUBE:
10195     // These nodes' second result is a boolean
10196     if (Op.getResNo() == 0)
10197       break;
10198     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10199     break;
10200   case ARMISD::CMOV: {
10201     // Bits are known zero/one if known on the LHS and RHS.
10202     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10203     if (KnownZero == 0 && KnownOne == 0) return;
10204
10205     APInt KnownZeroRHS, KnownOneRHS;
10206     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10207     KnownZero &= KnownZeroRHS;
10208     KnownOne  &= KnownOneRHS;
10209     return;
10210   }
10211   }
10212 }
10213
10214 //===----------------------------------------------------------------------===//
10215 //                           ARM Inline Assembly Support
10216 //===----------------------------------------------------------------------===//
10217
10218 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10219   // Looking for "rev" which is V6+.
10220   if (!Subtarget->hasV6Ops())
10221     return false;
10222
10223   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10224   std::string AsmStr = IA->getAsmString();
10225   SmallVector<StringRef, 4> AsmPieces;
10226   SplitString(AsmStr, AsmPieces, ";\n");
10227
10228   switch (AsmPieces.size()) {
10229   default: return false;
10230   case 1:
10231     AsmStr = AsmPieces[0];
10232     AsmPieces.clear();
10233     SplitString(AsmStr, AsmPieces, " \t,");
10234
10235     // rev $0, $1
10236     if (AsmPieces.size() == 3 &&
10237         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10238         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10239       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10240       if (Ty && Ty->getBitWidth() == 32)
10241         return IntrinsicLowering::LowerToByteSwap(CI);
10242     }
10243     break;
10244   }
10245
10246   return false;
10247 }
10248
10249 /// getConstraintType - Given a constraint letter, return the type of
10250 /// constraint it is for this target.
10251 ARMTargetLowering::ConstraintType
10252 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10253   if (Constraint.size() == 1) {
10254     switch (Constraint[0]) {
10255     default:  break;
10256     case 'l': return C_RegisterClass;
10257     case 'w': return C_RegisterClass;
10258     case 'h': return C_RegisterClass;
10259     case 'x': return C_RegisterClass;
10260     case 't': return C_RegisterClass;
10261     case 'j': return C_Other; // Constant for movw.
10262       // An address with a single base register. Due to the way we
10263       // currently handle addresses it is the same as an 'r' memory constraint.
10264     case 'Q': return C_Memory;
10265     }
10266   } else if (Constraint.size() == 2) {
10267     switch (Constraint[0]) {
10268     default: break;
10269     // All 'U+' constraints are addresses.
10270     case 'U': return C_Memory;
10271     }
10272   }
10273   return TargetLowering::getConstraintType(Constraint);
10274 }
10275
10276 /// Examine constraint type and operand type and determine a weight value.
10277 /// This object must already have been set up with the operand type
10278 /// and the current alternative constraint selected.
10279 TargetLowering::ConstraintWeight
10280 ARMTargetLowering::getSingleConstraintMatchWeight(
10281     AsmOperandInfo &info, const char *constraint) const {
10282   ConstraintWeight weight = CW_Invalid;
10283   Value *CallOperandVal = info.CallOperandVal;
10284     // If we don't have a value, we can't do a match,
10285     // but allow it at the lowest weight.
10286   if (CallOperandVal == NULL)
10287     return CW_Default;
10288   Type *type = CallOperandVal->getType();
10289   // Look at the constraint type.
10290   switch (*constraint) {
10291   default:
10292     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10293     break;
10294   case 'l':
10295     if (type->isIntegerTy()) {
10296       if (Subtarget->isThumb())
10297         weight = CW_SpecificReg;
10298       else
10299         weight = CW_Register;
10300     }
10301     break;
10302   case 'w':
10303     if (type->isFloatingPointTy())
10304       weight = CW_Register;
10305     break;
10306   }
10307   return weight;
10308 }
10309
10310 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10311 RCPair
10312 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10313                                                 MVT VT) const {
10314   if (Constraint.size() == 1) {
10315     // GCC ARM Constraint Letters
10316     switch (Constraint[0]) {
10317     case 'l': // Low regs or general regs.
10318       if (Subtarget->isThumb())
10319         return RCPair(0U, &ARM::tGPRRegClass);
10320       return RCPair(0U, &ARM::GPRRegClass);
10321     case 'h': // High regs or no regs.
10322       if (Subtarget->isThumb())
10323         return RCPair(0U, &ARM::hGPRRegClass);
10324       break;
10325     case 'r':
10326       return RCPair(0U, &ARM::GPRRegClass);
10327     case 'w':
10328       if (VT == MVT::f32)
10329         return RCPair(0U, &ARM::SPRRegClass);
10330       if (VT.getSizeInBits() == 64)
10331         return RCPair(0U, &ARM::DPRRegClass);
10332       if (VT.getSizeInBits() == 128)
10333         return RCPair(0U, &ARM::QPRRegClass);
10334       break;
10335     case 'x':
10336       if (VT == MVT::f32)
10337         return RCPair(0U, &ARM::SPR_8RegClass);
10338       if (VT.getSizeInBits() == 64)
10339         return RCPair(0U, &ARM::DPR_8RegClass);
10340       if (VT.getSizeInBits() == 128)
10341         return RCPair(0U, &ARM::QPR_8RegClass);
10342       break;
10343     case 't':
10344       if (VT == MVT::f32)
10345         return RCPair(0U, &ARM::SPRRegClass);
10346       break;
10347     }
10348   }
10349   if (StringRef("{cc}").equals_lower(Constraint))
10350     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10351
10352   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10353 }
10354
10355 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10356 /// vector.  If it is invalid, don't add anything to Ops.
10357 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10358                                                      std::string &Constraint,
10359                                                      std::vector<SDValue>&Ops,
10360                                                      SelectionDAG &DAG) const {
10361   SDValue Result(0, 0);
10362
10363   // Currently only support length 1 constraints.
10364   if (Constraint.length() != 1) return;
10365
10366   char ConstraintLetter = Constraint[0];
10367   switch (ConstraintLetter) {
10368   default: break;
10369   case 'j':
10370   case 'I': case 'J': case 'K': case 'L':
10371   case 'M': case 'N': case 'O':
10372     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10373     if (!C)
10374       return;
10375
10376     int64_t CVal64 = C->getSExtValue();
10377     int CVal = (int) CVal64;
10378     // None of these constraints allow values larger than 32 bits.  Check
10379     // that the value fits in an int.
10380     if (CVal != CVal64)
10381       return;
10382
10383     switch (ConstraintLetter) {
10384       case 'j':
10385         // Constant suitable for movw, must be between 0 and
10386         // 65535.
10387         if (Subtarget->hasV6T2Ops())
10388           if (CVal >= 0 && CVal <= 65535)
10389             break;
10390         return;
10391       case 'I':
10392         if (Subtarget->isThumb1Only()) {
10393           // This must be a constant between 0 and 255, for ADD
10394           // immediates.
10395           if (CVal >= 0 && CVal <= 255)
10396             break;
10397         } else if (Subtarget->isThumb2()) {
10398           // A constant that can be used as an immediate value in a
10399           // data-processing instruction.
10400           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10401             break;
10402         } else {
10403           // A constant that can be used as an immediate value in a
10404           // data-processing instruction.
10405           if (ARM_AM::getSOImmVal(CVal) != -1)
10406             break;
10407         }
10408         return;
10409
10410       case 'J':
10411         if (Subtarget->isThumb()) {  // FIXME thumb2
10412           // This must be a constant between -255 and -1, for negated ADD
10413           // immediates. This can be used in GCC with an "n" modifier that
10414           // prints the negated value, for use with SUB instructions. It is
10415           // not useful otherwise but is implemented for compatibility.
10416           if (CVal >= -255 && CVal <= -1)
10417             break;
10418         } else {
10419           // This must be a constant between -4095 and 4095. It is not clear
10420           // what this constraint is intended for. Implemented for
10421           // compatibility with GCC.
10422           if (CVal >= -4095 && CVal <= 4095)
10423             break;
10424         }
10425         return;
10426
10427       case 'K':
10428         if (Subtarget->isThumb1Only()) {
10429           // A 32-bit value where only one byte has a nonzero value. Exclude
10430           // zero to match GCC. This constraint is used by GCC internally for
10431           // constants that can be loaded with a move/shift combination.
10432           // It is not useful otherwise but is implemented for compatibility.
10433           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10434             break;
10435         } else if (Subtarget->isThumb2()) {
10436           // A constant whose bitwise inverse can be used as an immediate
10437           // value in a data-processing instruction. This can be used in GCC
10438           // with a "B" modifier that prints the inverted value, for use with
10439           // BIC and MVN instructions. It is not useful otherwise but is
10440           // implemented for compatibility.
10441           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10442             break;
10443         } else {
10444           // A constant whose bitwise inverse can be used as an immediate
10445           // value in a data-processing instruction. This can be used in GCC
10446           // with a "B" modifier that prints the inverted value, for use with
10447           // BIC and MVN instructions. It is not useful otherwise but is
10448           // implemented for compatibility.
10449           if (ARM_AM::getSOImmVal(~CVal) != -1)
10450             break;
10451         }
10452         return;
10453
10454       case 'L':
10455         if (Subtarget->isThumb1Only()) {
10456           // This must be a constant between -7 and 7,
10457           // for 3-operand ADD/SUB immediate instructions.
10458           if (CVal >= -7 && CVal < 7)
10459             break;
10460         } else if (Subtarget->isThumb2()) {
10461           // A constant whose negation can be used as an immediate value in a
10462           // data-processing instruction. This can be used in GCC with an "n"
10463           // modifier that prints the negated value, for use with SUB
10464           // instructions. It is not useful otherwise but is implemented for
10465           // compatibility.
10466           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10467             break;
10468         } else {
10469           // A constant whose negation can be used as an immediate value in a
10470           // data-processing instruction. This can be used in GCC with an "n"
10471           // modifier that prints the negated value, for use with SUB
10472           // instructions. It is not useful otherwise but is implemented for
10473           // compatibility.
10474           if (ARM_AM::getSOImmVal(-CVal) != -1)
10475             break;
10476         }
10477         return;
10478
10479       case 'M':
10480         if (Subtarget->isThumb()) { // FIXME thumb2
10481           // This must be a multiple of 4 between 0 and 1020, for
10482           // ADD sp + immediate.
10483           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10484             break;
10485         } else {
10486           // A power of two or a constant between 0 and 32.  This is used in
10487           // GCC for the shift amount on shifted register operands, but it is
10488           // useful in general for any shift amounts.
10489           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10490             break;
10491         }
10492         return;
10493
10494       case 'N':
10495         if (Subtarget->isThumb()) {  // FIXME thumb2
10496           // This must be a constant between 0 and 31, for shift amounts.
10497           if (CVal >= 0 && CVal <= 31)
10498             break;
10499         }
10500         return;
10501
10502       case 'O':
10503         if (Subtarget->isThumb()) {  // FIXME thumb2
10504           // This must be a multiple of 4 between -508 and 508, for
10505           // ADD/SUB sp = sp + immediate.
10506           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10507             break;
10508         }
10509         return;
10510     }
10511     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10512     break;
10513   }
10514
10515   if (Result.getNode()) {
10516     Ops.push_back(Result);
10517     return;
10518   }
10519   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10520 }
10521
10522 bool
10523 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10524   // The ARM target isn't yet aware of offsets.
10525   return false;
10526 }
10527
10528 bool ARM::isBitFieldInvertedMask(unsigned v) {
10529   if (v == 0xffffffff)
10530     return false;
10531
10532   // there can be 1's on either or both "outsides", all the "inside"
10533   // bits must be 0's
10534   unsigned TO = CountTrailingOnes_32(v);
10535   unsigned LO = CountLeadingOnes_32(v);
10536   v = (v >> TO) << TO;
10537   v = (v << LO) >> LO;
10538   return v == 0;
10539 }
10540
10541 /// isFPImmLegal - Returns true if the target can instruction select the
10542 /// specified FP immediate natively. If false, the legalizer will
10543 /// materialize the FP immediate as a load from a constant pool.
10544 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10545   if (!Subtarget->hasVFP3())
10546     return false;
10547   if (VT == MVT::f32)
10548     return ARM_AM::getFP32Imm(Imm) != -1;
10549   if (VT == MVT::f64)
10550     return ARM_AM::getFP64Imm(Imm) != -1;
10551   return false;
10552 }
10553
10554 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10555 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10556 /// specified in the intrinsic calls.
10557 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10558                                            const CallInst &I,
10559                                            unsigned Intrinsic) const {
10560   switch (Intrinsic) {
10561   case Intrinsic::arm_neon_vld1:
10562   case Intrinsic::arm_neon_vld2:
10563   case Intrinsic::arm_neon_vld3:
10564   case Intrinsic::arm_neon_vld4:
10565   case Intrinsic::arm_neon_vld2lane:
10566   case Intrinsic::arm_neon_vld3lane:
10567   case Intrinsic::arm_neon_vld4lane: {
10568     Info.opc = ISD::INTRINSIC_W_CHAIN;
10569     // Conservatively set memVT to the entire set of vectors loaded.
10570     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10571     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10572     Info.ptrVal = I.getArgOperand(0);
10573     Info.offset = 0;
10574     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10575     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10576     Info.vol = false; // volatile loads with NEON intrinsics not supported
10577     Info.readMem = true;
10578     Info.writeMem = false;
10579     return true;
10580   }
10581   case Intrinsic::arm_neon_vst1:
10582   case Intrinsic::arm_neon_vst2:
10583   case Intrinsic::arm_neon_vst3:
10584   case Intrinsic::arm_neon_vst4:
10585   case Intrinsic::arm_neon_vst2lane:
10586   case Intrinsic::arm_neon_vst3lane:
10587   case Intrinsic::arm_neon_vst4lane: {
10588     Info.opc = ISD::INTRINSIC_VOID;
10589     // Conservatively set memVT to the entire set of vectors stored.
10590     unsigned NumElts = 0;
10591     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10592       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10593       if (!ArgTy->isVectorTy())
10594         break;
10595       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10596     }
10597     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10598     Info.ptrVal = I.getArgOperand(0);
10599     Info.offset = 0;
10600     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10601     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10602     Info.vol = false; // volatile stores with NEON intrinsics not supported
10603     Info.readMem = false;
10604     Info.writeMem = true;
10605     return true;
10606   }
10607   case Intrinsic::arm_strexd: {
10608     Info.opc = ISD::INTRINSIC_W_CHAIN;
10609     Info.memVT = MVT::i64;
10610     Info.ptrVal = I.getArgOperand(2);
10611     Info.offset = 0;
10612     Info.align = 8;
10613     Info.vol = true;
10614     Info.readMem = false;
10615     Info.writeMem = true;
10616     return true;
10617   }
10618   case Intrinsic::arm_ldrexd: {
10619     Info.opc = ISD::INTRINSIC_W_CHAIN;
10620     Info.memVT = MVT::i64;
10621     Info.ptrVal = I.getArgOperand(0);
10622     Info.offset = 0;
10623     Info.align = 8;
10624     Info.vol = true;
10625     Info.readMem = true;
10626     Info.writeMem = false;
10627     return true;
10628   }
10629   default:
10630     break;
10631   }
10632
10633   return false;
10634 }