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