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