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