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