Add lowering of ARM 4-element shuffles to multiple instructios via perfectshuffle...
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/Constants.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instruction.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstrBuilder.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/CodeGen/SelectionDAG.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/VectorExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MathExtras.h"
43 using namespace llvm;
44
45 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
46                                    CCValAssign::LocInfo &LocInfo,
47                                    ISD::ArgFlagsTy &ArgFlags,
48                                    CCState &State);
49 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
50                                     CCValAssign::LocInfo &LocInfo,
51                                     ISD::ArgFlagsTy &ArgFlags,
52                                     CCState &State);
53 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
54                                       CCValAssign::LocInfo &LocInfo,
55                                       ISD::ArgFlagsTy &ArgFlags,
56                                       CCState &State);
57 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
58                                        CCValAssign::LocInfo &LocInfo,
59                                        ISD::ArgFlagsTy &ArgFlags,
60                                        CCState &State);
61
62 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
63                                        EVT PromotedBitwiseVT) {
64   if (VT != PromotedLdStVT) {
65     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
66     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
67                        PromotedLdStVT.getSimpleVT());
68
69     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
70     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
71                        PromotedLdStVT.getSimpleVT());
72   }
73
74   EVT ElemTy = VT.getVectorElementType();
75   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
76     setOperationAction(ISD::VSETCC, VT.getSimpleVT(), Custom);
77   if (ElemTy == MVT::i8 || ElemTy == MVT::i16)
78     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
79   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
80   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
81   setOperationAction(ISD::SCALAR_TO_VECTOR, VT.getSimpleVT(), Custom);
82   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Custom);
83   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Expand);
84   if (VT.isInteger()) {
85     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
86     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
87     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
88   }
89
90   // Promote all bit-wise operations.
91   if (VT.isInteger() && VT != PromotedBitwiseVT) {
92     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
93     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
94                        PromotedBitwiseVT.getSimpleVT());
95     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
96     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
97                        PromotedBitwiseVT.getSimpleVT());
98     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
99     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
100                        PromotedBitwiseVT.getSimpleVT());
101   }
102 }
103
104 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
105   addRegisterClass(VT, ARM::DPRRegisterClass);
106   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
107 }
108
109 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
110   addRegisterClass(VT, ARM::QPRRegisterClass);
111   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
112 }
113
114 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
115   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
116     return new TargetLoweringObjectFileMachO();
117   return new ARMElfTargetObjectFile();
118 }
119
120 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
121     : TargetLowering(TM, createTLOF(TM)), ARMPCLabelIndex(0) {
122   Subtarget = &TM.getSubtarget<ARMSubtarget>();
123
124   if (Subtarget->isTargetDarwin()) {
125     // Uses VFP for Thumb libfuncs if available.
126     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
127       // Single-precision floating-point arithmetic.
128       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
129       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
130       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
131       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
132
133       // Double-precision floating-point arithmetic.
134       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
135       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
136       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
137       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
138
139       // Single-precision comparisons.
140       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
141       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
142       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
143       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
144       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
145       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
146       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
147       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
148
149       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
150       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
151       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
152       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
153       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
154       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
155       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
156       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
157
158       // Double-precision comparisons.
159       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
160       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
161       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
162       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
163       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
164       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
165       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
166       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
167
168       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
169       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
170       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
171       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
172       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
173       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
174       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
175       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
176
177       // Floating-point to integer conversions.
178       // i64 conversions are done via library routines even when generating VFP
179       // instructions, so use the same ones.
180       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
181       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
182       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
183       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
184
185       // Conversions between floating types.
186       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
187       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
188
189       // Integer to floating-point conversions.
190       // i64 conversions are done via library routines even when generating VFP
191       // instructions, so use the same ones.
192       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
193       // e.g., __floatunsidf vs. __floatunssidfvfp.
194       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
195       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
196       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
197       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
198     }
199   }
200
201   // These libcalls are not available in 32-bit.
202   setLibcallName(RTLIB::SHL_I128, 0);
203   setLibcallName(RTLIB::SRL_I128, 0);
204   setLibcallName(RTLIB::SRA_I128, 0);
205
206   // Libcalls should use the AAPCS base standard ABI, even if hard float
207   // is in effect, as per the ARM RTABI specification, section 4.1.2.
208   if (Subtarget->isAAPCS_ABI()) {
209     for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i) {
210       setLibcallCallingConv(static_cast<RTLIB::Libcall>(i),
211                             CallingConv::ARM_AAPCS);
212     }
213   }
214
215   if (Subtarget->isThumb1Only())
216     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
217   else
218     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
219   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
220     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
221     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
222
223     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224   }
225
226   if (Subtarget->hasNEON()) {
227     addDRTypeForNEON(MVT::v2f32);
228     addDRTypeForNEON(MVT::v8i8);
229     addDRTypeForNEON(MVT::v4i16);
230     addDRTypeForNEON(MVT::v2i32);
231     addDRTypeForNEON(MVT::v1i64);
232
233     addQRTypeForNEON(MVT::v4f32);
234     addQRTypeForNEON(MVT::v2f64);
235     addQRTypeForNEON(MVT::v16i8);
236     addQRTypeForNEON(MVT::v8i16);
237     addQRTypeForNEON(MVT::v4i32);
238     addQRTypeForNEON(MVT::v2i64);
239
240     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
241     setTargetDAGCombine(ISD::SHL);
242     setTargetDAGCombine(ISD::SRL);
243     setTargetDAGCombine(ISD::SRA);
244     setTargetDAGCombine(ISD::SIGN_EXTEND);
245     setTargetDAGCombine(ISD::ZERO_EXTEND);
246     setTargetDAGCombine(ISD::ANY_EXTEND);
247   }
248
249   computeRegisterProperties();
250
251   // ARM does not have f32 extending load.
252   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
253
254   // ARM does not have i1 sign extending load.
255   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
256
257   // ARM supports all 4 flavors of integer indexed load / store.
258   if (!Subtarget->isThumb1Only()) {
259     for (unsigned im = (unsigned)ISD::PRE_INC;
260          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
261       setIndexedLoadAction(im,  MVT::i1,  Legal);
262       setIndexedLoadAction(im,  MVT::i8,  Legal);
263       setIndexedLoadAction(im,  MVT::i16, Legal);
264       setIndexedLoadAction(im,  MVT::i32, Legal);
265       setIndexedStoreAction(im, MVT::i1,  Legal);
266       setIndexedStoreAction(im, MVT::i8,  Legal);
267       setIndexedStoreAction(im, MVT::i16, Legal);
268       setIndexedStoreAction(im, MVT::i32, Legal);
269     }
270   }
271
272   // i64 operation support.
273   if (Subtarget->isThumb1Only()) {
274     setOperationAction(ISD::MUL,     MVT::i64, Expand);
275     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
276     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
277     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
278     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
279   } else {
280     setOperationAction(ISD::MUL,     MVT::i64, Expand);
281     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
282     if (!Subtarget->hasV6Ops())
283       setOperationAction(ISD::MULHS, MVT::i32, Expand);
284   }
285   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
286   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
287   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
288   setOperationAction(ISD::SRL,       MVT::i64, Custom);
289   setOperationAction(ISD::SRA,       MVT::i64, Custom);
290
291   // ARM does not have ROTL.
292   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
293   setOperationAction(ISD::CTTZ,  MVT::i32, Expand);
294   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
295   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
296     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
297
298   // Only ARMv6 has BSWAP.
299   if (!Subtarget->hasV6Ops())
300     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
301
302   // These are expanded into libcalls.
303   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
304   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
305   setOperationAction(ISD::SREM,  MVT::i32, Expand);
306   setOperationAction(ISD::UREM,  MVT::i32, Expand);
307   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
308   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
309
310   // Support label based line numbers.
311   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
312   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
313
314   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
315   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
316   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
317   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
318
319   // Use the default implementation.
320   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
321   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
322   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
323   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
324   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
325   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
326   setOperationAction(ISD::EHSELECTION,        MVT::i32,   Expand);
327   // FIXME: Shouldn't need this, since no register is used, but the legalizer
328   // doesn't yet know how to not do that for SjLj.
329   setExceptionSelectorRegister(ARM::R0);
330   if (Subtarget->isThumb())
331     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
332   else
333     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
334   setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
335
336   if (!Subtarget->hasV6Ops() && !Subtarget->isThumb2()) {
337     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
338     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
339   }
340   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
341
342   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only())
343     // Turn f64->i64 into FMRRD, i64 -> f64 to FMDRR iff target supports vfp2.
344     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
345
346   // We want to custom lower some of our intrinsics.
347   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
348   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
349   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
350
351   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
352   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
353   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
354   setOperationAction(ISD::SELECT,    MVT::i32, Expand);
355   setOperationAction(ISD::SELECT,    MVT::f32, Expand);
356   setOperationAction(ISD::SELECT,    MVT::f64, Expand);
357   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
358   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
359   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
360
361   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
362   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
363   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
364   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
365   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
366
367   // We don't support sin/cos/fmod/copysign/pow
368   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
369   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
370   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
371   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
372   setOperationAction(ISD::FREM,      MVT::f64, Expand);
373   setOperationAction(ISD::FREM,      MVT::f32, Expand);
374   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
375     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
376     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
377   }
378   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
379   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
380
381   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
382   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb1Only()) {
383     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
384     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
385     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
386     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
387   }
388
389   // We have target-specific dag combine patterns for the following nodes:
390   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
391   setTargetDAGCombine(ISD::ADD);
392   setTargetDAGCombine(ISD::SUB);
393
394   setStackPointerRegisterToSaveRestore(ARM::SP);
395   setSchedulingPreference(SchedulingForRegPressure);
396
397   // FIXME: If-converter should use instruction latency to determine
398   // profitability rather than relying on fixed limits.
399   if (Subtarget->getCPUString() == "generic") {
400     // Generic (and overly aggressive) if-conversion limits.
401     setIfCvtBlockSizeLimit(10);
402     setIfCvtDupBlockSizeLimit(2);
403   } else if (Subtarget->hasV6Ops()) {
404     setIfCvtBlockSizeLimit(2);
405     setIfCvtDupBlockSizeLimit(1);
406   } else {
407     setIfCvtBlockSizeLimit(3);
408     setIfCvtDupBlockSizeLimit(2);
409   }
410
411   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
412   // Do not enable CodePlacementOpt for now: it currently runs after the
413   // ARMConstantIslandPass and messes up branch relaxation and placement
414   // of constant islands.
415   // benefitFromCodePlacementOpt = true;
416 }
417
418 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
419   switch (Opcode) {
420   default: return 0;
421   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
422   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
423   case ARMISD::CALL:          return "ARMISD::CALL";
424   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
425   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
426   case ARMISD::tCALL:         return "ARMISD::tCALL";
427   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
428   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
429   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
430   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
431   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
432   case ARMISD::CMP:           return "ARMISD::CMP";
433   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
434   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
435   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
436   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
437   case ARMISD::CMOV:          return "ARMISD::CMOV";
438   case ARMISD::CNEG:          return "ARMISD::CNEG";
439
440   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
441   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
442   case ARMISD::SITOF:         return "ARMISD::SITOF";
443   case ARMISD::UITOF:         return "ARMISD::UITOF";
444
445   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
446   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
447   case ARMISD::RRX:           return "ARMISD::RRX";
448
449   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
450   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
451
452   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
453
454   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
455
456   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
457   case ARMISD::VCGE:          return "ARMISD::VCGE";
458   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
459   case ARMISD::VCGT:          return "ARMISD::VCGT";
460   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
461   case ARMISD::VTST:          return "ARMISD::VTST";
462
463   case ARMISD::VSHL:          return "ARMISD::VSHL";
464   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
465   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
466   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
467   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
468   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
469   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
470   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
471   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
472   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
473   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
474   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
475   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
476   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
477   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
478   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
479   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
480   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
481   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
482   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
483   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
484   case ARMISD::VDUP:          return "ARMISD::VDUP";
485   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
486   case ARMISD::VLD2D:         return "ARMISD::VLD2D";
487   case ARMISD::VLD3D:         return "ARMISD::VLD3D";
488   case ARMISD::VLD4D:         return "ARMISD::VLD4D";
489   case ARMISD::VST2D:         return "ARMISD::VST2D";
490   case ARMISD::VST3D:         return "ARMISD::VST3D";
491   case ARMISD::VST4D:         return "ARMISD::VST4D";
492   case ARMISD::VEXT:          return "ARMISD::VEXT";
493   case ARMISD::VREV64:        return "ARMISD::VREV64";
494   case ARMISD::VREV32:        return "ARMISD::VREV32";
495   case ARMISD::VREV16:        return "ARMISD::VREV16";
496   case ARMISD::VZIP32:        return "ARMISD::VZIP32";
497   case ARMISD::VZIP16:        return "ARMISD::VZIP16";
498   case ARMISD::VZIP8:         return "ARMISD::VZIP8";
499   case ARMISD::VUZP32:        return "ARMISD::VUZP32";
500   case ARMISD::VUZP16:        return "ARMISD::VUZP16";
501   case ARMISD::VUZP8:         return "ARMISD::VUZP8";
502   case ARMISD::VTRN32:        return "ARMISD::VTRN32";
503   case ARMISD::VTRN16:        return "ARMISD::VTRN16";
504   case ARMISD::VTRN8:         return "ARMISD::VTRN8";
505   }
506 }
507
508 /// getFunctionAlignment - Return the Log2 alignment of this function.
509 unsigned ARMTargetLowering::getFunctionAlignment(const Function *F) const {
510   return getTargetMachine().getSubtarget<ARMSubtarget>().isThumb() ? 1 : 2;
511 }
512
513 //===----------------------------------------------------------------------===//
514 // Lowering Code
515 //===----------------------------------------------------------------------===//
516
517 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
518 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
519   switch (CC) {
520   default: llvm_unreachable("Unknown condition code!");
521   case ISD::SETNE:  return ARMCC::NE;
522   case ISD::SETEQ:  return ARMCC::EQ;
523   case ISD::SETGT:  return ARMCC::GT;
524   case ISD::SETGE:  return ARMCC::GE;
525   case ISD::SETLT:  return ARMCC::LT;
526   case ISD::SETLE:  return ARMCC::LE;
527   case ISD::SETUGT: return ARMCC::HI;
528   case ISD::SETUGE: return ARMCC::HS;
529   case ISD::SETULT: return ARMCC::LO;
530   case ISD::SETULE: return ARMCC::LS;
531   }
532 }
533
534 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
535 /// returns true if the operands should be inverted to form the proper
536 /// comparison.
537 static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
538                         ARMCC::CondCodes &CondCode2) {
539   bool Invert = false;
540   CondCode2 = ARMCC::AL;
541   switch (CC) {
542   default: llvm_unreachable("Unknown FP condition!");
543   case ISD::SETEQ:
544   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
545   case ISD::SETGT:
546   case ISD::SETOGT: CondCode = ARMCC::GT; break;
547   case ISD::SETGE:
548   case ISD::SETOGE: CondCode = ARMCC::GE; break;
549   case ISD::SETOLT: CondCode = ARMCC::MI; break;
550   case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
551   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
552   case ISD::SETO:   CondCode = ARMCC::VC; break;
553   case ISD::SETUO:  CondCode = ARMCC::VS; break;
554   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
555   case ISD::SETUGT: CondCode = ARMCC::HI; break;
556   case ISD::SETUGE: CondCode = ARMCC::PL; break;
557   case ISD::SETLT:
558   case ISD::SETULT: CondCode = ARMCC::LT; break;
559   case ISD::SETLE:
560   case ISD::SETULE: CondCode = ARMCC::LE; break;
561   case ISD::SETNE:
562   case ISD::SETUNE: CondCode = ARMCC::NE; break;
563   }
564   return Invert;
565 }
566
567 //===----------------------------------------------------------------------===//
568 //                      Calling Convention Implementation
569 //===----------------------------------------------------------------------===//
570
571 #include "ARMGenCallingConv.inc"
572
573 // APCS f64 is in register pairs, possibly split to stack
574 static bool f64AssignAPCS(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
575                           CCValAssign::LocInfo &LocInfo,
576                           CCState &State, bool CanFail) {
577   static const unsigned RegList[] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 };
578
579   // Try to get the first register.
580   if (unsigned Reg = State.AllocateReg(RegList, 4))
581     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
582   else {
583     // For the 2nd half of a v2f64, do not fail.
584     if (CanFail)
585       return false;
586
587     // Put the whole thing on the stack.
588     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
589                                            State.AllocateStack(8, 4),
590                                            LocVT, LocInfo));
591     return true;
592   }
593
594   // Try to get the second register.
595   if (unsigned Reg = State.AllocateReg(RegList, 4))
596     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
597   else
598     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
599                                            State.AllocateStack(4, 4),
600                                            LocVT, LocInfo));
601   return true;
602 }
603
604 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
605                                    CCValAssign::LocInfo &LocInfo,
606                                    ISD::ArgFlagsTy &ArgFlags,
607                                    CCState &State) {
608   if (!f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
609     return false;
610   if (LocVT == MVT::v2f64 &&
611       !f64AssignAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
612     return false;
613   return true;  // we handled it
614 }
615
616 // AAPCS f64 is in aligned register pairs
617 static bool f64AssignAAPCS(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
618                            CCValAssign::LocInfo &LocInfo,
619                            CCState &State, bool CanFail) {
620   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
621   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
622
623   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
624   if (Reg == 0) {
625     // For the 2nd half of a v2f64, do not just fail.
626     if (CanFail)
627       return false;
628
629     // Put the whole thing on the stack.
630     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
631                                            State.AllocateStack(8, 8),
632                                            LocVT, LocInfo));
633     return true;
634   }
635
636   unsigned i;
637   for (i = 0; i < 2; ++i)
638     if (HiRegList[i] == Reg)
639       break;
640
641   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
642   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
643                                          LocVT, LocInfo));
644   return true;
645 }
646
647 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
648                                     CCValAssign::LocInfo &LocInfo,
649                                     ISD::ArgFlagsTy &ArgFlags,
650                                     CCState &State) {
651   if (!f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, true))
652     return false;
653   if (LocVT == MVT::v2f64 &&
654       !f64AssignAAPCS(ValNo, ValVT, LocVT, LocInfo, State, false))
655     return false;
656   return true;  // we handled it
657 }
658
659 static bool f64RetAssign(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
660                          CCValAssign::LocInfo &LocInfo, CCState &State) {
661   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
662   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
663
664   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
665   if (Reg == 0)
666     return false; // we didn't handle it
667
668   unsigned i;
669   for (i = 0; i < 2; ++i)
670     if (HiRegList[i] == Reg)
671       break;
672
673   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
674   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
675                                          LocVT, LocInfo));
676   return true;
677 }
678
679 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
680                                       CCValAssign::LocInfo &LocInfo,
681                                       ISD::ArgFlagsTy &ArgFlags,
682                                       CCState &State) {
683   if (!f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
684     return false;
685   if (LocVT == MVT::v2f64 && !f64RetAssign(ValNo, ValVT, LocVT, LocInfo, State))
686     return false;
687   return true;  // we handled it
688 }
689
690 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, EVT &ValVT, EVT &LocVT,
691                                        CCValAssign::LocInfo &LocInfo,
692                                        ISD::ArgFlagsTy &ArgFlags,
693                                        CCState &State) {
694   return RetCC_ARM_APCS_Custom_f64(ValNo, ValVT, LocVT, LocInfo, ArgFlags,
695                                    State);
696 }
697
698 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
699 /// given CallingConvention value.
700 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(unsigned CC,
701                                                  bool Return,
702                                                  bool isVarArg) const {
703   switch (CC) {
704   default:
705     llvm_unreachable("Unsupported calling convention");
706   case CallingConv::C:
707   case CallingConv::Fast:
708     // Use target triple & subtarget features to do actual dispatch.
709     if (Subtarget->isAAPCS_ABI()) {
710       if (Subtarget->hasVFP2() &&
711           FloatABIType == FloatABI::Hard && !isVarArg)
712         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
713       else
714         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
715     } else
716         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
717   case CallingConv::ARM_AAPCS_VFP:
718     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
719   case CallingConv::ARM_AAPCS:
720     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
721   case CallingConv::ARM_APCS:
722     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
723   }
724 }
725
726 /// LowerCallResult - Lower the result values of a call into the
727 /// appropriate copies out of appropriate physical registers.
728 SDValue
729 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
730                                    unsigned CallConv, bool isVarArg,
731                                    const SmallVectorImpl<ISD::InputArg> &Ins,
732                                    DebugLoc dl, SelectionDAG &DAG,
733                                    SmallVectorImpl<SDValue> &InVals) {
734
735   // Assign locations to each value returned by this call.
736   SmallVector<CCValAssign, 16> RVLocs;
737   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
738                  RVLocs, *DAG.getContext());
739   CCInfo.AnalyzeCallResult(Ins,
740                            CCAssignFnForNode(CallConv, /* Return*/ true,
741                                              isVarArg));
742
743   // Copy all of the result registers out of their specified physreg.
744   for (unsigned i = 0; i != RVLocs.size(); ++i) {
745     CCValAssign VA = RVLocs[i];
746
747     SDValue Val;
748     if (VA.needsCustom()) {
749       // Handle f64 or half of a v2f64.
750       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
751                                       InFlag);
752       Chain = Lo.getValue(1);
753       InFlag = Lo.getValue(2);
754       VA = RVLocs[++i]; // skip ahead to next loc
755       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
756                                       InFlag);
757       Chain = Hi.getValue(1);
758       InFlag = Hi.getValue(2);
759       Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
760
761       if (VA.getLocVT() == MVT::v2f64) {
762         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
763         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
764                           DAG.getConstant(0, MVT::i32));
765
766         VA = RVLocs[++i]; // skip ahead to next loc
767         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
768         Chain = Lo.getValue(1);
769         InFlag = Lo.getValue(2);
770         VA = RVLocs[++i]; // skip ahead to next loc
771         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
772         Chain = Hi.getValue(1);
773         InFlag = Hi.getValue(2);
774         Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
775         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
776                           DAG.getConstant(1, MVT::i32));
777       }
778     } else {
779       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
780                                InFlag);
781       Chain = Val.getValue(1);
782       InFlag = Val.getValue(2);
783     }
784
785     switch (VA.getLocInfo()) {
786     default: llvm_unreachable("Unknown loc info!");
787     case CCValAssign::Full: break;
788     case CCValAssign::BCvt:
789       Val = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), Val);
790       break;
791     }
792
793     InVals.push_back(Val);
794   }
795
796   return Chain;
797 }
798
799 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
800 /// by "Src" to address "Dst" of size "Size".  Alignment information is
801 /// specified by the specific parameter attribute.  The copy will be passed as
802 /// a byval function parameter.
803 /// Sometimes what we are copying is the end of a larger object, the part that
804 /// does not fit in registers.
805 static SDValue
806 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
807                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
808                           DebugLoc dl) {
809   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
810   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
811                        /*AlwaysInline=*/false, NULL, 0, NULL, 0);
812 }
813
814 /// LowerMemOpCallTo - Store the argument to the stack.
815 SDValue
816 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
817                                     SDValue StackPtr, SDValue Arg,
818                                     DebugLoc dl, SelectionDAG &DAG,
819                                     const CCValAssign &VA,
820                                     ISD::ArgFlagsTy Flags) {
821   unsigned LocMemOffset = VA.getLocMemOffset();
822   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
823   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
824   if (Flags.isByVal()) {
825     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
826   }
827   return DAG.getStore(Chain, dl, Arg, PtrOff,
828                       PseudoSourceValue::getStack(), LocMemOffset);
829 }
830
831 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
832                                          SDValue Chain, SDValue &Arg,
833                                          RegsToPassVector &RegsToPass,
834                                          CCValAssign &VA, CCValAssign &NextVA,
835                                          SDValue &StackPtr,
836                                          SmallVector<SDValue, 8> &MemOpChains,
837                                          ISD::ArgFlagsTy Flags) {
838
839   SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
840                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
841   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
842
843   if (NextVA.isRegLoc())
844     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
845   else {
846     assert(NextVA.isMemLoc());
847     if (StackPtr.getNode() == 0)
848       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
849
850     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
851                                            dl, DAG, NextVA,
852                                            Flags));
853   }
854 }
855
856 /// LowerCall - Lowering a call into a callseq_start <-
857 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
858 /// nodes.
859 SDValue
860 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
861                              unsigned CallConv, bool isVarArg,
862                              bool isTailCall,
863                              const SmallVectorImpl<ISD::OutputArg> &Outs,
864                              const SmallVectorImpl<ISD::InputArg> &Ins,
865                              DebugLoc dl, SelectionDAG &DAG,
866                              SmallVectorImpl<SDValue> &InVals) {
867
868   // Analyze operands of the call, assigning locations to each operand.
869   SmallVector<CCValAssign, 16> ArgLocs;
870   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
871                  *DAG.getContext());
872   CCInfo.AnalyzeCallOperands(Outs,
873                              CCAssignFnForNode(CallConv, /* Return*/ false,
874                                                isVarArg));
875
876   // Get a count of how many bytes are to be pushed on the stack.
877   unsigned NumBytes = CCInfo.getNextStackOffset();
878
879   // Adjust the stack pointer for the new arguments...
880   // These operations are automatically eliminated by the prolog/epilog pass
881   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
882
883   SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
884
885   RegsToPassVector RegsToPass;
886   SmallVector<SDValue, 8> MemOpChains;
887
888   // Walk the register/memloc assignments, inserting copies/loads.  In the case
889   // of tail call optimization, arguments are handled later.
890   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
891        i != e;
892        ++i, ++realArgIdx) {
893     CCValAssign &VA = ArgLocs[i];
894     SDValue Arg = Outs[realArgIdx].Val;
895     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
896
897     // Promote the value if needed.
898     switch (VA.getLocInfo()) {
899     default: llvm_unreachable("Unknown loc info!");
900     case CCValAssign::Full: break;
901     case CCValAssign::SExt:
902       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
903       break;
904     case CCValAssign::ZExt:
905       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
906       break;
907     case CCValAssign::AExt:
908       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
909       break;
910     case CCValAssign::BCvt:
911       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
912       break;
913     }
914
915     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
916     if (VA.needsCustom()) {
917       if (VA.getLocVT() == MVT::v2f64) {
918         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
919                                   DAG.getConstant(0, MVT::i32));
920         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
921                                   DAG.getConstant(1, MVT::i32));
922
923         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
924                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
925
926         VA = ArgLocs[++i]; // skip ahead to next loc
927         if (VA.isRegLoc()) {
928           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
929                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
930         } else {
931           assert(VA.isMemLoc());
932           if (StackPtr.getNode() == 0)
933             StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
934
935           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
936                                                  dl, DAG, VA, Flags));
937         }
938       } else {
939         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
940                          StackPtr, MemOpChains, Flags);
941       }
942     } else if (VA.isRegLoc()) {
943       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
944     } else {
945       assert(VA.isMemLoc());
946       if (StackPtr.getNode() == 0)
947         StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
948
949       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
950                                              dl, DAG, VA, Flags));
951     }
952   }
953
954   if (!MemOpChains.empty())
955     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
956                         &MemOpChains[0], MemOpChains.size());
957
958   // Build a sequence of copy-to-reg nodes chained together with token chain
959   // and flag operands which copy the outgoing args into the appropriate regs.
960   SDValue InFlag;
961   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
962     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
963                              RegsToPass[i].second, InFlag);
964     InFlag = Chain.getValue(1);
965   }
966
967   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
968   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
969   // node so that legalize doesn't hack it.
970   bool isDirect = false;
971   bool isARMFunc = false;
972   bool isLocalARMFunc = false;
973   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
974     GlobalValue *GV = G->getGlobal();
975     isDirect = true;
976     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
977     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
978                    getTargetMachine().getRelocationModel() != Reloc::Static;
979     isARMFunc = !Subtarget->isThumb() || isStub;
980     // ARM call to a local ARM function is predicable.
981     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
982     // tBX takes a register source operand.
983     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
984       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
985                                                            ARMCP::CPStub, 4);
986       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
987       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
988       Callee = DAG.getLoad(getPointerTy(), dl,
989                            DAG.getEntryNode(), CPAddr, NULL, 0);
990       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
991       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
992                            getPointerTy(), Callee, PICLabel);
993    } else
994       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
995   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
996     isDirect = true;
997     bool isStub = Subtarget->isTargetDarwin() &&
998                   getTargetMachine().getRelocationModel() != Reloc::Static;
999     isARMFunc = !Subtarget->isThumb() || isStub;
1000     // tBX takes a register source operand.
1001     const char *Sym = S->getSymbol();
1002     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1003       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1004                                                           Sym, ARMPCLabelIndex,
1005                                                            ARMCP::CPStub, 4);
1006       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1007       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1008       Callee = DAG.getLoad(getPointerTy(), dl,
1009                            DAG.getEntryNode(), CPAddr, NULL, 0);
1010       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1011       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1012                            getPointerTy(), Callee, PICLabel);
1013     } else
1014       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1015   }
1016
1017   // FIXME: handle tail calls differently.
1018   unsigned CallOpc;
1019   if (Subtarget->isThumb()) {
1020     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1021       CallOpc = ARMISD::CALL_NOLINK;
1022     else
1023       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1024   } else {
1025     CallOpc = (isDirect || Subtarget->hasV5TOps())
1026       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
1027       : ARMISD::CALL_NOLINK;
1028   }
1029   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb1Only()) {
1030     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
1031     Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
1032     InFlag = Chain.getValue(1);
1033   }
1034
1035   std::vector<SDValue> Ops;
1036   Ops.push_back(Chain);
1037   Ops.push_back(Callee);
1038
1039   // Add argument registers to the end of the list so that they are known live
1040   // into the call.
1041   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1042     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1043                                   RegsToPass[i].second.getValueType()));
1044
1045   if (InFlag.getNode())
1046     Ops.push_back(InFlag);
1047   // Returns a chain and a flag for retval copy to use.
1048   Chain = DAG.getNode(CallOpc, dl, DAG.getVTList(MVT::Other, MVT::Flag),
1049                       &Ops[0], Ops.size());
1050   InFlag = Chain.getValue(1);
1051
1052   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1053                              DAG.getIntPtrConstant(0, true), InFlag);
1054   if (!Ins.empty())
1055     InFlag = Chain.getValue(1);
1056
1057   // Handle result values, copying them out of physregs into vregs that we
1058   // return.
1059   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1060                          dl, DAG, InVals);
1061 }
1062
1063 SDValue
1064 ARMTargetLowering::LowerReturn(SDValue Chain,
1065                                unsigned CallConv, bool isVarArg,
1066                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1067                                DebugLoc dl, SelectionDAG &DAG) {
1068
1069   // CCValAssign - represent the assignment of the return value to a location.
1070   SmallVector<CCValAssign, 16> RVLocs;
1071
1072   // CCState - Info about the registers and stack slots.
1073   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
1074                  *DAG.getContext());
1075
1076   // Analyze outgoing return values.
1077   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1078                                                isVarArg));
1079
1080   // If this is the first return lowered for this function, add
1081   // the regs to the liveout set for the function.
1082   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1083     for (unsigned i = 0; i != RVLocs.size(); ++i)
1084       if (RVLocs[i].isRegLoc())
1085         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1086   }
1087
1088   SDValue Flag;
1089
1090   // Copy the result values into the output registers.
1091   for (unsigned i = 0, realRVLocIdx = 0;
1092        i != RVLocs.size();
1093        ++i, ++realRVLocIdx) {
1094     CCValAssign &VA = RVLocs[i];
1095     assert(VA.isRegLoc() && "Can only return in registers!");
1096
1097     SDValue Arg = Outs[realRVLocIdx].Val;
1098
1099     switch (VA.getLocInfo()) {
1100     default: llvm_unreachable("Unknown loc info!");
1101     case CCValAssign::Full: break;
1102     case CCValAssign::BCvt:
1103       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
1104       break;
1105     }
1106
1107     if (VA.needsCustom()) {
1108       if (VA.getLocVT() == MVT::v2f64) {
1109         // Extract the first half and return it in two registers.
1110         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1111                                    DAG.getConstant(0, MVT::i32));
1112         SDValue HalfGPRs = DAG.getNode(ARMISD::FMRRD, dl,
1113                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1114
1115         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1116         Flag = Chain.getValue(1);
1117         VA = RVLocs[++i]; // skip ahead to next loc
1118         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1119                                  HalfGPRs.getValue(1), Flag);
1120         Flag = Chain.getValue(1);
1121         VA = RVLocs[++i]; // skip ahead to next loc
1122
1123         // Extract the 2nd half and fall through to handle it as an f64 value.
1124         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1125                           DAG.getConstant(1, MVT::i32));
1126       }
1127       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1128       // available.
1129       SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
1130                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1131       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1132       Flag = Chain.getValue(1);
1133       VA = RVLocs[++i]; // skip ahead to next loc
1134       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1135                                Flag);
1136     } else
1137       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1138
1139     // Guarantee that all emitted copies are
1140     // stuck together, avoiding something bad.
1141     Flag = Chain.getValue(1);
1142   }
1143
1144   SDValue result;
1145   if (Flag.getNode())
1146     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1147   else // Return Void
1148     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1149
1150   return result;
1151 }
1152
1153 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
1154 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
1155 // one of the above mentioned nodes. It has to be wrapped because otherwise
1156 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1157 // be used to form addressing mode. These wrapped nodes will be selected
1158 // into MOVi.
1159 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
1160   EVT PtrVT = Op.getValueType();
1161   // FIXME there is no actual debug info here
1162   DebugLoc dl = Op.getDebugLoc();
1163   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1164   SDValue Res;
1165   if (CP->isMachineConstantPoolEntry())
1166     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1167                                     CP->getAlignment());
1168   else
1169     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1170                                     CP->getAlignment());
1171   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
1172 }
1173
1174 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
1175 SDValue
1176 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
1177                                                  SelectionDAG &DAG) {
1178   DebugLoc dl = GA->getDebugLoc();
1179   EVT PtrVT = getPointerTy();
1180   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1181   ARMConstantPoolValue *CPV =
1182     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
1183                              PCAdj, "tlsgd", true);
1184   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1185   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
1186   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, NULL, 0);
1187   SDValue Chain = Argument.getValue(1);
1188
1189   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1190   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
1191
1192   // call __tls_get_addr.
1193   ArgListTy Args;
1194   ArgListEntry Entry;
1195   Entry.Node = Argument;
1196   Entry.Ty = (const Type *) Type::getInt32Ty(*DAG.getContext());
1197   Args.push_back(Entry);
1198   // FIXME: is there useful debug info available here?
1199   std::pair<SDValue, SDValue> CallResult =
1200     LowerCallTo(Chain, (const Type *) Type::getInt32Ty(*DAG.getContext()),
1201                 false, false, false, false,
1202                 0, CallingConv::C, false, /*isReturnValueUsed=*/true,
1203                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
1204   return CallResult.first;
1205 }
1206
1207 // Lower ISD::GlobalTLSAddress using the "initial exec" or
1208 // "local exec" model.
1209 SDValue
1210 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
1211                                         SelectionDAG &DAG) {
1212   GlobalValue *GV = GA->getGlobal();
1213   DebugLoc dl = GA->getDebugLoc();
1214   SDValue Offset;
1215   SDValue Chain = DAG.getEntryNode();
1216   EVT PtrVT = getPointerTy();
1217   // Get the Thread Pointer
1218   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1219
1220   if (GV->isDeclaration()) {
1221     // initial exec model
1222     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
1223     ARMConstantPoolValue *CPV =
1224       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
1225                                PCAdj, "gottpoff", true);
1226     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1227     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1228     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1229     Chain = Offset.getValue(1);
1230
1231     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1232     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
1233
1234     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1235   } else {
1236     // local exec model
1237     ARMConstantPoolValue *CPV =
1238       new ARMConstantPoolValue(GV, ARMCP::CPValue, "tpoff");
1239     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1240     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
1241     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
1242   }
1243
1244   // The address of the thread local variable is the add of the thread
1245   // pointer with the offset of the variable.
1246   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1247 }
1248
1249 SDValue
1250 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
1251   // TODO: implement the "local dynamic" model
1252   assert(Subtarget->isTargetELF() &&
1253          "TLS not implemented for non-ELF targets");
1254   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1255   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
1256   // otherwise use the "Local Exec" TLS Model
1257   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
1258     return LowerToTLSGeneralDynamicModel(GA, DAG);
1259   else
1260     return LowerToTLSExecModels(GA, DAG);
1261 }
1262
1263 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
1264                                                  SelectionDAG &DAG) {
1265   EVT PtrVT = getPointerTy();
1266   DebugLoc dl = Op.getDebugLoc();
1267   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1268   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1269   if (RelocM == Reloc::PIC_) {
1270     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
1271     ARMConstantPoolValue *CPV =
1272       new ARMConstantPoolValue(GV, ARMCP::CPValue, UseGOTOFF ? "GOTOFF":"GOT");
1273     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1274     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1275     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
1276                                  CPAddr, NULL, 0);
1277     SDValue Chain = Result.getValue(1);
1278     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
1279     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
1280     if (!UseGOTOFF)
1281       Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1282     return Result;
1283   } else {
1284     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1285     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1286     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1287   }
1288 }
1289
1290 /// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol
1291 /// even in non-static mode.
1292 static bool GVIsIndirectSymbol(GlobalValue *GV, Reloc::Model RelocM) {
1293   // If symbol visibility is hidden, the extra load is not needed if
1294   // the symbol is definitely defined in the current translation unit.
1295   bool isDecl = GV->isDeclaration() || GV->hasAvailableExternallyLinkage();
1296   if (GV->hasHiddenVisibility() && (!isDecl && !GV->hasCommonLinkage()))
1297     return false;
1298   return RelocM != Reloc::Static && (isDecl || GV->isWeakForLinker());
1299 }
1300
1301 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
1302                                                     SelectionDAG &DAG) {
1303   EVT PtrVT = getPointerTy();
1304   DebugLoc dl = Op.getDebugLoc();
1305   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1306   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1307   bool IsIndirect = GVIsIndirectSymbol(GV, RelocM);
1308   SDValue CPAddr;
1309   if (RelocM == Reloc::Static)
1310     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1311   else {
1312     unsigned PCAdj = (RelocM != Reloc::PIC_)
1313       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1314     ARMCP::ARMCPKind Kind = IsIndirect ? ARMCP::CPNonLazyPtr
1315       : ARMCP::CPValue;
1316     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
1317                                                          Kind, PCAdj);
1318     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1319   }
1320   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1321
1322   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1323   SDValue Chain = Result.getValue(1);
1324
1325   if (RelocM == Reloc::PIC_) {
1326     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1327     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1328   }
1329   if (IsIndirect)
1330     Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1331
1332   return Result;
1333 }
1334
1335 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
1336                                                     SelectionDAG &DAG){
1337   assert(Subtarget->isTargetELF() &&
1338          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
1339   EVT PtrVT = getPointerTy();
1340   DebugLoc dl = Op.getDebugLoc();
1341   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1342   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(*DAG.getContext(),
1343                                                        "_GLOBAL_OFFSET_TABLE_",
1344                                                        ARMPCLabelIndex,
1345                                                        ARMCP::CPValue, PCAdj);
1346   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1347   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1348   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1349   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1350   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1351 }
1352
1353 static SDValue LowerNeonVLDIntrinsic(SDValue Op, SelectionDAG &DAG,
1354                                      unsigned Opcode) {
1355   SDNode *Node = Op.getNode();
1356   EVT VT = Node->getValueType(0);
1357   DebugLoc dl = Op.getDebugLoc();
1358
1359   if (!VT.is64BitVector())
1360     return SDValue(); // unimplemented
1361
1362   SDValue Ops[] = { Node->getOperand(0),
1363                     Node->getOperand(2) };
1364   return DAG.getNode(Opcode, dl, Node->getVTList(), Ops, 2);
1365 }
1366
1367 static SDValue LowerNeonVSTIntrinsic(SDValue Op, SelectionDAG &DAG,
1368                                      unsigned Opcode, unsigned NumVecs) {
1369   SDNode *Node = Op.getNode();
1370   EVT VT = Node->getOperand(3).getValueType();
1371   DebugLoc dl = Op.getDebugLoc();
1372
1373   if (!VT.is64BitVector())
1374     return SDValue(); // unimplemented
1375
1376   SmallVector<SDValue, 6> Ops;
1377   Ops.push_back(Node->getOperand(0));
1378   Ops.push_back(Node->getOperand(2));
1379   for (unsigned N = 0; N < NumVecs; ++N)
1380     Ops.push_back(Node->getOperand(N + 3));
1381   return DAG.getNode(Opcode, dl, MVT::Other, Ops.data(), Ops.size());
1382 }
1383
1384 SDValue
1385 ARMTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
1386   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1387   switch (IntNo) {
1388   case Intrinsic::arm_neon_vld2:
1389     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD2D);
1390   case Intrinsic::arm_neon_vld3:
1391     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD3D);
1392   case Intrinsic::arm_neon_vld4:
1393     return LowerNeonVLDIntrinsic(Op, DAG, ARMISD::VLD4D);
1394   case Intrinsic::arm_neon_vst2:
1395     return LowerNeonVSTIntrinsic(Op, DAG, ARMISD::VST2D, 2);
1396   case Intrinsic::arm_neon_vst3:
1397     return LowerNeonVSTIntrinsic(Op, DAG, ARMISD::VST3D, 3);
1398   case Intrinsic::arm_neon_vst4:
1399     return LowerNeonVSTIntrinsic(Op, DAG, ARMISD::VST4D, 4);
1400   default: return SDValue();    // Don't custom lower most intrinsics.
1401   }
1402 }
1403
1404 SDValue
1405 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
1406   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1407   DebugLoc dl = Op.getDebugLoc();
1408   switch (IntNo) {
1409   default: return SDValue();    // Don't custom lower most intrinsics.
1410   case Intrinsic::arm_thread_pointer: {
1411     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1412     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1413   }
1414   case Intrinsic::eh_sjlj_lsda: {
1415     // blah. horrible, horrible hack with the forced magic name.
1416     // really need to clean this up. It belongs in the target-independent
1417     // layer somehow that doesn't require the coupling with the asm
1418     // printer.
1419     MachineFunction &MF = DAG.getMachineFunction();
1420     EVT PtrVT = getPointerTy();
1421     DebugLoc dl = Op.getDebugLoc();
1422     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1423     SDValue CPAddr;
1424     unsigned PCAdj = (RelocM != Reloc::PIC_)
1425       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1426     ARMCP::ARMCPKind Kind = ARMCP::CPValue;
1427     // Save off the LSDA name for the AsmPrinter to use when it's time
1428     // to emit the table
1429     std::string LSDAName = "L_lsda_";
1430     LSDAName += MF.getFunction()->getName();
1431     ARMConstantPoolValue *CPV =
1432       new ARMConstantPoolValue(*DAG.getContext(), LSDAName.c_str(), 
1433                                ARMPCLabelIndex, Kind, PCAdj);
1434     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1435     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1436     SDValue Result =
1437       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1438     SDValue Chain = Result.getValue(1);
1439
1440     if (RelocM == Reloc::PIC_) {
1441       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1442       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1443     }
1444     return Result;
1445   }
1446   case Intrinsic::eh_sjlj_setjmp:
1447     return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32, Op.getOperand(1));
1448   }
1449 }
1450
1451 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1452                             unsigned VarArgsFrameIndex) {
1453   // vastart just stores the address of the VarArgsFrameIndex slot into the
1454   // memory location argument.
1455   DebugLoc dl = Op.getDebugLoc();
1456   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1457   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1458   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1459   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1460 }
1461
1462 SDValue
1463 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1464   SDNode *Node = Op.getNode();
1465   DebugLoc dl = Node->getDebugLoc();
1466   EVT VT = Node->getValueType(0);
1467   SDValue Chain = Op.getOperand(0);
1468   SDValue Size  = Op.getOperand(1);
1469   SDValue Align = Op.getOperand(2);
1470
1471   // Chain the dynamic stack allocation so that it doesn't modify the stack
1472   // pointer when other instructions are using the stack.
1473   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1474
1475   unsigned AlignVal = cast<ConstantSDNode>(Align)->getZExtValue();
1476   unsigned StackAlign = getTargetMachine().getFrameInfo()->getStackAlignment();
1477   if (AlignVal > StackAlign)
1478     // Do this now since selection pass cannot introduce new target
1479     // independent node.
1480     Align = DAG.getConstant(-(uint64_t)AlignVal, VT);
1481
1482   // In Thumb1 mode, there isn't a "sub r, sp, r" instruction, we will end up
1483   // using a "add r, sp, r" instead. Negate the size now so we don't have to
1484   // do even more horrible hack later.
1485   MachineFunction &MF = DAG.getMachineFunction();
1486   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1487   if (AFI->isThumb1OnlyFunction()) {
1488     bool Negate = true;
1489     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Size);
1490     if (C) {
1491       uint32_t Val = C->getZExtValue();
1492       if (Val <= 508 && ((Val & 3) == 0))
1493         Negate = false;
1494     }
1495     if (Negate)
1496       Size = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, VT), Size);
1497   }
1498
1499   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1500   SDValue Ops1[] = { Chain, Size, Align };
1501   SDValue Res = DAG.getNode(ARMISD::DYN_ALLOC, dl, VTList, Ops1, 3);
1502   Chain = Res.getValue(1);
1503   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1504                              DAG.getIntPtrConstant(0, true), SDValue());
1505   SDValue Ops2[] = { Res, Chain };
1506   return DAG.getMergeValues(Ops2, 2, dl);
1507 }
1508
1509 SDValue
1510 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
1511                                         SDValue &Root, SelectionDAG &DAG,
1512                                         DebugLoc dl) {
1513   MachineFunction &MF = DAG.getMachineFunction();
1514   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1515
1516   TargetRegisterClass *RC;
1517   if (AFI->isThumb1OnlyFunction())
1518     RC = ARM::tGPRRegisterClass;
1519   else
1520     RC = ARM::GPRRegisterClass;
1521
1522   // Transform the arguments stored in physical registers into virtual ones.
1523   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1524   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1525
1526   SDValue ArgValue2;
1527   if (NextVA.isMemLoc()) {
1528     unsigned ArgSize = NextVA.getLocVT().getSizeInBits()/8;
1529     MachineFrameInfo *MFI = MF.getFrameInfo();
1530     int FI = MFI->CreateFixedObject(ArgSize, NextVA.getLocMemOffset());
1531
1532     // Create load node to retrieve arguments from the stack.
1533     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1534     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
1535   } else {
1536     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
1537     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1538   }
1539
1540   return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, ArgValue, ArgValue2);
1541 }
1542
1543 SDValue
1544 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
1545                                         unsigned CallConv, bool isVarArg,
1546                                         const SmallVectorImpl<ISD::InputArg>
1547                                           &Ins,
1548                                         DebugLoc dl, SelectionDAG &DAG,
1549                                         SmallVectorImpl<SDValue> &InVals) {
1550
1551   MachineFunction &MF = DAG.getMachineFunction();
1552   MachineFrameInfo *MFI = MF.getFrameInfo();
1553
1554   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1555
1556   // Assign locations to all of the incoming arguments.
1557   SmallVector<CCValAssign, 16> ArgLocs;
1558   CCState CCInfo(CallConv, isVarArg, getTargetMachine(), ArgLocs,
1559                  *DAG.getContext());
1560   CCInfo.AnalyzeFormalArguments(Ins,
1561                                 CCAssignFnForNode(CallConv, /* Return*/ false,
1562                                                   isVarArg));
1563
1564   SmallVector<SDValue, 16> ArgValues;
1565
1566   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1567     CCValAssign &VA = ArgLocs[i];
1568
1569     // Arguments stored in registers.
1570     if (VA.isRegLoc()) {
1571       EVT RegVT = VA.getLocVT();
1572
1573       SDValue ArgValue;
1574       if (VA.needsCustom()) {
1575         // f64 and vector types are split up into multiple registers or
1576         // combinations of registers and stack slots.
1577         RegVT = MVT::i32;
1578
1579         if (VA.getLocVT() == MVT::v2f64) {
1580           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
1581                                                    Chain, DAG, dl);
1582           VA = ArgLocs[++i]; // skip ahead to next loc
1583           SDValue ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
1584                                                    Chain, DAG, dl);
1585           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1586           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1587                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
1588           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
1589                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
1590         } else
1591           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
1592
1593       } else {
1594         TargetRegisterClass *RC;
1595
1596         if (RegVT == MVT::f32)
1597           RC = ARM::SPRRegisterClass;
1598         else if (RegVT == MVT::f64)
1599           RC = ARM::DPRRegisterClass;
1600         else if (RegVT == MVT::v2f64)
1601           RC = ARM::QPRRegisterClass;
1602         else if (RegVT == MVT::i32)
1603           RC = (AFI->isThumb1OnlyFunction() ?
1604                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
1605         else
1606           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1607
1608         // Transform the arguments in physical registers into virtual ones.
1609         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1610         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1611       }
1612
1613       // If this is an 8 or 16-bit value, it is really passed promoted
1614       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1615       // truncate to the right size.
1616       switch (VA.getLocInfo()) {
1617       default: llvm_unreachable("Unknown loc info!");
1618       case CCValAssign::Full: break;
1619       case CCValAssign::BCvt:
1620         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1621         break;
1622       case CCValAssign::SExt:
1623         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1624                                DAG.getValueType(VA.getValVT()));
1625         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1626         break;
1627       case CCValAssign::ZExt:
1628         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1629                                DAG.getValueType(VA.getValVT()));
1630         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1631         break;
1632       }
1633
1634       InVals.push_back(ArgValue);
1635
1636     } else { // VA.isRegLoc()
1637
1638       // sanity check
1639       assert(VA.isMemLoc());
1640       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1641
1642       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1643       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1644
1645       // Create load nodes to retrieve arguments from the stack.
1646       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1647       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, NULL, 0));
1648     }
1649   }
1650
1651   // varargs
1652   if (isVarArg) {
1653     static const unsigned GPRArgRegs[] = {
1654       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1655     };
1656
1657     unsigned NumGPRs = CCInfo.getFirstUnallocated
1658       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1659
1660     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1661     unsigned VARegSize = (4 - NumGPRs) * 4;
1662     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1663     unsigned ArgOffset = 0;
1664     if (VARegSaveSize) {
1665       // If this function is vararg, store any remaining integer argument regs
1666       // to their spots on the stack so that they may be loaded by deferencing
1667       // the result of va_next.
1668       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1669       ArgOffset = CCInfo.getNextStackOffset();
1670       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1671                                                  VARegSaveSize - VARegSize);
1672       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1673
1674       SmallVector<SDValue, 4> MemOps;
1675       for (; NumGPRs < 4; ++NumGPRs) {
1676         TargetRegisterClass *RC;
1677         if (AFI->isThumb1OnlyFunction())
1678           RC = ARM::tGPRRegisterClass;
1679         else
1680           RC = ARM::GPRRegisterClass;
1681
1682         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1683         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
1684         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1685         MemOps.push_back(Store);
1686         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1687                           DAG.getConstant(4, getPointerTy()));
1688       }
1689       if (!MemOps.empty())
1690         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1691                             &MemOps[0], MemOps.size());
1692     } else
1693       // This will point to the next argument passed via stack.
1694       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1695   }
1696
1697   return Chain;
1698 }
1699
1700 /// isFloatingPointZero - Return true if this is +0.0.
1701 static bool isFloatingPointZero(SDValue Op) {
1702   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1703     return CFP->getValueAPF().isPosZero();
1704   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1705     // Maybe this has already been legalized into the constant pool?
1706     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1707       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1708       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1709         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1710           return CFP->getValueAPF().isPosZero();
1711     }
1712   }
1713   return false;
1714 }
1715
1716 static bool isLegalCmpImmediate(unsigned C, bool isThumb1Only) {
1717   return ( isThumb1Only && (C & ~255U) == 0) ||
1718          (!isThumb1Only && ARM_AM::getSOImmVal(C) != -1);
1719 }
1720
1721 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1722 /// the given operands.
1723 static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1724                          SDValue &ARMCC, SelectionDAG &DAG, bool isThumb1Only,
1725                          DebugLoc dl) {
1726   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1727     unsigned C = RHSC->getZExtValue();
1728     if (!isLegalCmpImmediate(C, isThumb1Only)) {
1729       // Constant does not fit, try adjusting it by one?
1730       switch (CC) {
1731       default: break;
1732       case ISD::SETLT:
1733       case ISD::SETGE:
1734         if (isLegalCmpImmediate(C-1, isThumb1Only)) {
1735           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1736           RHS = DAG.getConstant(C-1, MVT::i32);
1737         }
1738         break;
1739       case ISD::SETULT:
1740       case ISD::SETUGE:
1741         if (C > 0 && isLegalCmpImmediate(C-1, isThumb1Only)) {
1742           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1743           RHS = DAG.getConstant(C-1, MVT::i32);
1744         }
1745         break;
1746       case ISD::SETLE:
1747       case ISD::SETGT:
1748         if (isLegalCmpImmediate(C+1, isThumb1Only)) {
1749           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1750           RHS = DAG.getConstant(C+1, MVT::i32);
1751         }
1752         break;
1753       case ISD::SETULE:
1754       case ISD::SETUGT:
1755         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb1Only)) {
1756           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1757           RHS = DAG.getConstant(C+1, MVT::i32);
1758         }
1759         break;
1760       }
1761     }
1762   }
1763
1764   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1765   ARMISD::NodeType CompareType;
1766   switch (CondCode) {
1767   default:
1768     CompareType = ARMISD::CMP;
1769     break;
1770   case ARMCC::EQ:
1771   case ARMCC::NE:
1772     // Uses only Z Flag
1773     CompareType = ARMISD::CMPZ;
1774     break;
1775   }
1776   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1777   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1778 }
1779
1780 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1781 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1782                          DebugLoc dl) {
1783   SDValue Cmp;
1784   if (!isFloatingPointZero(RHS))
1785     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1786   else
1787     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1788   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1789 }
1790
1791 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1792                               const ARMSubtarget *ST) {
1793   EVT VT = Op.getValueType();
1794   SDValue LHS = Op.getOperand(0);
1795   SDValue RHS = Op.getOperand(1);
1796   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1797   SDValue TrueVal = Op.getOperand(2);
1798   SDValue FalseVal = Op.getOperand(3);
1799   DebugLoc dl = Op.getDebugLoc();
1800
1801   if (LHS.getValueType() == MVT::i32) {
1802     SDValue ARMCC;
1803     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1804     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1805     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1806   }
1807
1808   ARMCC::CondCodes CondCode, CondCode2;
1809   if (FPCCToARMCC(CC, CondCode, CondCode2))
1810     std::swap(TrueVal, FalseVal);
1811
1812   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1813   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1814   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1815   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1816                                  ARMCC, CCR, Cmp);
1817   if (CondCode2 != ARMCC::AL) {
1818     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1819     // FIXME: Needs another CMP because flag can have but one use.
1820     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1821     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1822                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1823   }
1824   return Result;
1825 }
1826
1827 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1828                           const ARMSubtarget *ST) {
1829   SDValue  Chain = Op.getOperand(0);
1830   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1831   SDValue    LHS = Op.getOperand(2);
1832   SDValue    RHS = Op.getOperand(3);
1833   SDValue   Dest = Op.getOperand(4);
1834   DebugLoc dl = Op.getDebugLoc();
1835
1836   if (LHS.getValueType() == MVT::i32) {
1837     SDValue ARMCC;
1838     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1839     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb1Only(), dl);
1840     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1841                        Chain, Dest, ARMCC, CCR,Cmp);
1842   }
1843
1844   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1845   ARMCC::CondCodes CondCode, CondCode2;
1846   if (FPCCToARMCC(CC, CondCode, CondCode2))
1847     // Swap the LHS/RHS of the comparison if needed.
1848     std::swap(LHS, RHS);
1849
1850   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1851   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1852   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1853   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1854   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1855   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1856   if (CondCode2 != ARMCC::AL) {
1857     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1858     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1859     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1860   }
1861   return Res;
1862 }
1863
1864 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1865   SDValue Chain = Op.getOperand(0);
1866   SDValue Table = Op.getOperand(1);
1867   SDValue Index = Op.getOperand(2);
1868   DebugLoc dl = Op.getDebugLoc();
1869
1870   EVT PTy = getPointerTy();
1871   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1872   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1873   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
1874   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1875   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1876   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1877   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1878   if (Subtarget->isThumb2()) {
1879     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
1880     // which does another jump to the destination. This also makes it easier
1881     // to translate it to TBB / TBH later.
1882     // FIXME: This might not work if the function is extremely large.
1883     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
1884                        Addr, Op.getOperand(2), JTI, UId);
1885   }
1886   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1887     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr, NULL, 0);
1888     Chain = Addr.getValue(1);
1889     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1890     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1891   } else {
1892     Addr = DAG.getLoad(PTy, dl, Chain, Addr, NULL, 0);
1893     Chain = Addr.getValue(1);
1894     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1895   }
1896 }
1897
1898 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1899   DebugLoc dl = Op.getDebugLoc();
1900   unsigned Opc =
1901     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1902   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1903   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1904 }
1905
1906 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1907   EVT VT = Op.getValueType();
1908   DebugLoc dl = Op.getDebugLoc();
1909   unsigned Opc =
1910     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1911
1912   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1913   return DAG.getNode(Opc, dl, VT, Op);
1914 }
1915
1916 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1917   // Implement fcopysign with a fabs and a conditional fneg.
1918   SDValue Tmp0 = Op.getOperand(0);
1919   SDValue Tmp1 = Op.getOperand(1);
1920   DebugLoc dl = Op.getDebugLoc();
1921   EVT VT = Op.getValueType();
1922   EVT SrcVT = Tmp1.getValueType();
1923   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1924   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1925   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1926   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1927   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1928 }
1929
1930 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1931   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1932   MFI->setFrameAddressIsTaken(true);
1933   EVT VT = Op.getValueType();
1934   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1935   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1936   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
1937     ? ARM::R7 : ARM::R11;
1938   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1939   while (Depth--)
1940     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1941   return FrameAddr;
1942 }
1943
1944 SDValue
1945 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1946                                            SDValue Chain,
1947                                            SDValue Dst, SDValue Src,
1948                                            SDValue Size, unsigned Align,
1949                                            bool AlwaysInline,
1950                                          const Value *DstSV, uint64_t DstSVOff,
1951                                          const Value *SrcSV, uint64_t SrcSVOff){
1952   // Do repeated 4-byte loads and stores. To be improved.
1953   // This requires 4-byte alignment.
1954   if ((Align & 3) != 0)
1955     return SDValue();
1956   // This requires the copy size to be a constant, preferrably
1957   // within a subtarget-specific limit.
1958   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1959   if (!ConstantSize)
1960     return SDValue();
1961   uint64_t SizeVal = ConstantSize->getZExtValue();
1962   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1963     return SDValue();
1964
1965   unsigned BytesLeft = SizeVal & 3;
1966   unsigned NumMemOps = SizeVal >> 2;
1967   unsigned EmittedNumMemOps = 0;
1968   EVT VT = MVT::i32;
1969   unsigned VTSize = 4;
1970   unsigned i = 0;
1971   const unsigned MAX_LOADS_IN_LDM = 6;
1972   SDValue TFOps[MAX_LOADS_IN_LDM];
1973   SDValue Loads[MAX_LOADS_IN_LDM];
1974   uint64_t SrcOff = 0, DstOff = 0;
1975
1976   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1977   // same number of stores.  The loads and stores will get combined into
1978   // ldm/stm later on.
1979   while (EmittedNumMemOps < NumMemOps) {
1980     for (i = 0;
1981          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1982       Loads[i] = DAG.getLoad(VT, dl, Chain,
1983                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1984                                          DAG.getConstant(SrcOff, MVT::i32)),
1985                              SrcSV, SrcSVOff + SrcOff);
1986       TFOps[i] = Loads[i].getValue(1);
1987       SrcOff += VTSize;
1988     }
1989     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1990
1991     for (i = 0;
1992          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1993       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1994                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1995                                        DAG.getConstant(DstOff, MVT::i32)),
1996                            DstSV, DstSVOff + DstOff);
1997       DstOff += VTSize;
1998     }
1999     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2000
2001     EmittedNumMemOps += i;
2002   }
2003
2004   if (BytesLeft == 0)
2005     return Chain;
2006
2007   // Issue loads / stores for the trailing (1 - 3) bytes.
2008   unsigned BytesLeftSave = BytesLeft;
2009   i = 0;
2010   while (BytesLeft) {
2011     if (BytesLeft >= 2) {
2012       VT = MVT::i16;
2013       VTSize = 2;
2014     } else {
2015       VT = MVT::i8;
2016       VTSize = 1;
2017     }
2018
2019     Loads[i] = DAG.getLoad(VT, dl, Chain,
2020                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
2021                                        DAG.getConstant(SrcOff, MVT::i32)),
2022                            SrcSV, SrcSVOff + SrcOff);
2023     TFOps[i] = Loads[i].getValue(1);
2024     ++i;
2025     SrcOff += VTSize;
2026     BytesLeft -= VTSize;
2027   }
2028   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2029
2030   i = 0;
2031   BytesLeft = BytesLeftSave;
2032   while (BytesLeft) {
2033     if (BytesLeft >= 2) {
2034       VT = MVT::i16;
2035       VTSize = 2;
2036     } else {
2037       VT = MVT::i8;
2038       VTSize = 1;
2039     }
2040
2041     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
2042                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
2043                                         DAG.getConstant(DstOff, MVT::i32)),
2044                             DstSV, DstSVOff + DstOff);
2045     ++i;
2046     DstOff += VTSize;
2047     BytesLeft -= VTSize;
2048   }
2049   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
2050 }
2051
2052 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
2053   SDValue Op = N->getOperand(0);
2054   DebugLoc dl = N->getDebugLoc();
2055   if (N->getValueType(0) == MVT::f64) {
2056     // Turn i64->f64 into FMDRR.
2057     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2058                              DAG.getConstant(0, MVT::i32));
2059     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
2060                              DAG.getConstant(1, MVT::i32));
2061     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
2062   }
2063
2064   // Turn f64->i64 into FMRRD.
2065   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
2066                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
2067
2068   // Merge the pieces into a single i64 value.
2069   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
2070 }
2071
2072 /// getZeroVector - Returns a vector of specified type with all zero elements.
2073 ///
2074 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2075   assert(VT.isVector() && "Expected a vector type");
2076
2077   // Zero vectors are used to represent vector negation and in those cases
2078   // will be implemented with the NEON VNEG instruction.  However, VNEG does
2079   // not support i64 elements, so sometimes the zero vectors will need to be
2080   // explicitly constructed.  For those cases, and potentially other uses in
2081   // the future, always build zero vectors as <4 x i32> or <2 x i32> bitcasted
2082   // to their dest type.  This ensures they get CSE'd.
2083   SDValue Vec;
2084   SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2085   if (VT.getSizeInBits() == 64)
2086     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2087   else
2088     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2089
2090   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2091 }
2092
2093 /// getOnesVector - Returns a vector of specified type with all bits set.
2094 ///
2095 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2096   assert(VT.isVector() && "Expected a vector type");
2097
2098   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2099   // type.  This ensures they get CSE'd.
2100   SDValue Vec;
2101   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2102   if (VT.getSizeInBits() == 64)
2103     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2104   else
2105     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2106
2107   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2108 }
2109
2110 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
2111                           const ARMSubtarget *ST) {
2112   EVT VT = N->getValueType(0);
2113   DebugLoc dl = N->getDebugLoc();
2114
2115   // Lower vector shifts on NEON to use VSHL.
2116   if (VT.isVector()) {
2117     assert(ST->hasNEON() && "unexpected vector shift");
2118
2119     // Left shifts translate directly to the vshiftu intrinsic.
2120     if (N->getOpcode() == ISD::SHL)
2121       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2122                          DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
2123                          N->getOperand(0), N->getOperand(1));
2124
2125     assert((N->getOpcode() == ISD::SRA ||
2126             N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
2127
2128     // NEON uses the same intrinsics for both left and right shifts.  For
2129     // right shifts, the shift amounts are negative, so negate the vector of
2130     // shift amounts.
2131     EVT ShiftVT = N->getOperand(1).getValueType();
2132     SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
2133                                        getZeroVector(ShiftVT, DAG, dl),
2134                                        N->getOperand(1));
2135     Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
2136                                Intrinsic::arm_neon_vshifts :
2137                                Intrinsic::arm_neon_vshiftu);
2138     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
2139                        DAG.getConstant(vshiftInt, MVT::i32),
2140                        N->getOperand(0), NegatedCount);
2141   }
2142
2143   assert(VT == MVT::i64 &&
2144          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
2145          "Unknown shift to lower!");
2146
2147   // We only lower SRA, SRL of 1 here, all others use generic lowering.
2148   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
2149       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
2150     return SDValue();
2151
2152   // If we are in thumb mode, we don't have RRX.
2153   if (ST->isThumb1Only()) return SDValue();
2154
2155   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
2156   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2157                              DAG.getConstant(0, MVT::i32));
2158   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
2159                              DAG.getConstant(1, MVT::i32));
2160
2161   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
2162   // captures the result into a carry flag.
2163   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
2164   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
2165
2166   // The low part is an ARMISD::RRX operand, which shifts the carry in.
2167   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
2168
2169   // Merge the pieces into a single i64 value.
2170  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
2171 }
2172
2173 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
2174   SDValue TmpOp0, TmpOp1;
2175   bool Invert = false;
2176   bool Swap = false;
2177   unsigned Opc = 0;
2178
2179   SDValue Op0 = Op.getOperand(0);
2180   SDValue Op1 = Op.getOperand(1);
2181   SDValue CC = Op.getOperand(2);
2182   EVT VT = Op.getValueType();
2183   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
2184   DebugLoc dl = Op.getDebugLoc();
2185
2186   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
2187     switch (SetCCOpcode) {
2188     default: llvm_unreachable("Illegal FP comparison"); break;
2189     case ISD::SETUNE:
2190     case ISD::SETNE:  Invert = true; // Fallthrough
2191     case ISD::SETOEQ:
2192     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2193     case ISD::SETOLT:
2194     case ISD::SETLT: Swap = true; // Fallthrough
2195     case ISD::SETOGT:
2196     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2197     case ISD::SETOLE:
2198     case ISD::SETLE:  Swap = true; // Fallthrough
2199     case ISD::SETOGE:
2200     case ISD::SETGE: Opc = ARMISD::VCGE; break;
2201     case ISD::SETUGE: Swap = true; // Fallthrough
2202     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
2203     case ISD::SETUGT: Swap = true; // Fallthrough
2204     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
2205     case ISD::SETUEQ: Invert = true; // Fallthrough
2206     case ISD::SETONE:
2207       // Expand this to (OLT | OGT).
2208       TmpOp0 = Op0;
2209       TmpOp1 = Op1;
2210       Opc = ISD::OR;
2211       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2212       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
2213       break;
2214     case ISD::SETUO: Invert = true; // Fallthrough
2215     case ISD::SETO:
2216       // Expand this to (OLT | OGE).
2217       TmpOp0 = Op0;
2218       TmpOp1 = Op1;
2219       Opc = ISD::OR;
2220       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
2221       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
2222       break;
2223     }
2224   } else {
2225     // Integer comparisons.
2226     switch (SetCCOpcode) {
2227     default: llvm_unreachable("Illegal integer comparison"); break;
2228     case ISD::SETNE:  Invert = true;
2229     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
2230     case ISD::SETLT:  Swap = true;
2231     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
2232     case ISD::SETLE:  Swap = true;
2233     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
2234     case ISD::SETULT: Swap = true;
2235     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
2236     case ISD::SETULE: Swap = true;
2237     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
2238     }
2239
2240     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
2241     if (Opc == ARMISD::VCEQ) {
2242
2243       SDValue AndOp;
2244       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
2245         AndOp = Op0;
2246       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
2247         AndOp = Op1;
2248
2249       // Ignore bitconvert.
2250       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BIT_CONVERT)
2251         AndOp = AndOp.getOperand(0);
2252
2253       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
2254         Opc = ARMISD::VTST;
2255         Op0 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(0));
2256         Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, VT, AndOp.getOperand(1));
2257         Invert = !Invert;
2258       }
2259     }
2260   }
2261
2262   if (Swap)
2263     std::swap(Op0, Op1);
2264
2265   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
2266
2267   if (Invert)
2268     Result = DAG.getNOT(dl, Result, VT);
2269
2270   return Result;
2271 }
2272
2273 /// isVMOVSplat - Check if the specified splat value corresponds to an immediate
2274 /// VMOV instruction, and if so, return the constant being splatted.
2275 static SDValue isVMOVSplat(uint64_t SplatBits, uint64_t SplatUndef,
2276                            unsigned SplatBitSize, SelectionDAG &DAG) {
2277   switch (SplatBitSize) {
2278   case 8:
2279     // Any 1-byte value is OK.
2280     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2281     return DAG.getTargetConstant(SplatBits, MVT::i8);
2282
2283   case 16:
2284     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
2285     if ((SplatBits & ~0xff) == 0 ||
2286         (SplatBits & ~0xff00) == 0)
2287       return DAG.getTargetConstant(SplatBits, MVT::i16);
2288     break;
2289
2290   case 32:
2291     // NEON's 32-bit VMOV supports splat values where:
2292     // * only one byte is nonzero, or
2293     // * the least significant byte is 0xff and the second byte is nonzero, or
2294     // * the least significant 2 bytes are 0xff and the third is nonzero.
2295     if ((SplatBits & ~0xff) == 0 ||
2296         (SplatBits & ~0xff00) == 0 ||
2297         (SplatBits & ~0xff0000) == 0 ||
2298         (SplatBits & ~0xff000000) == 0)
2299       return DAG.getTargetConstant(SplatBits, MVT::i32);
2300
2301     if ((SplatBits & ~0xffff) == 0 &&
2302         ((SplatBits | SplatUndef) & 0xff) == 0xff)
2303       return DAG.getTargetConstant(SplatBits | 0xff, MVT::i32);
2304
2305     if ((SplatBits & ~0xffffff) == 0 &&
2306         ((SplatBits | SplatUndef) & 0xffff) == 0xffff)
2307       return DAG.getTargetConstant(SplatBits | 0xffff, MVT::i32);
2308
2309     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
2310     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
2311     // VMOV.I32.  A (very) minor optimization would be to replicate the value
2312     // and fall through here to test for a valid 64-bit splat.  But, then the
2313     // caller would also need to check and handle the change in size.
2314     break;
2315
2316   case 64: {
2317     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
2318     uint64_t BitMask = 0xff;
2319     uint64_t Val = 0;
2320     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2321       if (((SplatBits | SplatUndef) & BitMask) == BitMask)
2322         Val |= BitMask;
2323       else if ((SplatBits & BitMask) != 0)
2324         return SDValue();
2325       BitMask <<= 8;
2326     }
2327     return DAG.getTargetConstant(Val, MVT::i64);
2328   }
2329
2330   default:
2331     llvm_unreachable("unexpected size for isVMOVSplat");
2332     break;
2333   }
2334
2335   return SDValue();
2336 }
2337
2338 /// getVMOVImm - If this is a build_vector of constants which can be
2339 /// formed by using a VMOV instruction of the specified element size,
2340 /// return the constant being splatted.  The ByteSize field indicates the
2341 /// number of bytes of each element [1248].
2342 SDValue ARM::getVMOVImm(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2343   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N);
2344   APInt SplatBits, SplatUndef;
2345   unsigned SplatBitSize;
2346   bool HasAnyUndefs;
2347   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
2348                                       HasAnyUndefs, ByteSize * 8))
2349     return SDValue();
2350
2351   if (SplatBitSize > ByteSize * 8)
2352     return SDValue();
2353
2354   return isVMOVSplat(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
2355                      SplatBitSize, DAG);
2356 }
2357
2358 static bool isVEXTMask(const SmallVectorImpl<int> &M, EVT VT,
2359                        bool &ReverseVEXT, unsigned &Imm) {
2360   unsigned NumElts = VT.getVectorNumElements();
2361   ReverseVEXT = false;
2362   Imm = M[0];
2363
2364   // If this is a VEXT shuffle, the immediate value is the index of the first
2365   // element.  The other shuffle indices must be the successive elements after
2366   // the first one.
2367   unsigned ExpectedElt = Imm;
2368   for (unsigned i = 1; i < NumElts; ++i) {
2369     // Increment the expected index.  If it wraps around, it may still be
2370     // a VEXT but the source vectors must be swapped.
2371     ExpectedElt += 1;
2372     if (ExpectedElt == NumElts * 2) {
2373       ExpectedElt = 0;
2374       ReverseVEXT = true;
2375     }
2376
2377     if (ExpectedElt != static_cast<unsigned>(M[i]))
2378       return false;
2379   }
2380
2381   // Adjust the index value if the source operands will be swapped.
2382   if (ReverseVEXT)
2383     Imm -= NumElts;
2384
2385   return true;
2386 }
2387
2388 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
2389 /// instruction with the specified blocksize.  (The order of the elements
2390 /// within each block of the vector is reversed.)
2391 static bool isVREVMask(const SmallVectorImpl<int> &M, EVT VT,
2392                        unsigned BlockSize) {
2393   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
2394          "Only possible block sizes for VREV are: 16, 32, 64");
2395
2396   unsigned NumElts = VT.getVectorNumElements();
2397   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
2398   unsigned BlockElts = M[0] + 1;
2399
2400   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
2401     return false;
2402
2403   for (unsigned i = 0; i < NumElts; ++i) {
2404     if ((unsigned) M[i] !=
2405         (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
2406       return false;
2407   }
2408
2409   return true;
2410 }
2411
2412 static SDValue BuildSplat(SDValue Val, EVT VT, SelectionDAG &DAG, DebugLoc dl) {
2413   // Canonicalize all-zeros and all-ones vectors.
2414   ConstantSDNode *ConstVal = cast<ConstantSDNode>(Val.getNode());
2415   if (ConstVal->isNullValue())
2416     return getZeroVector(VT, DAG, dl);
2417   if (ConstVal->isAllOnesValue())
2418     return getOnesVector(VT, DAG, dl);
2419
2420   EVT CanonicalVT;
2421   if (VT.is64BitVector()) {
2422     switch (Val.getValueType().getSizeInBits()) {
2423     case 8:  CanonicalVT = MVT::v8i8; break;
2424     case 16: CanonicalVT = MVT::v4i16; break;
2425     case 32: CanonicalVT = MVT::v2i32; break;
2426     case 64: CanonicalVT = MVT::v1i64; break;
2427     default: llvm_unreachable("unexpected splat element type"); break;
2428     }
2429   } else {
2430     assert(VT.is128BitVector() && "unknown splat vector size");
2431     switch (Val.getValueType().getSizeInBits()) {
2432     case 8:  CanonicalVT = MVT::v16i8; break;
2433     case 16: CanonicalVT = MVT::v8i16; break;
2434     case 32: CanonicalVT = MVT::v4i32; break;
2435     case 64: CanonicalVT = MVT::v2i64; break;
2436     default: llvm_unreachable("unexpected splat element type"); break;
2437     }
2438   }
2439
2440   // Build a canonical splat for this value.
2441   SmallVector<SDValue, 8> Ops;
2442   Ops.assign(CanonicalVT.getVectorNumElements(), Val);
2443   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, &Ops[0],
2444                             Ops.size());
2445   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Res);
2446 }
2447
2448 // If this is a case we can't handle, return null and let the default
2449 // expansion code take care of it.
2450 static SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
2451   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
2452   DebugLoc dl = Op.getDebugLoc();
2453   EVT VT = Op.getValueType();
2454
2455   APInt SplatBits, SplatUndef;
2456   unsigned SplatBitSize;
2457   bool HasAnyUndefs;
2458   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
2459     SDValue Val = isVMOVSplat(SplatBits.getZExtValue(),
2460                               SplatUndef.getZExtValue(), SplatBitSize, DAG);
2461     if (Val.getNode())
2462       return BuildSplat(Val, VT, DAG, dl);
2463   }
2464
2465   // If there are only 2 elements in a 128-bit vector, insert them into an
2466   // undef vector.  This handles the common case for 128-bit vector argument
2467   // passing, where the insertions should be translated to subreg accesses
2468   // with no real instructions.
2469   if (VT.is128BitVector() && Op.getNumOperands() == 2) {
2470     SDValue Val = DAG.getUNDEF(VT);
2471     SDValue Op0 = Op.getOperand(0);
2472     SDValue Op1 = Op.getOperand(1);
2473     if (Op0.getOpcode() != ISD::UNDEF)
2474       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op0,
2475                         DAG.getIntPtrConstant(0));
2476     if (Op1.getOpcode() != ISD::UNDEF)
2477       Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, Op1,
2478                         DAG.getIntPtrConstant(1));
2479     return Val;
2480   }
2481
2482   return SDValue();
2483 }
2484
2485 /// isShuffleMaskLegal - Targets can use this to indicate that they only
2486 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
2487 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
2488 /// are assumed to be legal.
2489 bool
2490 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
2491                                       EVT VT) const {
2492   if (VT.getVectorNumElements() == 4 &&
2493       (VT.is128BitVector() || VT.is64BitVector())) {
2494     unsigned PFIndexes[4];
2495     for (unsigned i = 0; i != 4; ++i) {
2496       if (M[i] < 0)
2497         PFIndexes[i] = 8;
2498       else
2499         PFIndexes[i] = M[i];
2500     }
2501
2502     // Compute the index in the perfect shuffle table.
2503     unsigned PFTableIndex =
2504       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2505     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2506     unsigned Cost = (PFEntry >> 30);
2507
2508     if (Cost <= 4)
2509       return true;
2510   }
2511
2512   bool ReverseVEXT;
2513   unsigned Imm;
2514
2515   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
2516           isVREVMask(M, VT, 64) ||
2517           isVREVMask(M, VT, 32) ||
2518           isVREVMask(M, VT, 16) ||
2519           isVEXTMask(M, VT, ReverseVEXT, Imm));
2520 }
2521
2522 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
2523 /// the specified operations to build the shuffle.
2524 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
2525                                       SDValue RHS, SelectionDAG &DAG,
2526                                       DebugLoc dl) {
2527   unsigned OpNum = (PFEntry >> 26) & 0x0F;
2528   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
2529   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
2530
2531   enum {
2532     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
2533     OP_VREV,
2534     OP_VDUP0,
2535     OP_VDUP1,
2536     OP_VDUP2,
2537     OP_VDUP3,
2538     OP_VEXT1,
2539     OP_VEXT2,
2540     OP_VEXT3,
2541     OP_VUZPL, // VUZP, left result
2542     OP_VUZPR, // VUZP, right result
2543     OP_VZIPL, // VZIP, left result
2544     OP_VZIPR, // VZIP, right result
2545     OP_VTRNL, // VTRN, left result
2546     OP_VTRNR  // VTRN, right result
2547   };
2548
2549   if (OpNum == OP_COPY) {
2550     if (LHSID == (1*9+2)*9+3) return LHS;
2551     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
2552     return RHS;
2553   }
2554
2555   SDValue OpLHS, OpRHS;
2556   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
2557   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
2558   EVT VT = OpLHS.getValueType();
2559
2560   switch (OpNum) {
2561   default: llvm_unreachable("Unknown shuffle opcode!");
2562   case OP_VREV:
2563     return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
2564   case OP_VDUP0:
2565   case OP_VDUP1:
2566   case OP_VDUP2:
2567   case OP_VDUP3:
2568     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
2569                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0+1, MVT::i32));
2570   case OP_VEXT1:
2571   case OP_VEXT2:
2572   case OP_VEXT3:
2573     return DAG.getNode(ARMISD::VEXT, dl, VT,
2574                        OpLHS, OpRHS,
2575                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
2576   case OP_VUZPL:
2577   case OP_VUZPR:
2578     return DAG.getNode(VT.is64BitVector() ? ARMISD::VUZP16 : ARMISD::VUZP32,
2579                        dl, DAG.getVTList(VT, VT),
2580                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
2581   case OP_VZIPL:
2582   case OP_VZIPR:
2583     return DAG.getNode(VT.is64BitVector() ? ARMISD::VZIP16 : ARMISD::VZIP32,
2584                        dl, DAG.getVTList(VT, VT),
2585                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
2586   case OP_VTRNL:
2587   case OP_VTRNR:
2588     return DAG.getNode(VT.is64BitVector() ? ARMISD::VTRN16 : ARMISD::VTRN32,
2589                        dl, DAG.getVTList(VT, VT),
2590                        OpLHS, OpRHS).getValue(0);
2591   }
2592 }
2593
2594 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
2595   SDValue V1 = Op.getOperand(0);
2596   SDValue V2 = Op.getOperand(1);
2597   DebugLoc dl = Op.getDebugLoc();
2598   EVT VT = Op.getValueType();
2599   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2600   SmallVector<int, 8> ShuffleMask;
2601
2602   // Convert shuffles that are directly supported on NEON to target-specific
2603   // DAG nodes, instead of keeping them as shuffles and matching them again
2604   // during code selection.  This is more efficient and avoids the possibility
2605   // of inconsistencies between legalization and selection.
2606   // FIXME: floating-point vectors should be canonicalized to integer vectors
2607   // of the same time so that they get CSEd properly.
2608   SVN->getMask(ShuffleMask);
2609
2610   if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
2611     int Lane = SVN->getSplatIndex();
2612     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
2613       return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
2614     }
2615     return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
2616                        DAG.getConstant(Lane, MVT::i32));
2617   }
2618
2619   bool ReverseVEXT;
2620   unsigned Imm;
2621   if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
2622     SDValue Op0 = SVN->getOperand(0);
2623     SDValue Op1 = SVN->getOperand(1);
2624     if (ReverseVEXT)
2625       std::swap(Op0, Op1);
2626     return DAG.getNode(ARMISD::VEXT, dl, VT, Op0, Op1,
2627                        DAG.getConstant(Imm, MVT::i32));
2628   }
2629
2630   if (isVREVMask(ShuffleMask, VT, 64))
2631     return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
2632   if (isVREVMask(ShuffleMask, VT, 32))
2633     return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
2634   if (isVREVMask(ShuffleMask, VT, 16))
2635     return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
2636
2637   if (VT.getVectorNumElements() == 4 &&
2638       (VT.is128BitVector() || VT.is64BitVector())) {
2639     unsigned PFIndexes[4];
2640     for (unsigned i = 0; i != 4; ++i) {
2641       if (ShuffleMask[i] < 0)
2642         PFIndexes[i] = 8;
2643       else
2644         PFIndexes[i] = ShuffleMask[i];
2645     }
2646
2647     // Compute the index in the perfect shuffle table.
2648     unsigned PFTableIndex =
2649       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
2650
2651     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
2652     unsigned Cost = (PFEntry >> 30);
2653
2654     if (Cost <= 4)
2655       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
2656   }
2657
2658   return SDValue();
2659 }
2660
2661 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
2662   return Op;
2663 }
2664
2665 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
2666   EVT VT = Op.getValueType();
2667   DebugLoc dl = Op.getDebugLoc();
2668   assert((VT == MVT::i8 || VT == MVT::i16) &&
2669          "unexpected type for custom-lowering vector extract");
2670   SDValue Vec = Op.getOperand(0);
2671   SDValue Lane = Op.getOperand(1);
2672   Op = DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
2673   Op = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Op, DAG.getValueType(VT));
2674   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
2675 }
2676
2677 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
2678   // The only time a CONCAT_VECTORS operation can have legal types is when
2679   // two 64-bit vectors are concatenated to a 128-bit vector.
2680   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
2681          "unexpected CONCAT_VECTORS");
2682   DebugLoc dl = Op.getDebugLoc();
2683   SDValue Val = DAG.getUNDEF(MVT::v2f64);
2684   SDValue Op0 = Op.getOperand(0);
2685   SDValue Op1 = Op.getOperand(1);
2686   if (Op0.getOpcode() != ISD::UNDEF)
2687     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2688                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op0),
2689                       DAG.getIntPtrConstant(0));
2690   if (Op1.getOpcode() != ISD::UNDEF)
2691     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
2692                       DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, Op1),
2693                       DAG.getIntPtrConstant(1));
2694   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Val);
2695 }
2696
2697 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
2698   switch (Op.getOpcode()) {
2699   default: llvm_unreachable("Don't know how to custom lower this!");
2700   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
2701   case ISD::GlobalAddress:
2702     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
2703       LowerGlobalAddressELF(Op, DAG);
2704   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
2705   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
2706   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
2707   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
2708   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
2709   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
2710   case ISD::SINT_TO_FP:
2711   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
2712   case ISD::FP_TO_SINT:
2713   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
2714   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
2715   case ISD::RETURNADDR:    break;
2716   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
2717   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
2718   case ISD::INTRINSIC_VOID:
2719   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
2720   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2721   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
2722   case ISD::SHL:
2723   case ISD::SRL:
2724   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
2725   case ISD::VSETCC:        return LowerVSETCC(Op, DAG);
2726   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG);
2727   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2728   case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
2729   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2730   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
2731   }
2732   return SDValue();
2733 }
2734
2735 /// ReplaceNodeResults - Replace the results of node with an illegal result
2736 /// type with new values built out of custom code.
2737 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
2738                                            SmallVectorImpl<SDValue>&Results,
2739                                            SelectionDAG &DAG) {
2740   switch (N->getOpcode()) {
2741   default:
2742     llvm_unreachable("Don't know how to custom expand this!");
2743     return;
2744   case ISD::BIT_CONVERT:
2745     Results.push_back(ExpandBIT_CONVERT(N, DAG));
2746     return;
2747   case ISD::SRL:
2748   case ISD::SRA: {
2749     SDValue Res = LowerShift(N, DAG, Subtarget);
2750     if (Res.getNode())
2751       Results.push_back(Res);
2752     return;
2753   }
2754   }
2755 }
2756
2757 //===----------------------------------------------------------------------===//
2758 //                           ARM Scheduler Hooks
2759 //===----------------------------------------------------------------------===//
2760
2761 MachineBasicBlock *
2762 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
2763                                                MachineBasicBlock *BB) const {
2764   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2765   DebugLoc dl = MI->getDebugLoc();
2766   switch (MI->getOpcode()) {
2767   default:
2768     llvm_unreachable("Unexpected instr type to insert");
2769   case ARM::tMOVCCr_pseudo: {
2770     // To "insert" a SELECT_CC instruction, we actually have to insert the
2771     // diamond control-flow pattern.  The incoming instruction knows the
2772     // destination vreg to set, the condition code register to branch on, the
2773     // true/false values to select between, and a branch opcode to use.
2774     const BasicBlock *LLVM_BB = BB->getBasicBlock();
2775     MachineFunction::iterator It = BB;
2776     ++It;
2777
2778     //  thisMBB:
2779     //  ...
2780     //   TrueVal = ...
2781     //   cmpTY ccX, r1, r2
2782     //   bCC copy1MBB
2783     //   fallthrough --> copy0MBB
2784     MachineBasicBlock *thisMBB  = BB;
2785     MachineFunction *F = BB->getParent();
2786     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
2787     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
2788     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
2789       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
2790     F->insert(It, copy0MBB);
2791     F->insert(It, sinkMBB);
2792     // Update machine-CFG edges by first adding all successors of the current
2793     // block to the new block which will contain the Phi node for the select.
2794     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
2795         e = BB->succ_end(); i != e; ++i)
2796       sinkMBB->addSuccessor(*i);
2797     // Next, remove all successors of the current block, and add the true
2798     // and fallthrough blocks as its successors.
2799     while(!BB->succ_empty())
2800       BB->removeSuccessor(BB->succ_begin());
2801     BB->addSuccessor(copy0MBB);
2802     BB->addSuccessor(sinkMBB);
2803
2804     //  copy0MBB:
2805     //   %FalseValue = ...
2806     //   # fallthrough to sinkMBB
2807     BB = copy0MBB;
2808
2809     // Update machine-CFG edges
2810     BB->addSuccessor(sinkMBB);
2811
2812     //  sinkMBB:
2813     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
2814     //  ...
2815     BB = sinkMBB;
2816     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
2817       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
2818       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
2819
2820     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2821     return BB;
2822   }
2823
2824   case ARM::tANDsp:
2825   case ARM::tADDspr_:
2826   case ARM::tSUBspi_:
2827   case ARM::t2SUBrSPi_:
2828   case ARM::t2SUBrSPi12_:
2829   case ARM::t2SUBrSPs_: {
2830     MachineFunction *MF = BB->getParent();
2831     unsigned DstReg = MI->getOperand(0).getReg();
2832     unsigned SrcReg = MI->getOperand(1).getReg();
2833     bool DstIsDead = MI->getOperand(0).isDead();
2834     bool SrcIsKill = MI->getOperand(1).isKill();
2835
2836     if (SrcReg != ARM::SP) {
2837       // Copy the source to SP from virtual register.
2838       const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(SrcReg);
2839       unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
2840         ? ARM::tMOVtgpr2gpr : ARM::tMOVgpr2gpr;
2841       BuildMI(BB, dl, TII->get(CopyOpc), ARM::SP)
2842         .addReg(SrcReg, getKillRegState(SrcIsKill));
2843     }
2844
2845     unsigned OpOpc = 0;
2846     bool NeedPred = false, NeedCC = false, NeedOp3 = false;
2847     switch (MI->getOpcode()) {
2848     default:
2849       llvm_unreachable("Unexpected pseudo instruction!");
2850     case ARM::tANDsp:
2851       OpOpc = ARM::tAND;
2852       NeedPred = true;
2853       break;
2854     case ARM::tADDspr_:
2855       OpOpc = ARM::tADDspr;
2856       break;
2857     case ARM::tSUBspi_:
2858       OpOpc = ARM::tSUBspi;
2859       break;
2860     case ARM::t2SUBrSPi_:
2861       OpOpc = ARM::t2SUBrSPi;
2862       NeedPred = true; NeedCC = true;
2863       break;
2864     case ARM::t2SUBrSPi12_:
2865       OpOpc = ARM::t2SUBrSPi12;
2866       NeedPred = true;
2867       break;
2868     case ARM::t2SUBrSPs_:
2869       OpOpc = ARM::t2SUBrSPs;
2870       NeedPred = true; NeedCC = true; NeedOp3 = true;
2871       break;
2872     }
2873     MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(OpOpc), ARM::SP);
2874     if (OpOpc == ARM::tAND)
2875       AddDefaultT1CC(MIB);
2876     MIB.addReg(ARM::SP);
2877     MIB.addOperand(MI->getOperand(2));
2878     if (NeedOp3)
2879       MIB.addOperand(MI->getOperand(3));
2880     if (NeedPred)
2881       AddDefaultPred(MIB);
2882     if (NeedCC)
2883       AddDefaultCC(MIB);
2884
2885     // Copy the result from SP to virtual register.
2886     const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(DstReg);
2887     unsigned CopyOpc = (RC == ARM::tGPRRegisterClass)
2888       ? ARM::tMOVgpr2tgpr : ARM::tMOVgpr2gpr;
2889     BuildMI(BB, dl, TII->get(CopyOpc))
2890       .addReg(DstReg, getDefRegState(true) | getDeadRegState(DstIsDead))
2891       .addReg(ARM::SP);
2892     MF->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
2893     return BB;
2894   }
2895   }
2896 }
2897
2898 //===----------------------------------------------------------------------===//
2899 //                           ARM Optimization Hooks
2900 //===----------------------------------------------------------------------===//
2901
2902 static
2903 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
2904                             TargetLowering::DAGCombinerInfo &DCI) {
2905   SelectionDAG &DAG = DCI.DAG;
2906   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2907   EVT VT = N->getValueType(0);
2908   unsigned Opc = N->getOpcode();
2909   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
2910   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
2911   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
2912   ISD::CondCode CC = ISD::SETCC_INVALID;
2913
2914   if (isSlctCC) {
2915     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
2916   } else {
2917     SDValue CCOp = Slct.getOperand(0);
2918     if (CCOp.getOpcode() == ISD::SETCC)
2919       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
2920   }
2921
2922   bool DoXform = false;
2923   bool InvCC = false;
2924   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
2925           "Bad input!");
2926
2927   if (LHS.getOpcode() == ISD::Constant &&
2928       cast<ConstantSDNode>(LHS)->isNullValue()) {
2929     DoXform = true;
2930   } else if (CC != ISD::SETCC_INVALID &&
2931              RHS.getOpcode() == ISD::Constant &&
2932              cast<ConstantSDNode>(RHS)->isNullValue()) {
2933     std::swap(LHS, RHS);
2934     SDValue Op0 = Slct.getOperand(0);
2935     EVT OpVT = isSlctCC ? Op0.getValueType() :
2936                           Op0.getOperand(0).getValueType();
2937     bool isInt = OpVT.isInteger();
2938     CC = ISD::getSetCCInverse(CC, isInt);
2939
2940     if (!TLI.isCondCodeLegal(CC, OpVT))
2941       return SDValue();         // Inverse operator isn't legal.
2942
2943     DoXform = true;
2944     InvCC = true;
2945   }
2946
2947   if (DoXform) {
2948     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
2949     if (isSlctCC)
2950       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
2951                              Slct.getOperand(0), Slct.getOperand(1), CC);
2952     SDValue CCOp = Slct.getOperand(0);
2953     if (InvCC)
2954       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
2955                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
2956     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
2957                        CCOp, OtherOp, Result);
2958   }
2959   return SDValue();
2960 }
2961
2962 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
2963 static SDValue PerformADDCombine(SDNode *N,
2964                                  TargetLowering::DAGCombinerInfo &DCI) {
2965   // added by evan in r37685 with no testcase.
2966   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2967
2968   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
2969   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
2970     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
2971     if (Result.getNode()) return Result;
2972   }
2973   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2974     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2975     if (Result.getNode()) return Result;
2976   }
2977
2978   return SDValue();
2979 }
2980
2981 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
2982 static SDValue PerformSUBCombine(SDNode *N,
2983                                  TargetLowering::DAGCombinerInfo &DCI) {
2984   // added by evan in r37685 with no testcase.
2985   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2986
2987   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
2988   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
2989     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
2990     if (Result.getNode()) return Result;
2991   }
2992
2993   return SDValue();
2994 }
2995
2996
2997 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
2998 static SDValue PerformFMRRDCombine(SDNode *N,
2999                                    TargetLowering::DAGCombinerInfo &DCI) {
3000   // fmrrd(fmdrr x, y) -> x,y
3001   SDValue InDouble = N->getOperand(0);
3002   if (InDouble.getOpcode() == ARMISD::FMDRR)
3003     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
3004   return SDValue();
3005 }
3006
3007 /// getVShiftImm - Check if this is a valid build_vector for the immediate
3008 /// operand of a vector shift operation, where all the elements of the
3009 /// build_vector must have the same constant integer value.
3010 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3011   // Ignore bit_converts.
3012   while (Op.getOpcode() == ISD::BIT_CONVERT)
3013     Op = Op.getOperand(0);
3014   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3015   APInt SplatBits, SplatUndef;
3016   unsigned SplatBitSize;
3017   bool HasAnyUndefs;
3018   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3019                                       HasAnyUndefs, ElementBits) ||
3020       SplatBitSize > ElementBits)
3021     return false;
3022   Cnt = SplatBits.getSExtValue();
3023   return true;
3024 }
3025
3026 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
3027 /// operand of a vector shift left operation.  That value must be in the range:
3028 ///   0 <= Value < ElementBits for a left shift; or
3029 ///   0 <= Value <= ElementBits for a long left shift.
3030 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
3031   assert(VT.isVector() && "vector shift count is not a vector type");
3032   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3033   if (! getVShiftImm(Op, ElementBits, Cnt))
3034     return false;
3035   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
3036 }
3037
3038 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
3039 /// operand of a vector shift right operation.  For a shift opcode, the value
3040 /// is positive, but for an intrinsic the value count must be negative. The
3041 /// absolute value must be in the range:
3042 ///   1 <= |Value| <= ElementBits for a right shift; or
3043 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
3044 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
3045                          int64_t &Cnt) {
3046   assert(VT.isVector() && "vector shift count is not a vector type");
3047   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3048   if (! getVShiftImm(Op, ElementBits, Cnt))
3049     return false;
3050   if (isIntrinsic)
3051     Cnt = -Cnt;
3052   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
3053 }
3054
3055 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
3056 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3057   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3058   switch (IntNo) {
3059   default:
3060     // Don't do anything for most intrinsics.
3061     break;
3062
3063   // Vector shifts: check for immediate versions and lower them.
3064   // Note: This is done during DAG combining instead of DAG legalizing because
3065   // the build_vectors for 64-bit vector element shift counts are generally
3066   // not legal, and it is hard to see their values after they get legalized to
3067   // loads from a constant pool.
3068   case Intrinsic::arm_neon_vshifts:
3069   case Intrinsic::arm_neon_vshiftu:
3070   case Intrinsic::arm_neon_vshiftls:
3071   case Intrinsic::arm_neon_vshiftlu:
3072   case Intrinsic::arm_neon_vshiftn:
3073   case Intrinsic::arm_neon_vrshifts:
3074   case Intrinsic::arm_neon_vrshiftu:
3075   case Intrinsic::arm_neon_vrshiftn:
3076   case Intrinsic::arm_neon_vqshifts:
3077   case Intrinsic::arm_neon_vqshiftu:
3078   case Intrinsic::arm_neon_vqshiftsu:
3079   case Intrinsic::arm_neon_vqshiftns:
3080   case Intrinsic::arm_neon_vqshiftnu:
3081   case Intrinsic::arm_neon_vqshiftnsu:
3082   case Intrinsic::arm_neon_vqrshiftns:
3083   case Intrinsic::arm_neon_vqrshiftnu:
3084   case Intrinsic::arm_neon_vqrshiftnsu: {
3085     EVT VT = N->getOperand(1).getValueType();
3086     int64_t Cnt;
3087     unsigned VShiftOpc = 0;
3088
3089     switch (IntNo) {
3090     case Intrinsic::arm_neon_vshifts:
3091     case Intrinsic::arm_neon_vshiftu:
3092       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
3093         VShiftOpc = ARMISD::VSHL;
3094         break;
3095       }
3096       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
3097         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
3098                      ARMISD::VSHRs : ARMISD::VSHRu);
3099         break;
3100       }
3101       return SDValue();
3102
3103     case Intrinsic::arm_neon_vshiftls:
3104     case Intrinsic::arm_neon_vshiftlu:
3105       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
3106         break;
3107       llvm_unreachable("invalid shift count for vshll intrinsic");
3108
3109     case Intrinsic::arm_neon_vrshifts:
3110     case Intrinsic::arm_neon_vrshiftu:
3111       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
3112         break;
3113       return SDValue();
3114
3115     case Intrinsic::arm_neon_vqshifts:
3116     case Intrinsic::arm_neon_vqshiftu:
3117       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3118         break;
3119       return SDValue();
3120
3121     case Intrinsic::arm_neon_vqshiftsu:
3122       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
3123         break;
3124       llvm_unreachable("invalid shift count for vqshlu intrinsic");
3125
3126     case Intrinsic::arm_neon_vshiftn:
3127     case Intrinsic::arm_neon_vrshiftn:
3128     case Intrinsic::arm_neon_vqshiftns:
3129     case Intrinsic::arm_neon_vqshiftnu:
3130     case Intrinsic::arm_neon_vqshiftnsu:
3131     case Intrinsic::arm_neon_vqrshiftns:
3132     case Intrinsic::arm_neon_vqrshiftnu:
3133     case Intrinsic::arm_neon_vqrshiftnsu:
3134       // Narrowing shifts require an immediate right shift.
3135       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
3136         break;
3137       llvm_unreachable("invalid shift count for narrowing vector shift intrinsic");
3138
3139     default:
3140       llvm_unreachable("unhandled vector shift");
3141     }
3142
3143     switch (IntNo) {
3144     case Intrinsic::arm_neon_vshifts:
3145     case Intrinsic::arm_neon_vshiftu:
3146       // Opcode already set above.
3147       break;
3148     case Intrinsic::arm_neon_vshiftls:
3149     case Intrinsic::arm_neon_vshiftlu:
3150       if (Cnt == VT.getVectorElementType().getSizeInBits())
3151         VShiftOpc = ARMISD::VSHLLi;
3152       else
3153         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
3154                      ARMISD::VSHLLs : ARMISD::VSHLLu);
3155       break;
3156     case Intrinsic::arm_neon_vshiftn:
3157       VShiftOpc = ARMISD::VSHRN; break;
3158     case Intrinsic::arm_neon_vrshifts:
3159       VShiftOpc = ARMISD::VRSHRs; break;
3160     case Intrinsic::arm_neon_vrshiftu:
3161       VShiftOpc = ARMISD::VRSHRu; break;
3162     case Intrinsic::arm_neon_vrshiftn:
3163       VShiftOpc = ARMISD::VRSHRN; break;
3164     case Intrinsic::arm_neon_vqshifts:
3165       VShiftOpc = ARMISD::VQSHLs; break;
3166     case Intrinsic::arm_neon_vqshiftu:
3167       VShiftOpc = ARMISD::VQSHLu; break;
3168     case Intrinsic::arm_neon_vqshiftsu:
3169       VShiftOpc = ARMISD::VQSHLsu; break;
3170     case Intrinsic::arm_neon_vqshiftns:
3171       VShiftOpc = ARMISD::VQSHRNs; break;
3172     case Intrinsic::arm_neon_vqshiftnu:
3173       VShiftOpc = ARMISD::VQSHRNu; break;
3174     case Intrinsic::arm_neon_vqshiftnsu:
3175       VShiftOpc = ARMISD::VQSHRNsu; break;
3176     case Intrinsic::arm_neon_vqrshiftns:
3177       VShiftOpc = ARMISD::VQRSHRNs; break;
3178     case Intrinsic::arm_neon_vqrshiftnu:
3179       VShiftOpc = ARMISD::VQRSHRNu; break;
3180     case Intrinsic::arm_neon_vqrshiftnsu:
3181       VShiftOpc = ARMISD::VQRSHRNsu; break;
3182     }
3183
3184     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3185                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3186   }
3187
3188   case Intrinsic::arm_neon_vshiftins: {
3189     EVT VT = N->getOperand(1).getValueType();
3190     int64_t Cnt;
3191     unsigned VShiftOpc = 0;
3192
3193     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
3194       VShiftOpc = ARMISD::VSLI;
3195     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
3196       VShiftOpc = ARMISD::VSRI;
3197     else {
3198       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
3199     }
3200
3201     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
3202                        N->getOperand(1), N->getOperand(2),
3203                        DAG.getConstant(Cnt, MVT::i32));
3204   }
3205
3206   case Intrinsic::arm_neon_vqrshifts:
3207   case Intrinsic::arm_neon_vqrshiftu:
3208     // No immediate versions of these to check for.
3209     break;
3210   }
3211
3212   return SDValue();
3213 }
3214
3215 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
3216 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
3217 /// combining instead of DAG legalizing because the build_vectors for 64-bit
3218 /// vector element shift counts are generally not legal, and it is hard to see
3219 /// their values after they get legalized to loads from a constant pool.
3220 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
3221                                    const ARMSubtarget *ST) {
3222   EVT VT = N->getValueType(0);
3223
3224   // Nothing to be done for scalar shifts.
3225   if (! VT.isVector())
3226     return SDValue();
3227
3228   assert(ST->hasNEON() && "unexpected vector shift");
3229   int64_t Cnt;
3230
3231   switch (N->getOpcode()) {
3232   default: llvm_unreachable("unexpected shift opcode");
3233
3234   case ISD::SHL:
3235     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
3236       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
3237                          DAG.getConstant(Cnt, MVT::i32));
3238     break;
3239
3240   case ISD::SRA:
3241   case ISD::SRL:
3242     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
3243       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
3244                             ARMISD::VSHRs : ARMISD::VSHRu);
3245       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
3246                          DAG.getConstant(Cnt, MVT::i32));
3247     }
3248   }
3249   return SDValue();
3250 }
3251
3252 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
3253 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
3254 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
3255                                     const ARMSubtarget *ST) {
3256   SDValue N0 = N->getOperand(0);
3257
3258   // Check for sign- and zero-extensions of vector extract operations of 8-
3259   // and 16-bit vector elements.  NEON supports these directly.  They are
3260   // handled during DAG combining because type legalization will promote them
3261   // to 32-bit types and it is messy to recognize the operations after that.
3262   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
3263     SDValue Vec = N0.getOperand(0);
3264     SDValue Lane = N0.getOperand(1);
3265     EVT VT = N->getValueType(0);
3266     EVT EltVT = N0.getValueType();
3267     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3268
3269     if (VT == MVT::i32 &&
3270         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
3271         TLI.isTypeLegal(Vec.getValueType())) {
3272
3273       unsigned Opc = 0;
3274       switch (N->getOpcode()) {
3275       default: llvm_unreachable("unexpected opcode");
3276       case ISD::SIGN_EXTEND:
3277         Opc = ARMISD::VGETLANEs;
3278         break;
3279       case ISD::ZERO_EXTEND:
3280       case ISD::ANY_EXTEND:
3281         Opc = ARMISD::VGETLANEu;
3282         break;
3283       }
3284       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
3285     }
3286   }
3287
3288   return SDValue();
3289 }
3290
3291 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
3292                                              DAGCombinerInfo &DCI) const {
3293   switch (N->getOpcode()) {
3294   default: break;
3295   case ISD::ADD:      return PerformADDCombine(N, DCI);
3296   case ISD::SUB:      return PerformSUBCombine(N, DCI);
3297   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
3298   case ISD::INTRINSIC_WO_CHAIN:
3299     return PerformIntrinsicCombine(N, DCI.DAG);
3300   case ISD::SHL:
3301   case ISD::SRA:
3302   case ISD::SRL:
3303     return PerformShiftCombine(N, DCI.DAG, Subtarget);
3304   case ISD::SIGN_EXTEND:
3305   case ISD::ZERO_EXTEND:
3306   case ISD::ANY_EXTEND:
3307     return PerformExtendCombine(N, DCI.DAG, Subtarget);
3308   }
3309   return SDValue();
3310 }
3311
3312 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
3313   if (!Subtarget->hasV6Ops())
3314     // Pre-v6 does not support unaligned mem access.
3315     return false;
3316   else if (!Subtarget->hasV6Ops()) {
3317     // v6 may or may not support unaligned mem access.
3318     if (!Subtarget->isTargetDarwin())
3319       return false;
3320   }
3321
3322   switch (VT.getSimpleVT().SimpleTy) {
3323   default:
3324     return false;
3325   case MVT::i8:
3326   case MVT::i16:
3327   case MVT::i32:
3328     return true;
3329   // FIXME: VLD1 etc with standard alignment is legal.
3330   }
3331 }
3332
3333 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
3334   if (V < 0)
3335     return false;
3336
3337   unsigned Scale = 1;
3338   switch (VT.getSimpleVT().SimpleTy) {
3339   default: return false;
3340   case MVT::i1:
3341   case MVT::i8:
3342     // Scale == 1;
3343     break;
3344   case MVT::i16:
3345     // Scale == 2;
3346     Scale = 2;
3347     break;
3348   case MVT::i32:
3349     // Scale == 4;
3350     Scale = 4;
3351     break;
3352   }
3353
3354   if ((V & (Scale - 1)) != 0)
3355     return false;
3356   V /= Scale;
3357   return V == (V & ((1LL << 5) - 1));
3358 }
3359
3360 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
3361                                       const ARMSubtarget *Subtarget) {
3362   bool isNeg = false;
3363   if (V < 0) {
3364     isNeg = true;
3365     V = - V;
3366   }
3367
3368   switch (VT.getSimpleVT().SimpleTy) {
3369   default: return false;
3370   case MVT::i1:
3371   case MVT::i8:
3372   case MVT::i16:
3373   case MVT::i32:
3374     // + imm12 or - imm8
3375     if (isNeg)
3376       return V == (V & ((1LL << 8) - 1));
3377     return V == (V & ((1LL << 12) - 1));
3378   case MVT::f32:
3379   case MVT::f64:
3380     // Same as ARM mode. FIXME: NEON?
3381     if (!Subtarget->hasVFP2())
3382       return false;
3383     if ((V & 3) != 0)
3384       return false;
3385     V >>= 2;
3386     return V == (V & ((1LL << 8) - 1));
3387   }
3388 }
3389
3390 /// isLegalAddressImmediate - Return true if the integer value can be used
3391 /// as the offset of the target addressing mode for load / store of the
3392 /// given type.
3393 static bool isLegalAddressImmediate(int64_t V, EVT VT,
3394                                     const ARMSubtarget *Subtarget) {
3395   if (V == 0)
3396     return true;
3397
3398   if (!VT.isSimple())
3399     return false;
3400
3401   if (Subtarget->isThumb1Only())
3402     return isLegalT1AddressImmediate(V, VT);
3403   else if (Subtarget->isThumb2())
3404     return isLegalT2AddressImmediate(V, VT, Subtarget);
3405
3406   // ARM mode.
3407   if (V < 0)
3408     V = - V;
3409   switch (VT.getSimpleVT().SimpleTy) {
3410   default: return false;
3411   case MVT::i1:
3412   case MVT::i8:
3413   case MVT::i32:
3414     // +- imm12
3415     return V == (V & ((1LL << 12) - 1));
3416   case MVT::i16:
3417     // +- imm8
3418     return V == (V & ((1LL << 8) - 1));
3419   case MVT::f32:
3420   case MVT::f64:
3421     if (!Subtarget->hasVFP2()) // FIXME: NEON?
3422       return false;
3423     if ((V & 3) != 0)
3424       return false;
3425     V >>= 2;
3426     return V == (V & ((1LL << 8) - 1));
3427   }
3428 }
3429
3430 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
3431                                                       EVT VT) const {
3432   int Scale = AM.Scale;
3433   if (Scale < 0)
3434     return false;
3435
3436   switch (VT.getSimpleVT().SimpleTy) {
3437   default: return false;
3438   case MVT::i1:
3439   case MVT::i8:
3440   case MVT::i16:
3441   case MVT::i32:
3442     if (Scale == 1)
3443       return true;
3444     // r + r << imm
3445     Scale = Scale & ~1;
3446     return Scale == 2 || Scale == 4 || Scale == 8;
3447   case MVT::i64:
3448     // r + r
3449     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3450       return true;
3451     return false;
3452   case MVT::isVoid:
3453     // Note, we allow "void" uses (basically, uses that aren't loads or
3454     // stores), because arm allows folding a scale into many arithmetic
3455     // operations.  This should be made more precise and revisited later.
3456
3457     // Allow r << imm, but the imm has to be a multiple of two.
3458     if (Scale & 1) return false;
3459     return isPowerOf2_32(Scale);
3460   }
3461 }
3462
3463 /// isLegalAddressingMode - Return true if the addressing mode represented
3464 /// by AM is legal for this target, for a load/store of the specified type.
3465 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3466                                               const Type *Ty) const {
3467   EVT VT = getValueType(Ty, true);
3468   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
3469     return false;
3470
3471   // Can never fold addr of global into load/store.
3472   if (AM.BaseGV)
3473     return false;
3474
3475   switch (AM.Scale) {
3476   case 0:  // no scale reg, must be "r+i" or "r", or "i".
3477     break;
3478   case 1:
3479     if (Subtarget->isThumb1Only())
3480       return false;
3481     // FALL THROUGH.
3482   default:
3483     // ARM doesn't support any R+R*scale+imm addr modes.
3484     if (AM.BaseOffs)
3485       return false;
3486
3487     if (!VT.isSimple())
3488       return false;
3489
3490     if (Subtarget->isThumb2())
3491       return isLegalT2ScaledAddressingMode(AM, VT);
3492
3493     int Scale = AM.Scale;
3494     switch (VT.getSimpleVT().SimpleTy) {
3495     default: return false;
3496     case MVT::i1:
3497     case MVT::i8:
3498     case MVT::i32:
3499       if (Scale < 0) Scale = -Scale;
3500       if (Scale == 1)
3501         return true;
3502       // r + r << imm
3503       return isPowerOf2_32(Scale & ~1);
3504     case MVT::i16:
3505     case MVT::i64:
3506       // r + r
3507       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
3508         return true;
3509       return false;
3510
3511     case MVT::isVoid:
3512       // Note, we allow "void" uses (basically, uses that aren't loads or
3513       // stores), because arm allows folding a scale into many arithmetic
3514       // operations.  This should be made more precise and revisited later.
3515
3516       // Allow r << imm, but the imm has to be a multiple of two.
3517       if (Scale & 1) return false;
3518       return isPowerOf2_32(Scale);
3519     }
3520     break;
3521   }
3522   return true;
3523 }
3524
3525 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
3526                                       bool isSEXTLoad, SDValue &Base,
3527                                       SDValue &Offset, bool &isInc,
3528                                       SelectionDAG &DAG) {
3529   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3530     return false;
3531
3532   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
3533     // AddressingMode 3
3534     Base = Ptr->getOperand(0);
3535     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3536       int RHSC = (int)RHS->getZExtValue();
3537       if (RHSC < 0 && RHSC > -256) {
3538         assert(Ptr->getOpcode() == ISD::ADD);
3539         isInc = false;
3540         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3541         return true;
3542       }
3543     }
3544     isInc = (Ptr->getOpcode() == ISD::ADD);
3545     Offset = Ptr->getOperand(1);
3546     return true;
3547   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
3548     // AddressingMode 2
3549     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3550       int RHSC = (int)RHS->getZExtValue();
3551       if (RHSC < 0 && RHSC > -0x1000) {
3552         assert(Ptr->getOpcode() == ISD::ADD);
3553         isInc = false;
3554         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3555         Base = Ptr->getOperand(0);
3556         return true;
3557       }
3558     }
3559
3560     if (Ptr->getOpcode() == ISD::ADD) {
3561       isInc = true;
3562       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
3563       if (ShOpcVal != ARM_AM::no_shift) {
3564         Base = Ptr->getOperand(1);
3565         Offset = Ptr->getOperand(0);
3566       } else {
3567         Base = Ptr->getOperand(0);
3568         Offset = Ptr->getOperand(1);
3569       }
3570       return true;
3571     }
3572
3573     isInc = (Ptr->getOpcode() == ISD::ADD);
3574     Base = Ptr->getOperand(0);
3575     Offset = Ptr->getOperand(1);
3576     return true;
3577   }
3578
3579   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
3580   return false;
3581 }
3582
3583 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
3584                                      bool isSEXTLoad, SDValue &Base,
3585                                      SDValue &Offset, bool &isInc,
3586                                      SelectionDAG &DAG) {
3587   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
3588     return false;
3589
3590   Base = Ptr->getOperand(0);
3591   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
3592     int RHSC = (int)RHS->getZExtValue();
3593     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
3594       assert(Ptr->getOpcode() == ISD::ADD);
3595       isInc = false;
3596       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
3597       return true;
3598     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
3599       isInc = Ptr->getOpcode() == ISD::ADD;
3600       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
3601       return true;
3602     }
3603   }
3604
3605   return false;
3606 }
3607
3608 /// getPreIndexedAddressParts - returns true by value, base pointer and
3609 /// offset pointer and addressing mode by reference if the node's address
3610 /// can be legally represented as pre-indexed load / store address.
3611 bool
3612 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
3613                                              SDValue &Offset,
3614                                              ISD::MemIndexedMode &AM,
3615                                              SelectionDAG &DAG) const {
3616   if (Subtarget->isThumb1Only())
3617     return false;
3618
3619   EVT VT;
3620   SDValue Ptr;
3621   bool isSEXTLoad = false;
3622   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3623     Ptr = LD->getBasePtr();
3624     VT  = LD->getMemoryVT();
3625     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3626   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3627     Ptr = ST->getBasePtr();
3628     VT  = ST->getMemoryVT();
3629   } else
3630     return false;
3631
3632   bool isInc;
3633   bool isLegal = false;
3634   if (Subtarget->isThumb2())
3635     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3636                                        Offset, isInc, DAG);
3637   else
3638     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
3639                                         Offset, isInc, DAG);
3640   if (!isLegal)
3641     return false;
3642
3643   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
3644   return true;
3645 }
3646
3647 /// getPostIndexedAddressParts - returns true by value, base pointer and
3648 /// offset pointer and addressing mode by reference if this node can be
3649 /// combined with a load / store to form a post-indexed load / store.
3650 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
3651                                                    SDValue &Base,
3652                                                    SDValue &Offset,
3653                                                    ISD::MemIndexedMode &AM,
3654                                                    SelectionDAG &DAG) const {
3655   if (Subtarget->isThumb1Only())
3656     return false;
3657
3658   EVT VT;
3659   SDValue Ptr;
3660   bool isSEXTLoad = false;
3661   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3662     VT  = LD->getMemoryVT();
3663     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
3664   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3665     VT  = ST->getMemoryVT();
3666   } else
3667     return false;
3668
3669   bool isInc;
3670   bool isLegal = false;
3671   if (Subtarget->isThumb2())
3672     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3673                                         isInc, DAG);
3674   else
3675     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
3676                                         isInc, DAG);
3677   if (!isLegal)
3678     return false;
3679
3680   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
3681   return true;
3682 }
3683
3684 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
3685                                                        const APInt &Mask,
3686                                                        APInt &KnownZero,
3687                                                        APInt &KnownOne,
3688                                                        const SelectionDAG &DAG,
3689                                                        unsigned Depth) const {
3690   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
3691   switch (Op.getOpcode()) {
3692   default: break;
3693   case ARMISD::CMOV: {
3694     // Bits are known zero/one if known on the LHS and RHS.
3695     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
3696     if (KnownZero == 0 && KnownOne == 0) return;
3697
3698     APInt KnownZeroRHS, KnownOneRHS;
3699     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
3700                           KnownZeroRHS, KnownOneRHS, Depth+1);
3701     KnownZero &= KnownZeroRHS;
3702     KnownOne  &= KnownOneRHS;
3703     return;
3704   }
3705   }
3706 }
3707
3708 //===----------------------------------------------------------------------===//
3709 //                           ARM Inline Assembly Support
3710 //===----------------------------------------------------------------------===//
3711
3712 /// getConstraintType - Given a constraint letter, return the type of
3713 /// constraint it is for this target.
3714 ARMTargetLowering::ConstraintType
3715 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
3716   if (Constraint.size() == 1) {
3717     switch (Constraint[0]) {
3718     default:  break;
3719     case 'l': return C_RegisterClass;
3720     case 'w': return C_RegisterClass;
3721     }
3722   }
3723   return TargetLowering::getConstraintType(Constraint);
3724 }
3725
3726 std::pair<unsigned, const TargetRegisterClass*>
3727 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3728                                                 EVT VT) const {
3729   if (Constraint.size() == 1) {
3730     // GCC RS6000 Constraint Letters
3731     switch (Constraint[0]) {
3732     case 'l':
3733       if (Subtarget->isThumb1Only())
3734         return std::make_pair(0U, ARM::tGPRRegisterClass);
3735       else
3736         return std::make_pair(0U, ARM::GPRRegisterClass);
3737     case 'r':
3738       return std::make_pair(0U, ARM::GPRRegisterClass);
3739     case 'w':
3740       if (VT == MVT::f32)
3741         return std::make_pair(0U, ARM::SPRRegisterClass);
3742       if (VT == MVT::f64)
3743         return std::make_pair(0U, ARM::DPRRegisterClass);
3744       break;
3745     }
3746   }
3747   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3748 }
3749
3750 std::vector<unsigned> ARMTargetLowering::
3751 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3752                                   EVT VT) const {
3753   if (Constraint.size() != 1)
3754     return std::vector<unsigned>();
3755
3756   switch (Constraint[0]) {      // GCC ARM Constraint Letters
3757   default: break;
3758   case 'l':
3759     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3760                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3761                                  0);
3762   case 'r':
3763     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
3764                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
3765                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
3766                                  ARM::R12, ARM::LR, 0);
3767   case 'w':
3768     if (VT == MVT::f32)
3769       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
3770                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
3771                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
3772                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
3773                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
3774                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
3775                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
3776                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
3777     if (VT == MVT::f64)
3778       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
3779                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
3780                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
3781                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
3782       break;
3783   }
3784
3785   return std::vector<unsigned>();
3786 }
3787
3788 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3789 /// vector.  If it is invalid, don't add anything to Ops.
3790 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3791                                                      char Constraint,
3792                                                      bool hasMemory,
3793                                                      std::vector<SDValue>&Ops,
3794                                                      SelectionDAG &DAG) const {
3795   SDValue Result(0, 0);
3796
3797   switch (Constraint) {
3798   default: break;
3799   case 'I': case 'J': case 'K': case 'L':
3800   case 'M': case 'N': case 'O':
3801     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3802     if (!C)
3803       return;
3804
3805     int64_t CVal64 = C->getSExtValue();
3806     int CVal = (int) CVal64;
3807     // None of these constraints allow values larger than 32 bits.  Check
3808     // that the value fits in an int.
3809     if (CVal != CVal64)
3810       return;
3811
3812     switch (Constraint) {
3813       case 'I':
3814         if (Subtarget->isThumb1Only()) {
3815           // This must be a constant between 0 and 255, for ADD
3816           // immediates.
3817           if (CVal >= 0 && CVal <= 255)
3818             break;
3819         } else if (Subtarget->isThumb2()) {
3820           // A constant that can be used as an immediate value in a
3821           // data-processing instruction.
3822           if (ARM_AM::getT2SOImmVal(CVal) != -1)
3823             break;
3824         } else {
3825           // A constant that can be used as an immediate value in a
3826           // data-processing instruction.
3827           if (ARM_AM::getSOImmVal(CVal) != -1)
3828             break;
3829         }
3830         return;
3831
3832       case 'J':
3833         if (Subtarget->isThumb()) {  // FIXME thumb2
3834           // This must be a constant between -255 and -1, for negated ADD
3835           // immediates. This can be used in GCC with an "n" modifier that
3836           // prints the negated value, for use with SUB instructions. It is
3837           // not useful otherwise but is implemented for compatibility.
3838           if (CVal >= -255 && CVal <= -1)
3839             break;
3840         } else {
3841           // This must be a constant between -4095 and 4095. It is not clear
3842           // what this constraint is intended for. Implemented for
3843           // compatibility with GCC.
3844           if (CVal >= -4095 && CVal <= 4095)
3845             break;
3846         }
3847         return;
3848
3849       case 'K':
3850         if (Subtarget->isThumb1Only()) {
3851           // A 32-bit value where only one byte has a nonzero value. Exclude
3852           // zero to match GCC. This constraint is used by GCC internally for
3853           // constants that can be loaded with a move/shift combination.
3854           // It is not useful otherwise but is implemented for compatibility.
3855           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
3856             break;
3857         } else if (Subtarget->isThumb2()) {
3858           // A constant whose bitwise inverse can be used as an immediate
3859           // value in a data-processing instruction. This can be used in GCC
3860           // with a "B" modifier that prints the inverted value, for use with
3861           // BIC and MVN instructions. It is not useful otherwise but is
3862           // implemented for compatibility.
3863           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
3864             break;
3865         } else {
3866           // A constant whose bitwise inverse can be used as an immediate
3867           // value in a data-processing instruction. This can be used in GCC
3868           // with a "B" modifier that prints the inverted value, for use with
3869           // BIC and MVN instructions. It is not useful otherwise but is
3870           // implemented for compatibility.
3871           if (ARM_AM::getSOImmVal(~CVal) != -1)
3872             break;
3873         }
3874         return;
3875
3876       case 'L':
3877         if (Subtarget->isThumb1Only()) {
3878           // This must be a constant between -7 and 7,
3879           // for 3-operand ADD/SUB immediate instructions.
3880           if (CVal >= -7 && CVal < 7)
3881             break;
3882         } else if (Subtarget->isThumb2()) {
3883           // A constant whose negation can be used as an immediate value in a
3884           // data-processing instruction. This can be used in GCC with an "n"
3885           // modifier that prints the negated value, for use with SUB
3886           // instructions. It is not useful otherwise but is implemented for
3887           // compatibility.
3888           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
3889             break;
3890         } else {
3891           // A constant whose negation can be used as an immediate value in a
3892           // data-processing instruction. This can be used in GCC with an "n"
3893           // modifier that prints the negated value, for use with SUB
3894           // instructions. It is not useful otherwise but is implemented for
3895           // compatibility.
3896           if (ARM_AM::getSOImmVal(-CVal) != -1)
3897             break;
3898         }
3899         return;
3900
3901       case 'M':
3902         if (Subtarget->isThumb()) { // FIXME thumb2
3903           // This must be a multiple of 4 between 0 and 1020, for
3904           // ADD sp + immediate.
3905           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
3906             break;
3907         } else {
3908           // A power of two or a constant between 0 and 32.  This is used in
3909           // GCC for the shift amount on shifted register operands, but it is
3910           // useful in general for any shift amounts.
3911           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
3912             break;
3913         }
3914         return;
3915
3916       case 'N':
3917         if (Subtarget->isThumb()) {  // FIXME thumb2
3918           // This must be a constant between 0 and 31, for shift amounts.
3919           if (CVal >= 0 && CVal <= 31)
3920             break;
3921         }
3922         return;
3923
3924       case 'O':
3925         if (Subtarget->isThumb()) {  // FIXME thumb2
3926           // This must be a multiple of 4 between -508 and 508, for
3927           // ADD/SUB sp = sp + immediate.
3928           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
3929             break;
3930         }
3931         return;
3932     }
3933     Result = DAG.getTargetConstant(CVal, Op.getValueType());
3934     break;
3935   }
3936
3937   if (Result.getNode()) {
3938     Ops.push_back(Result);
3939     return;
3940   }
3941   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
3942                                                       Ops, DAG);
3943 }