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