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