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