PPCISelLowering.cpp revision c06441e5ea55d1e48a85e99ed2615ff4f459b4c2
1//===-- PPCISelLowering.cpp - PPC 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 implements the PPCISelLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "PPCISelLowering.h"
15#include "PPCMachineFunctionInfo.h"
16#include "PPCPredicates.h"
17#include "PPCTargetMachine.h"
18#include "PPCPerfectShuffle.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/VectorExtras.h"
21#include "llvm/CodeGen/CallingConvLower.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/PseudoSourceValue.h"
27#include "llvm/CodeGen/SelectionDAG.h"
28#include "llvm/CallingConv.h"
29#include "llvm/Constants.h"
30#include "llvm/Function.h"
31#include "llvm/Intrinsics.h"
32#include "llvm/Support/MathExtras.h"
33#include "llvm/Target/TargetOptions.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/DerivedTypes.h"
36using namespace llvm;
37
38static cl::opt<bool> EnablePPCPreinc("enable-ppc-preinc",
39cl::desc("enable preincrement load/store generation on PPC (experimental)"),
40                                     cl::Hidden);
41
42PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
43  : TargetLowering(TM), PPCSubTarget(*TM.getSubtargetImpl()) {
44
45  setPow2DivIsCheap();
46
47  // Use _setjmp/_longjmp instead of setjmp/longjmp.
48  setUseUnderscoreSetJmp(true);
49  setUseUnderscoreLongJmp(true);
50
51  // Set up the register classes.
52  addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
53  addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
54  addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
55
56  // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
57  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
58  setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
59
60  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
61
62  // PowerPC has pre-inc load and store's.
63  setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
64  setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
65  setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
66  setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
67  setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
68  setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
69  setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
70  setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
71  setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
72  setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
73
74  // This is used in the ppcf128->int sequence.  Note it has different semantics
75  // from FP_ROUND:  that rounds to nearest, this rounds to zero.
76  setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
77
78  // PowerPC has no SREM/UREM instructions
79  setOperationAction(ISD::SREM, MVT::i32, Expand);
80  setOperationAction(ISD::UREM, MVT::i32, Expand);
81  setOperationAction(ISD::SREM, MVT::i64, Expand);
82  setOperationAction(ISD::UREM, MVT::i64, Expand);
83
84  // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
85  setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
86  setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
87  setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
88  setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
89  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
90  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
91  setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
92  setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
93
94  // We don't support sin/cos/sqrt/fmod/pow
95  setOperationAction(ISD::FSIN , MVT::f64, Expand);
96  setOperationAction(ISD::FCOS , MVT::f64, Expand);
97  setOperationAction(ISD::FREM , MVT::f64, Expand);
98  setOperationAction(ISD::FPOW , MVT::f64, Expand);
99  setOperationAction(ISD::FSIN , MVT::f32, Expand);
100  setOperationAction(ISD::FCOS , MVT::f32, Expand);
101  setOperationAction(ISD::FREM , MVT::f32, Expand);
102  setOperationAction(ISD::FPOW , MVT::f32, Expand);
103
104  setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
105
106  // If we're enabling GP optimizations, use hardware square root
107  if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
108    setOperationAction(ISD::FSQRT, MVT::f64, Expand);
109    setOperationAction(ISD::FSQRT, MVT::f32, Expand);
110  }
111
112  setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
113  setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
114
115  // PowerPC does not have BSWAP, CTPOP or CTTZ
116  setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
117  setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
118  setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
119  setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
120  setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
121  setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
122
123  // PowerPC does not have ROTR
124  setOperationAction(ISD::ROTR, MVT::i32   , Expand);
125  setOperationAction(ISD::ROTR, MVT::i64   , Expand);
126
127  // PowerPC does not have Select
128  setOperationAction(ISD::SELECT, MVT::i32, Expand);
129  setOperationAction(ISD::SELECT, MVT::i64, Expand);
130  setOperationAction(ISD::SELECT, MVT::f32, Expand);
131  setOperationAction(ISD::SELECT, MVT::f64, Expand);
132
133  // PowerPC wants to turn select_cc of FP into fsel when possible.
134  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
135  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
136
137  // PowerPC wants to optimize integer setcc a bit
138  setOperationAction(ISD::SETCC, MVT::i32, Custom);
139
140  // PowerPC does not have BRCOND which requires SetCC
141  setOperationAction(ISD::BRCOND, MVT::Other, Expand);
142
143  setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
144
145  // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
146  setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
147
148  // PowerPC does not have [U|S]INT_TO_FP
149  setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
150  setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
151
152  setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
153  setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
154  setOperationAction(ISD::BIT_CONVERT, MVT::i64, Expand);
155  setOperationAction(ISD::BIT_CONVERT, MVT::f64, Expand);
156
157  // We cannot sextinreg(i1).  Expand to shifts.
158  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
159
160  // Support label based line numbers.
161  setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
162  setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
163
164  setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
165  setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
166  setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
167  setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
168
169
170  // We want to legalize GlobalAddress and ConstantPool nodes into the
171  // appropriate instructions to materialize the address.
172  setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
173  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
174  setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
175  setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
176  setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
177  setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
178  setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
179  setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
180
181  // RET must be custom lowered, to meet ABI requirements.
182  setOperationAction(ISD::RET               , MVT::Other, Custom);
183
184  // TRAP is legal.
185  setOperationAction(ISD::TRAP, MVT::Other, Legal);
186
187  // TRAMPOLINE is custom lowered.
188  setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
189
190  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
191  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
192
193  // VAARG is custom lowered with ELF 32 ABI
194  if (TM.getSubtarget<PPCSubtarget>().isELF32_ABI())
195    setOperationAction(ISD::VAARG, MVT::Other, Custom);
196  else
197    setOperationAction(ISD::VAARG, MVT::Other, Expand);
198
199  // Use the default implementation.
200  setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
201  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
202  setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
203  setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
204  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
205  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
206
207  // We want to custom lower some of our intrinsics.
208  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
209
210  // Comparisons that require checking two conditions.
211  setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
212  setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
213  setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
214  setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
215  setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
216  setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
217  setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
218  setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
219  setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
220  setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
221  setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
222  setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
223
224  if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
225    // They also have instructions for converting between i64 and fp.
226    setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
227    setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
228    setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
229    setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
230    setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
231
232    // FIXME: disable this lowered code.  This generates 64-bit register values,
233    // and we don't model the fact that the top part is clobbered by calls.  We
234    // need to flag these together so that the value isn't live across a call.
235    //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
236
237    // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
238    setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
239  } else {
240    // PowerPC does not have FP_TO_UINT on 32-bit implementations.
241    setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
242  }
243
244  if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) {
245    // 64-bit PowerPC implementations can support i64 types directly
246    addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
247    // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
248    setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
249    // 64-bit PowerPC wants to expand i128 shifts itself.
250    setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
251    setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
252    setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
253  } else {
254    // 32-bit PowerPC wants to expand i64 shifts itself.
255    setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
256    setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
257    setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
258  }
259
260  if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
261    // First set operation action for all vector types to expand. Then we
262    // will selectively turn on ones that can be effectively codegen'd.
263    for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
264         i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
265      MVT VT = (MVT::SimpleValueType)i;
266
267      // add/sub are legal for all supported vector VT's.
268      setOperationAction(ISD::ADD , VT, Legal);
269      setOperationAction(ISD::SUB , VT, Legal);
270
271      // We promote all shuffles to v16i8.
272      setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
273      AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
274
275      // We promote all non-typed operations to v4i32.
276      setOperationAction(ISD::AND   , VT, Promote);
277      AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
278      setOperationAction(ISD::OR    , VT, Promote);
279      AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
280      setOperationAction(ISD::XOR   , VT, Promote);
281      AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
282      setOperationAction(ISD::LOAD  , VT, Promote);
283      AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
284      setOperationAction(ISD::SELECT, VT, Promote);
285      AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
286      setOperationAction(ISD::STORE, VT, Promote);
287      AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
288
289      // No other operations are legal.
290      setOperationAction(ISD::MUL , VT, Expand);
291      setOperationAction(ISD::SDIV, VT, Expand);
292      setOperationAction(ISD::SREM, VT, Expand);
293      setOperationAction(ISD::UDIV, VT, Expand);
294      setOperationAction(ISD::UREM, VT, Expand);
295      setOperationAction(ISD::FDIV, VT, Expand);
296      setOperationAction(ISD::FNEG, VT, Expand);
297      setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
298      setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
299      setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
300      setOperationAction(ISD::UMUL_LOHI, VT, Expand);
301      setOperationAction(ISD::SMUL_LOHI, VT, Expand);
302      setOperationAction(ISD::UDIVREM, VT, Expand);
303      setOperationAction(ISD::SDIVREM, VT, Expand);
304      setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
305      setOperationAction(ISD::FPOW, VT, Expand);
306      setOperationAction(ISD::CTPOP, VT, Expand);
307      setOperationAction(ISD::CTLZ, VT, Expand);
308      setOperationAction(ISD::CTTZ, VT, Expand);
309    }
310
311    // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
312    // with merges, splats, etc.
313    setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
314
315    setOperationAction(ISD::AND   , MVT::v4i32, Legal);
316    setOperationAction(ISD::OR    , MVT::v4i32, Legal);
317    setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
318    setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
319    setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
320    setOperationAction(ISD::STORE , MVT::v4i32, Legal);
321
322    addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
323    addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
324    addRegisterClass(MVT::v8i16, PPC::VRRCRegisterClass);
325    addRegisterClass(MVT::v16i8, PPC::VRRCRegisterClass);
326
327    setOperationAction(ISD::MUL, MVT::v4f32, Legal);
328    setOperationAction(ISD::MUL, MVT::v4i32, Custom);
329    setOperationAction(ISD::MUL, MVT::v8i16, Custom);
330    setOperationAction(ISD::MUL, MVT::v16i8, Custom);
331
332    setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
333    setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
334
335    setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
336    setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
337    setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
338    setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
339  }
340
341  setShiftAmountType(MVT::i32);
342  setBooleanContents(ZeroOrOneBooleanContent);
343
344  if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
345    setStackPointerRegisterToSaveRestore(PPC::X1);
346    setExceptionPointerRegister(PPC::X3);
347    setExceptionSelectorRegister(PPC::X4);
348  } else {
349    setStackPointerRegisterToSaveRestore(PPC::R1);
350    setExceptionPointerRegister(PPC::R3);
351    setExceptionSelectorRegister(PPC::R4);
352  }
353
354  // We have target-specific dag combine patterns for the following nodes:
355  setTargetDAGCombine(ISD::SINT_TO_FP);
356  setTargetDAGCombine(ISD::STORE);
357  setTargetDAGCombine(ISD::BR_CC);
358  setTargetDAGCombine(ISD::BSWAP);
359
360  // Darwin long double math library functions have $LDBL128 appended.
361  if (TM.getSubtarget<PPCSubtarget>().isDarwin()) {
362    setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
363    setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
364    setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
365    setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
366    setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
367    setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
368    setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
369    setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
370    setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
371    setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
372  }
373
374  computeRegisterProperties();
375}
376
377/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
378/// function arguments in the caller parameter area.
379unsigned PPCTargetLowering::getByValTypeAlignment(const Type *Ty) const {
380  TargetMachine &TM = getTargetMachine();
381  // Darwin passes everything on 4 byte boundary.
382  if (TM.getSubtarget<PPCSubtarget>().isDarwin())
383    return 4;
384  // FIXME Elf TBD
385  return 4;
386}
387
388const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
389  switch (Opcode) {
390  default: return 0;
391  case PPCISD::FSEL:            return "PPCISD::FSEL";
392  case PPCISD::FCFID:           return "PPCISD::FCFID";
393  case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
394  case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
395  case PPCISD::STFIWX:          return "PPCISD::STFIWX";
396  case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
397  case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
398  case PPCISD::VPERM:           return "PPCISD::VPERM";
399  case PPCISD::Hi:              return "PPCISD::Hi";
400  case PPCISD::Lo:              return "PPCISD::Lo";
401  case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
402  case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
403  case PPCISD::SRL:             return "PPCISD::SRL";
404  case PPCISD::SRA:             return "PPCISD::SRA";
405  case PPCISD::SHL:             return "PPCISD::SHL";
406  case PPCISD::EXTSW_32:        return "PPCISD::EXTSW_32";
407  case PPCISD::STD_32:          return "PPCISD::STD_32";
408  case PPCISD::CALL_ELF:        return "PPCISD::CALL_ELF";
409  case PPCISD::CALL_Macho:      return "PPCISD::CALL_Macho";
410  case PPCISD::MTCTR:           return "PPCISD::MTCTR";
411  case PPCISD::BCTRL_Macho:     return "PPCISD::BCTRL_Macho";
412  case PPCISD::BCTRL_ELF:       return "PPCISD::BCTRL_ELF";
413  case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
414  case PPCISD::MFCR:            return "PPCISD::MFCR";
415  case PPCISD::VCMP:            return "PPCISD::VCMP";
416  case PPCISD::VCMPo:           return "PPCISD::VCMPo";
417  case PPCISD::LBRX:            return "PPCISD::LBRX";
418  case PPCISD::STBRX:           return "PPCISD::STBRX";
419  case PPCISD::LARX:            return "PPCISD::LARX";
420  case PPCISD::STCX:            return "PPCISD::STCX";
421  case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
422  case PPCISD::MFFS:            return "PPCISD::MFFS";
423  case PPCISD::MTFSB0:          return "PPCISD::MTFSB0";
424  case PPCISD::MTFSB1:          return "PPCISD::MTFSB1";
425  case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
426  case PPCISD::MTFSF:           return "PPCISD::MTFSF";
427  case PPCISD::TAILCALL:        return "PPCISD::TAILCALL";
428  case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
429  }
430}
431
432
433MVT PPCTargetLowering::getSetCCResultType(MVT VT) const {
434  return MVT::i32;
435}
436
437
438//===----------------------------------------------------------------------===//
439// Node matching predicates, for use by the tblgen matching code.
440//===----------------------------------------------------------------------===//
441
442/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
443static bool isFloatingPointZero(SDValue Op) {
444  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
445    return CFP->getValueAPF().isZero();
446  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
447    // Maybe this has already been legalized into the constant pool?
448    if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
449      if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
450        return CFP->getValueAPF().isZero();
451  }
452  return false;
453}
454
455/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
456/// true if Op is undef or if it matches the specified value.
457static bool isConstantOrUndef(int Op, int Val) {
458  return Op < 0 || Op == Val;
459}
460
461/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
462/// VPKUHUM instruction.
463bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
464  if (!isUnary) {
465    for (unsigned i = 0; i != 16; ++i)
466      if (!isConstantOrUndef(N->getMaskElt(i),  i*2+1))
467        return false;
468  } else {
469    for (unsigned i = 0; i != 8; ++i)
470      if (!isConstantOrUndef(N->getMaskElt(i),    i*2+1) ||
471          !isConstantOrUndef(N->getMaskElt(i+8),  i*2+1))
472        return false;
473  }
474  return true;
475}
476
477/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
478/// VPKUWUM instruction.
479bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
480  if (!isUnary) {
481    for (unsigned i = 0; i != 16; i += 2)
482      if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
483          !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
484        return false;
485  } else {
486    for (unsigned i = 0; i != 8; i += 2)
487      if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
488          !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3) ||
489          !isConstantOrUndef(N->getMaskElt(i+8),  i*2+2) ||
490          !isConstantOrUndef(N->getMaskElt(i+9),  i*2+3))
491        return false;
492  }
493  return true;
494}
495
496/// isVMerge - Common function, used to match vmrg* shuffles.
497///
498static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
499                     unsigned LHSStart, unsigned RHSStart) {
500  assert(N->getValueType(0) == MVT::v16i8 &&
501         "PPC only supports shuffles by bytes!");
502  assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
503         "Unsupported merge size!");
504
505  for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
506    for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
507      if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
508                             LHSStart+j+i*UnitSize) ||
509          !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
510                             RHSStart+j+i*UnitSize))
511        return false;
512    }
513  return true;
514}
515
516/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
517/// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
518bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
519                             bool isUnary) {
520  if (!isUnary)
521    return isVMerge(N, UnitSize, 8, 24);
522  return isVMerge(N, UnitSize, 8, 8);
523}
524
525/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
526/// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
527bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
528                             bool isUnary) {
529  if (!isUnary)
530    return isVMerge(N, UnitSize, 0, 16);
531  return isVMerge(N, UnitSize, 0, 0);
532}
533
534
535/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
536/// amount, otherwise return -1.
537int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
538  assert(N->getValueType(0) == MVT::v16i8 &&
539         "PPC only supports shuffles by bytes!");
540
541  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
542
543  // Find the first non-undef value in the shuffle mask.
544  unsigned i;
545  for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
546    /*search*/;
547
548  if (i == 16) return -1;  // all undef.
549
550  // Otherwise, check to see if the rest of the elements are consecutively
551  // numbered from this value.
552  unsigned ShiftAmt = SVOp->getMaskElt(i);
553  if (ShiftAmt < i) return -1;
554  ShiftAmt -= i;
555
556  if (!isUnary) {
557    // Check the rest of the elements to see if they are consecutive.
558    for (++i; i != 16; ++i)
559      if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
560        return -1;
561  } else {
562    // Check the rest of the elements to see if they are consecutive.
563    for (++i; i != 16; ++i)
564      if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
565        return -1;
566  }
567  return ShiftAmt;
568}
569
570/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
571/// specifies a splat of a single element that is suitable for input to
572/// VSPLTB/VSPLTH/VSPLTW.
573bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
574  assert(N->getValueType(0) == MVT::v16i8 &&
575         (EltSize == 1 || EltSize == 2 || EltSize == 4));
576
577  // This is a splat operation if each element of the permute is the same, and
578  // if the value doesn't reference the second vector.
579  unsigned ElementBase = N->getMaskElt(0);
580
581  // FIXME: Handle UNDEF elements too!
582  if (ElementBase >= 16)
583    return false;
584
585  // Check that the indices are consecutive, in the case of a multi-byte element
586  // splatted with a v16i8 mask.
587  for (unsigned i = 1; i != EltSize; ++i)
588    if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
589      return false;
590
591  for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
592    if (N->getMaskElt(i) < 0) continue;
593    for (unsigned j = 0; j != EltSize; ++j)
594      if (N->getMaskElt(i+j) != N->getMaskElt(j))
595        return false;
596  }
597  return true;
598}
599
600/// isAllNegativeZeroVector - Returns true if all elements of build_vector
601/// are -0.0.
602bool PPC::isAllNegativeZeroVector(SDNode *N) {
603  BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
604
605  APInt APVal, APUndef;
606  unsigned BitSize;
607  bool HasAnyUndefs;
608
609  if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32))
610    if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
611      return CFP->getValueAPF().isNegZero();
612
613  return false;
614}
615
616/// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
617/// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
618unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
619  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
620  assert(isSplatShuffleMask(SVOp, EltSize));
621  return SVOp->getMaskElt(0) / EltSize;
622}
623
624/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
625/// by using a vspltis[bhw] instruction of the specified element size, return
626/// the constant being splatted.  The ByteSize field indicates the number of
627/// bytes of each element [124] -> [bhw].
628SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
629  SDValue OpVal(0, 0);
630
631  // If ByteSize of the splat is bigger than the element size of the
632  // build_vector, then we have a case where we are checking for a splat where
633  // multiple elements of the buildvector are folded together into a single
634  // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
635  unsigned EltSize = 16/N->getNumOperands();
636  if (EltSize < ByteSize) {
637    unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
638    SDValue UniquedVals[4];
639    assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
640
641    // See if all of the elements in the buildvector agree across.
642    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
643      if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
644      // If the element isn't a constant, bail fully out.
645      if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
646
647
648      if (UniquedVals[i&(Multiple-1)].getNode() == 0)
649        UniquedVals[i&(Multiple-1)] = N->getOperand(i);
650      else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
651        return SDValue();  // no match.
652    }
653
654    // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
655    // either constant or undef values that are identical for each chunk.  See
656    // if these chunks can form into a larger vspltis*.
657
658    // Check to see if all of the leading entries are either 0 or -1.  If
659    // neither, then this won't fit into the immediate field.
660    bool LeadingZero = true;
661    bool LeadingOnes = true;
662    for (unsigned i = 0; i != Multiple-1; ++i) {
663      if (UniquedVals[i].getNode() == 0) continue;  // Must have been undefs.
664
665      LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
666      LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
667    }
668    // Finally, check the least significant entry.
669    if (LeadingZero) {
670      if (UniquedVals[Multiple-1].getNode() == 0)
671        return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
672      int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
673      if (Val < 16)
674        return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
675    }
676    if (LeadingOnes) {
677      if (UniquedVals[Multiple-1].getNode() == 0)
678        return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
679      int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
680      if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
681        return DAG.getTargetConstant(Val, MVT::i32);
682    }
683
684    return SDValue();
685  }
686
687  // Check to see if this buildvec has a single non-undef value in its elements.
688  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
689    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
690    if (OpVal.getNode() == 0)
691      OpVal = N->getOperand(i);
692    else if (OpVal != N->getOperand(i))
693      return SDValue();
694  }
695
696  if (OpVal.getNode() == 0) return SDValue();  // All UNDEF: use implicit def.
697
698  unsigned ValSizeInBytes = EltSize;
699  uint64_t Value = 0;
700  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
701    Value = CN->getZExtValue();
702  } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
703    assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
704    Value = FloatToBits(CN->getValueAPF().convertToFloat());
705  }
706
707  // If the splat value is larger than the element value, then we can never do
708  // this splat.  The only case that we could fit the replicated bits into our
709  // immediate field for would be zero, and we prefer to use vxor for it.
710  if (ValSizeInBytes < ByteSize) return SDValue();
711
712  // If the element value is larger than the splat value, cut it in half and
713  // check to see if the two halves are equal.  Continue doing this until we
714  // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
715  while (ValSizeInBytes > ByteSize) {
716    ValSizeInBytes >>= 1;
717
718    // If the top half equals the bottom half, we're still ok.
719    if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
720         (Value                        & ((1 << (8*ValSizeInBytes))-1)))
721      return SDValue();
722  }
723
724  // Properly sign extend the value.
725  int ShAmt = (4-ByteSize)*8;
726  int MaskVal = ((int)Value << ShAmt) >> ShAmt;
727
728  // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
729  if (MaskVal == 0) return SDValue();
730
731  // Finally, if this value fits in a 5 bit sext field, return it
732  if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
733    return DAG.getTargetConstant(MaskVal, MVT::i32);
734  return SDValue();
735}
736
737//===----------------------------------------------------------------------===//
738//  Addressing Mode Selection
739//===----------------------------------------------------------------------===//
740
741/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
742/// or 64-bit immediate, and if the value can be accurately represented as a
743/// sign extension from a 16-bit value.  If so, this returns true and the
744/// immediate.
745static bool isIntS16Immediate(SDNode *N, short &Imm) {
746  if (N->getOpcode() != ISD::Constant)
747    return false;
748
749  Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
750  if (N->getValueType(0) == MVT::i32)
751    return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
752  else
753    return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
754}
755static bool isIntS16Immediate(SDValue Op, short &Imm) {
756  return isIntS16Immediate(Op.getNode(), Imm);
757}
758
759
760/// SelectAddressRegReg - Given the specified addressed, check to see if it
761/// can be represented as an indexed [r+r] operation.  Returns false if it
762/// can be more efficiently represented with [r+imm].
763bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
764                                            SDValue &Index,
765                                            SelectionDAG &DAG) const {
766  short imm = 0;
767  if (N.getOpcode() == ISD::ADD) {
768    if (isIntS16Immediate(N.getOperand(1), imm))
769      return false;    // r+i
770    if (N.getOperand(1).getOpcode() == PPCISD::Lo)
771      return false;    // r+i
772
773    Base = N.getOperand(0);
774    Index = N.getOperand(1);
775    return true;
776  } else if (N.getOpcode() == ISD::OR) {
777    if (isIntS16Immediate(N.getOperand(1), imm))
778      return false;    // r+i can fold it if we can.
779
780    // If this is an or of disjoint bitfields, we can codegen this as an add
781    // (for better address arithmetic) if the LHS and RHS of the OR are provably
782    // disjoint.
783    APInt LHSKnownZero, LHSKnownOne;
784    APInt RHSKnownZero, RHSKnownOne;
785    DAG.ComputeMaskedBits(N.getOperand(0),
786                          APInt::getAllOnesValue(N.getOperand(0)
787                            .getValueSizeInBits()),
788                          LHSKnownZero, LHSKnownOne);
789
790    if (LHSKnownZero.getBoolValue()) {
791      DAG.ComputeMaskedBits(N.getOperand(1),
792                            APInt::getAllOnesValue(N.getOperand(1)
793                              .getValueSizeInBits()),
794                            RHSKnownZero, RHSKnownOne);
795      // If all of the bits are known zero on the LHS or RHS, the add won't
796      // carry.
797      if (~(LHSKnownZero | RHSKnownZero) == 0) {
798        Base = N.getOperand(0);
799        Index = N.getOperand(1);
800        return true;
801      }
802    }
803  }
804
805  return false;
806}
807
808/// Returns true if the address N can be represented by a base register plus
809/// a signed 16-bit displacement [r+imm], and if it is not better
810/// represented as reg+reg.
811bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
812                                            SDValue &Base,
813                                            SelectionDAG &DAG) const {
814  // FIXME dl should come from parent load or store, not from address
815  DebugLoc dl = N.getDebugLoc();
816  // If this can be more profitably realized as r+r, fail.
817  if (SelectAddressRegReg(N, Disp, Base, DAG))
818    return false;
819
820  if (N.getOpcode() == ISD::ADD) {
821    short imm = 0;
822    if (isIntS16Immediate(N.getOperand(1), imm)) {
823      Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
824      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
825        Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
826      } else {
827        Base = N.getOperand(0);
828      }
829      return true; // [r+i]
830    } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
831      // Match LOAD (ADD (X, Lo(G))).
832     assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
833             && "Cannot handle constant offsets yet!");
834      Disp = N.getOperand(1).getOperand(0);  // The global address.
835      assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
836             Disp.getOpcode() == ISD::TargetConstantPool ||
837             Disp.getOpcode() == ISD::TargetJumpTable);
838      Base = N.getOperand(0);
839      return true;  // [&g+r]
840    }
841  } else if (N.getOpcode() == ISD::OR) {
842    short imm = 0;
843    if (isIntS16Immediate(N.getOperand(1), imm)) {
844      // If this is an or of disjoint bitfields, we can codegen this as an add
845      // (for better address arithmetic) if the LHS and RHS of the OR are
846      // provably disjoint.
847      APInt LHSKnownZero, LHSKnownOne;
848      DAG.ComputeMaskedBits(N.getOperand(0),
849                            APInt::getAllOnesValue(N.getOperand(0)
850                                                   .getValueSizeInBits()),
851                            LHSKnownZero, LHSKnownOne);
852
853      if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
854        // If all of the bits are known zero on the LHS or RHS, the add won't
855        // carry.
856        Base = N.getOperand(0);
857        Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
858        return true;
859      }
860    }
861  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
862    // Loading from a constant address.
863
864    // If this address fits entirely in a 16-bit sext immediate field, codegen
865    // this as "d, 0"
866    short Imm;
867    if (isIntS16Immediate(CN, Imm)) {
868      Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
869      Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
870      return true;
871    }
872
873    // Handle 32-bit sext immediates with LIS + addr mode.
874    if (CN->getValueType(0) == MVT::i32 ||
875        (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
876      int Addr = (int)CN->getZExtValue();
877
878      // Otherwise, break this down into an LIS + disp.
879      Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
880
881      Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
882      unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
883      Base = SDValue(DAG.getTargetNode(Opc, dl, CN->getValueType(0), Base), 0);
884      return true;
885    }
886  }
887
888  Disp = DAG.getTargetConstant(0, getPointerTy());
889  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
890    Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
891  else
892    Base = N;
893  return true;      // [r+0]
894}
895
896/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
897/// represented as an indexed [r+r] operation.
898bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
899                                                SDValue &Index,
900                                                SelectionDAG &DAG) const {
901  // Check to see if we can easily represent this as an [r+r] address.  This
902  // will fail if it thinks that the address is more profitably represented as
903  // reg+imm, e.g. where imm = 0.
904  if (SelectAddressRegReg(N, Base, Index, DAG))
905    return true;
906
907  // If the operand is an addition, always emit this as [r+r], since this is
908  // better (for code size, and execution, as the memop does the add for free)
909  // than emitting an explicit add.
910  if (N.getOpcode() == ISD::ADD) {
911    Base = N.getOperand(0);
912    Index = N.getOperand(1);
913    return true;
914  }
915
916  // Otherwise, do it the hard way, using R0 as the base register.
917  Base = DAG.getRegister(PPC::R0, N.getValueType());
918  Index = N;
919  return true;
920}
921
922/// SelectAddressRegImmShift - Returns true if the address N can be
923/// represented by a base register plus a signed 14-bit displacement
924/// [r+imm*4].  Suitable for use by STD and friends.
925bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
926                                                 SDValue &Base,
927                                                 SelectionDAG &DAG) const {
928  // FIXME dl should come from the parent load or store, not the address
929  DebugLoc dl = N.getDebugLoc();
930  // If this can be more profitably realized as r+r, fail.
931  if (SelectAddressRegReg(N, Disp, Base, DAG))
932    return false;
933
934  if (N.getOpcode() == ISD::ADD) {
935    short imm = 0;
936    if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
937      Disp =  DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
938      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
939        Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
940      } else {
941        Base = N.getOperand(0);
942      }
943      return true; // [r+i]
944    } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
945      // Match LOAD (ADD (X, Lo(G))).
946     assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
947             && "Cannot handle constant offsets yet!");
948      Disp = N.getOperand(1).getOperand(0);  // The global address.
949      assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
950             Disp.getOpcode() == ISD::TargetConstantPool ||
951             Disp.getOpcode() == ISD::TargetJumpTable);
952      Base = N.getOperand(0);
953      return true;  // [&g+r]
954    }
955  } else if (N.getOpcode() == ISD::OR) {
956    short imm = 0;
957    if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
958      // If this is an or of disjoint bitfields, we can codegen this as an add
959      // (for better address arithmetic) if the LHS and RHS of the OR are
960      // provably disjoint.
961      APInt LHSKnownZero, LHSKnownOne;
962      DAG.ComputeMaskedBits(N.getOperand(0),
963                            APInt::getAllOnesValue(N.getOperand(0)
964                                                   .getValueSizeInBits()),
965                            LHSKnownZero, LHSKnownOne);
966      if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
967        // If all of the bits are known zero on the LHS or RHS, the add won't
968        // carry.
969        Base = N.getOperand(0);
970        Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
971        return true;
972      }
973    }
974  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
975    // Loading from a constant address.  Verify low two bits are clear.
976    if ((CN->getZExtValue() & 3) == 0) {
977      // If this address fits entirely in a 14-bit sext immediate field, codegen
978      // this as "d, 0"
979      short Imm;
980      if (isIntS16Immediate(CN, Imm)) {
981        Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
982        Base = DAG.getRegister(PPC::R0, CN->getValueType(0));
983        return true;
984      }
985
986      // Fold the low-part of 32-bit absolute addresses into addr mode.
987      if (CN->getValueType(0) == MVT::i32 ||
988          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
989        int Addr = (int)CN->getZExtValue();
990
991        // Otherwise, break this down into an LIS + disp.
992        Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
993        Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
994        unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
995        Base = SDValue(DAG.getTargetNode(Opc, dl, CN->getValueType(0), Base),0);
996        return true;
997      }
998    }
999  }
1000
1001  Disp = DAG.getTargetConstant(0, getPointerTy());
1002  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1003    Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1004  else
1005    Base = N;
1006  return true;      // [r+0]
1007}
1008
1009
1010/// getPreIndexedAddressParts - returns true by value, base pointer and
1011/// offset pointer and addressing mode by reference if the node's address
1012/// can be legally represented as pre-indexed load / store address.
1013bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1014                                                  SDValue &Offset,
1015                                                  ISD::MemIndexedMode &AM,
1016                                                  SelectionDAG &DAG) const {
1017  // Disabled by default for now.
1018  if (!EnablePPCPreinc) return false;
1019
1020  SDValue Ptr;
1021  MVT VT;
1022  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1023    Ptr = LD->getBasePtr();
1024    VT = LD->getMemoryVT();
1025
1026  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1027    ST = ST;
1028    Ptr = ST->getBasePtr();
1029    VT  = ST->getMemoryVT();
1030  } else
1031    return false;
1032
1033  // PowerPC doesn't have preinc load/store instructions for vectors.
1034  if (VT.isVector())
1035    return false;
1036
1037  // TODO: Check reg+reg first.
1038
1039  // LDU/STU use reg+imm*4, others use reg+imm.
1040  if (VT != MVT::i64) {
1041    // reg + imm
1042    if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1043      return false;
1044  } else {
1045    // reg + imm * 4.
1046    if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1047      return false;
1048  }
1049
1050  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1051    // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1052    // sext i32 to i64 when addr mode is r+i.
1053    if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1054        LD->getExtensionType() == ISD::SEXTLOAD &&
1055        isa<ConstantSDNode>(Offset))
1056      return false;
1057  }
1058
1059  AM = ISD::PRE_INC;
1060  return true;
1061}
1062
1063//===----------------------------------------------------------------------===//
1064//  LowerOperation implementation
1065//===----------------------------------------------------------------------===//
1066
1067SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1068                                             SelectionDAG &DAG) {
1069  MVT PtrVT = Op.getValueType();
1070  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1071  Constant *C = CP->getConstVal();
1072  SDValue CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
1073  SDValue Zero = DAG.getConstant(0, PtrVT);
1074  // FIXME there isn't really any debug info here
1075  DebugLoc dl = Op.getDebugLoc();
1076
1077  const TargetMachine &TM = DAG.getTarget();
1078
1079  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, CPI, Zero);
1080  SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, CPI, Zero);
1081
1082  // If this is a non-darwin platform, we don't support non-static relo models
1083  // yet.
1084  if (TM.getRelocationModel() == Reloc::Static ||
1085      !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1086    // Generate non-pic code that has direct accesses to the constant pool.
1087    // The address of the global is just (hi(&g)+lo(&g)).
1088    return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1089  }
1090
1091  if (TM.getRelocationModel() == Reloc::PIC_) {
1092    // With PIC, the first instruction is actually "GR+hi(&G)".
1093    Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1094                     DAG.getNode(PPCISD::GlobalBaseReg,
1095                                 DebugLoc::getUnknownLoc(), PtrVT), Hi);
1096  }
1097
1098  Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1099  return Lo;
1100}
1101
1102SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
1103  MVT PtrVT = Op.getValueType();
1104  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1105  SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1106  SDValue Zero = DAG.getConstant(0, PtrVT);
1107  // FIXME there isn't really any debug loc here
1108  DebugLoc dl = Op.getDebugLoc();
1109
1110  const TargetMachine &TM = DAG.getTarget();
1111
1112  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, JTI, Zero);
1113  SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, JTI, Zero);
1114
1115  // If this is a non-darwin platform, we don't support non-static relo models
1116  // yet.
1117  if (TM.getRelocationModel() == Reloc::Static ||
1118      !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1119    // Generate non-pic code that has direct accesses to the constant pool.
1120    // The address of the global is just (hi(&g)+lo(&g)).
1121    return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1122  }
1123
1124  if (TM.getRelocationModel() == Reloc::PIC_) {
1125    // With PIC, the first instruction is actually "GR+hi(&G)".
1126    Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1127                     DAG.getNode(PPCISD::GlobalBaseReg,
1128                                 DebugLoc::getUnknownLoc(), PtrVT), Hi);
1129  }
1130
1131  Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1132  return Lo;
1133}
1134
1135SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1136                                                   SelectionDAG &DAG) {
1137  assert(0 && "TLS not implemented for PPC.");
1138  return SDValue(); // Not reached
1139}
1140
1141SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1142                                              SelectionDAG &DAG) {
1143  MVT PtrVT = Op.getValueType();
1144  GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1145  GlobalValue *GV = GSDN->getGlobal();
1146  SDValue GA = DAG.getTargetGlobalAddress(GV, PtrVT, GSDN->getOffset());
1147  SDValue Zero = DAG.getConstant(0, PtrVT);
1148  // FIXME there isn't really any debug info here
1149  DebugLoc dl = GSDN->getDebugLoc();
1150
1151  const TargetMachine &TM = DAG.getTarget();
1152
1153  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, GA, Zero);
1154  SDValue Lo = DAG.getNode(PPCISD::Lo, dl, PtrVT, GA, Zero);
1155
1156  // If this is a non-darwin platform, we don't support non-static relo models
1157  // yet.
1158  if (TM.getRelocationModel() == Reloc::Static ||
1159      !TM.getSubtarget<PPCSubtarget>().isDarwin()) {
1160    // Generate non-pic code that has direct accesses to globals.
1161    // The address of the global is just (hi(&g)+lo(&g)).
1162    return DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1163  }
1164
1165  if (TM.getRelocationModel() == Reloc::PIC_) {
1166    // With PIC, the first instruction is actually "GR+hi(&G)".
1167    Hi = DAG.getNode(ISD::ADD, dl, PtrVT,
1168                     DAG.getNode(PPCISD::GlobalBaseReg,
1169                                 DebugLoc::getUnknownLoc(), PtrVT), Hi);
1170  }
1171
1172  Lo = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1173
1174  if (!TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV))
1175    return Lo;
1176
1177  // If the global is weak or external, we have to go through the lazy
1178  // resolution stub.
1179  return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Lo, NULL, 0);
1180}
1181
1182SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
1183  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1184  DebugLoc dl = Op.getDebugLoc();
1185
1186  // If we're comparing for equality to zero, expose the fact that this is
1187  // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1188  // fold the new nodes.
1189  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1190    if (C->isNullValue() && CC == ISD::SETEQ) {
1191      MVT VT = Op.getOperand(0).getValueType();
1192      SDValue Zext = Op.getOperand(0);
1193      if (VT.bitsLT(MVT::i32)) {
1194        VT = MVT::i32;
1195        Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1196      }
1197      unsigned Log2b = Log2_32(VT.getSizeInBits());
1198      SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1199      SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1200                                DAG.getConstant(Log2b, MVT::i32));
1201      return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1202    }
1203    // Leave comparisons against 0 and -1 alone for now, since they're usually
1204    // optimized.  FIXME: revisit this when we can custom lower all setcc
1205    // optimizations.
1206    if (C->isAllOnesValue() || C->isNullValue())
1207      return SDValue();
1208  }
1209
1210  // If we have an integer seteq/setne, turn it into a compare against zero
1211  // by xor'ing the rhs with the lhs, which is faster than setting a
1212  // condition register, reading it back out, and masking the correct bit.  The
1213  // normal approach here uses sub to do this instead of xor.  Using xor exposes
1214  // the result to other bit-twiddling opportunities.
1215  MVT LHSVT = Op.getOperand(0).getValueType();
1216  if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1217    MVT VT = Op.getValueType();
1218    SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1219                                Op.getOperand(1));
1220    return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1221  }
1222  return SDValue();
1223}
1224
1225SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1226                              int VarArgsFrameIndex,
1227                              int VarArgsStackOffset,
1228                              unsigned VarArgsNumGPR,
1229                              unsigned VarArgsNumFPR,
1230                              const PPCSubtarget &Subtarget) {
1231
1232  assert(0 && "VAARG in ELF32 ABI not implemented yet!");
1233  return SDValue(); // Not reached
1234}
1235
1236SDValue PPCTargetLowering::LowerTRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
1237  SDValue Chain = Op.getOperand(0);
1238  SDValue Trmp = Op.getOperand(1); // trampoline
1239  SDValue FPtr = Op.getOperand(2); // nested function
1240  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1241  DebugLoc dl = Op.getDebugLoc();
1242
1243  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1244  bool isPPC64 = (PtrVT == MVT::i64);
1245  const Type *IntPtrTy =
1246    DAG.getTargetLoweringInfo().getTargetData()->getIntPtrType();
1247
1248  TargetLowering::ArgListTy Args;
1249  TargetLowering::ArgListEntry Entry;
1250
1251  Entry.Ty = IntPtrTy;
1252  Entry.Node = Trmp; Args.push_back(Entry);
1253
1254  // TrampSize == (isPPC64 ? 48 : 40);
1255  Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1256                               isPPC64 ? MVT::i64 : MVT::i32);
1257  Args.push_back(Entry);
1258
1259  Entry.Node = FPtr; Args.push_back(Entry);
1260  Entry.Node = Nest; Args.push_back(Entry);
1261
1262  // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1263  std::pair<SDValue, SDValue> CallResult =
1264    LowerCallTo(Chain, Op.getValueType().getTypeForMVT(), false, false,
1265                false, false, CallingConv::C, false,
1266                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1267                Args, DAG, dl);
1268
1269  SDValue Ops[] =
1270    { CallResult.first, CallResult.second };
1271
1272  return DAG.getMergeValues(Ops, 2, dl);
1273}
1274
1275SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1276                                        int VarArgsFrameIndex,
1277                                        int VarArgsStackOffset,
1278                                        unsigned VarArgsNumGPR,
1279                                        unsigned VarArgsNumFPR,
1280                                        const PPCSubtarget &Subtarget) {
1281  DebugLoc dl = Op.getDebugLoc();
1282
1283  if (Subtarget.isMachoABI()) {
1284    // vastart just stores the address of the VarArgsFrameIndex slot into the
1285    // memory location argument.
1286    MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1287    SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1288    const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1289    return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1290  }
1291
1292  // For ELF 32 ABI we follow the layout of the va_list struct.
1293  // We suppose the given va_list is already allocated.
1294  //
1295  // typedef struct {
1296  //  char gpr;     /* index into the array of 8 GPRs
1297  //                 * stored in the register save area
1298  //                 * gpr=0 corresponds to r3,
1299  //                 * gpr=1 to r4, etc.
1300  //                 */
1301  //  char fpr;     /* index into the array of 8 FPRs
1302  //                 * stored in the register save area
1303  //                 * fpr=0 corresponds to f1,
1304  //                 * fpr=1 to f2, etc.
1305  //                 */
1306  //  char *overflow_arg_area;
1307  //                /* location on stack that holds
1308  //                 * the next overflow argument
1309  //                 */
1310  //  char *reg_save_area;
1311  //               /* where r3:r10 and f1:f8 (if saved)
1312  //                * are stored
1313  //                */
1314  // } va_list[1];
1315
1316
1317  SDValue ArgGPR = DAG.getConstant(VarArgsNumGPR, MVT::i8);
1318  SDValue ArgFPR = DAG.getConstant(VarArgsNumFPR, MVT::i8);
1319
1320
1321  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1322
1323  SDValue StackOffsetFI = DAG.getFrameIndex(VarArgsStackOffset, PtrVT);
1324  SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1325
1326  uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1327  SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1328
1329  uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1330  SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1331
1332  uint64_t FPROffset = 1;
1333  SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1334
1335  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1336
1337  // Store first byte : number of int regs
1338  SDValue firstStore = DAG.getStore(Op.getOperand(0), dl, ArgGPR,
1339                                      Op.getOperand(1), SV, 0);
1340  uint64_t nextOffset = FPROffset;
1341  SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1342                                  ConstFPROffset);
1343
1344  // Store second byte : number of float regs
1345  SDValue secondStore =
1346    DAG.getStore(firstStore, dl, ArgFPR, nextPtr, SV, nextOffset);
1347  nextOffset += StackOffset;
1348  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1349
1350  // Store second word : arguments given on stack
1351  SDValue thirdStore =
1352    DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, SV, nextOffset);
1353  nextOffset += FrameOffset;
1354  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1355
1356  // Store third word : arguments given in registers
1357  return DAG.getStore(thirdStore, dl, FR, nextPtr, SV, nextOffset);
1358
1359}
1360
1361#include "PPCGenCallingConv.inc"
1362
1363/// GetFPR - Get the set of FP registers that should be allocated for arguments,
1364/// depending on which subtarget is selected.
1365static const unsigned *GetFPR(const PPCSubtarget &Subtarget) {
1366  if (Subtarget.isMachoABI()) {
1367    static const unsigned FPR[] = {
1368      PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1369      PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1370    };
1371    return FPR;
1372  }
1373
1374
1375  static const unsigned FPR[] = {
1376    PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1377    PPC::F8
1378  };
1379  return FPR;
1380}
1381
1382/// CalculateStackSlotSize - Calculates the size reserved for this argument on
1383/// the stack.
1384static unsigned CalculateStackSlotSize(SDValue Arg, ISD::ArgFlagsTy Flags,
1385                                       bool isVarArg, unsigned PtrByteSize) {
1386  MVT ArgVT = Arg.getValueType();
1387  unsigned ArgSize =ArgVT.getSizeInBits()/8;
1388  if (Flags.isByVal())
1389    ArgSize = Flags.getByValSize();
1390  ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1391
1392  return ArgSize;
1393}
1394
1395SDValue
1396PPCTargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op,
1397                                         SelectionDAG &DAG,
1398                                         int &VarArgsFrameIndex,
1399                                         int &VarArgsStackOffset,
1400                                         unsigned &VarArgsNumGPR,
1401                                         unsigned &VarArgsNumFPR,
1402                                         const PPCSubtarget &Subtarget) {
1403  // TODO: add description of PPC stack frame format, or at least some docs.
1404  //
1405  MachineFunction &MF = DAG.getMachineFunction();
1406  MachineFrameInfo *MFI = MF.getFrameInfo();
1407  MachineRegisterInfo &RegInfo = MF.getRegInfo();
1408  SmallVector<SDValue, 8> ArgValues;
1409  SDValue Root = Op.getOperand(0);
1410  bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1411  DebugLoc dl = Op.getDebugLoc();
1412
1413  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1414  bool isPPC64 = PtrVT == MVT::i64;
1415  bool isMachoABI = Subtarget.isMachoABI();
1416  bool isELF32_ABI = Subtarget.isELF32_ABI();
1417  // Potential tail calls could cause overwriting of argument stack slots.
1418  unsigned CC = MF.getFunction()->getCallingConv();
1419  bool isImmutable = !(PerformTailCallOpt && (CC==CallingConv::Fast));
1420  unsigned PtrByteSize = isPPC64 ? 8 : 4;
1421
1422  unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1423  // Area that is at least reserved in caller of this function.
1424  unsigned MinReservedArea = ArgOffset;
1425
1426  static const unsigned GPR_32[] = {           // 32-bit registers.
1427    PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1428    PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1429  };
1430  static const unsigned GPR_64[] = {           // 64-bit registers.
1431    PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1432    PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1433  };
1434
1435  static const unsigned *FPR = GetFPR(Subtarget);
1436
1437  static const unsigned VR[] = {
1438    PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1439    PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1440  };
1441
1442  const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
1443  const unsigned Num_FPR_Regs = isMachoABI ? 13 : 8;
1444  const unsigned Num_VR_Regs  = array_lengthof( VR);
1445
1446  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1447
1448  const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
1449
1450  // In 32-bit non-varargs functions, the stack space for vectors is after the
1451  // stack space for non-vectors.  We do not use this space unless we have
1452  // too many vectors to fit in registers, something that only occurs in
1453  // constructed examples:), but we have to walk the arglist to figure
1454  // that out...for the pathological case, compute VecArgOffset as the
1455  // start of the vector parameter area.  Computing VecArgOffset is the
1456  // entire point of the following loop.
1457  // Altivec is not mentioned in the ppc32 Elf Supplement, so I'm not trying
1458  // to handle Elf here.
1459  unsigned VecArgOffset = ArgOffset;
1460  if (!isVarArg && !isPPC64) {
1461    for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues()-1; ArgNo != e;
1462         ++ArgNo) {
1463      MVT ObjectVT = Op.getValue(ArgNo).getValueType();
1464      unsigned ObjSize = ObjectVT.getSizeInBits()/8;
1465      ISD::ArgFlagsTy Flags =
1466        cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1467
1468      if (Flags.isByVal()) {
1469        // ObjSize is the true size, ArgSize rounded up to multiple of regs.
1470        ObjSize = Flags.getByValSize();
1471        unsigned ArgSize =
1472                ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1473        VecArgOffset += ArgSize;
1474        continue;
1475      }
1476
1477      switch(ObjectVT.getSimpleVT()) {
1478      default: assert(0 && "Unhandled argument type!");
1479      case MVT::i32:
1480      case MVT::f32:
1481        VecArgOffset += isPPC64 ? 8 : 4;
1482        break;
1483      case MVT::i64:  // PPC64
1484      case MVT::f64:
1485        VecArgOffset += 8;
1486        break;
1487      case MVT::v4f32:
1488      case MVT::v4i32:
1489      case MVT::v8i16:
1490      case MVT::v16i8:
1491        // Nothing to do, we're only looking at Nonvector args here.
1492        break;
1493      }
1494    }
1495  }
1496  // We've found where the vector parameter area in memory is.  Skip the
1497  // first 12 parameters; these don't use that memory.
1498  VecArgOffset = ((VecArgOffset+15)/16)*16;
1499  VecArgOffset += 12*16;
1500
1501  // Add DAG nodes to load the arguments or copy them out of registers.  On
1502  // entry to a function on PPC, the arguments start after the linkage area,
1503  // although the first ones are often in registers.
1504  //
1505  // In the ELF 32 ABI, GPRs and stack are double word align: an argument
1506  // represented with two words (long long or double) must be copied to an
1507  // even GPR_idx value or to an even ArgOffset value.
1508
1509  SmallVector<SDValue, 8> MemOps;
1510  unsigned nAltivecParamsAtEnd = 0;
1511  for (unsigned ArgNo = 0, e = Op.getNode()->getNumValues() - 1;
1512       ArgNo != e; ++ArgNo) {
1513    SDValue ArgVal;
1514    bool needsLoad = false;
1515    MVT ObjectVT = Op.getValue(ArgNo).getValueType();
1516    unsigned ObjSize = ObjectVT.getSizeInBits()/8;
1517    unsigned ArgSize = ObjSize;
1518    ISD::ArgFlagsTy Flags =
1519      cast<ARG_FLAGSSDNode>(Op.getOperand(ArgNo+3))->getArgFlags();
1520    // See if next argument requires stack alignment in ELF
1521    bool Align = Flags.isSplit();
1522
1523    unsigned CurArgOffset = ArgOffset;
1524
1525    // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
1526    if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
1527        ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
1528      if (isVarArg || isPPC64) {
1529        MinReservedArea = ((MinReservedArea+15)/16)*16;
1530        MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
1531                                                  Flags,
1532                                                  isVarArg,
1533                                                  PtrByteSize);
1534      } else  nAltivecParamsAtEnd++;
1535    } else
1536      // Calculate min reserved area.
1537      MinReservedArea += CalculateStackSlotSize(Op.getValue(ArgNo),
1538                                                Flags,
1539                                                isVarArg,
1540                                                PtrByteSize);
1541
1542    // FIXME alignment for ELF may not be right
1543    // FIXME the codegen can be much improved in some cases.
1544    // We do not have to keep everything in memory.
1545    if (Flags.isByVal()) {
1546      // ObjSize is the true size, ArgSize rounded up to multiple of registers.
1547      ObjSize = Flags.getByValSize();
1548      ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1549      // Double word align in ELF
1550      if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
1551      // Objects of size 1 and 2 are right justified, everything else is
1552      // left justified.  This means the memory address is adjusted forwards.
1553      if (ObjSize==1 || ObjSize==2) {
1554        CurArgOffset = CurArgOffset + (4 - ObjSize);
1555      }
1556      // The value of the object is its address.
1557      int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset);
1558      SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1559      ArgValues.push_back(FIN);
1560      if (ObjSize==1 || ObjSize==2) {
1561        if (GPR_idx != Num_GPR_Regs) {
1562          unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1563          RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1564          SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1565          SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
1566                               NULL, 0, ObjSize==1 ? MVT::i8 : MVT::i16 );
1567          MemOps.push_back(Store);
1568          ++GPR_idx;
1569          if (isMachoABI) ArgOffset += PtrByteSize;
1570        } else {
1571          ArgOffset += PtrByteSize;
1572        }
1573        continue;
1574      }
1575      for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
1576        // Store whatever pieces of the object are in registers
1577        // to memory.  ArgVal will be address of the beginning of
1578        // the object.
1579        if (GPR_idx != Num_GPR_Regs) {
1580          unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1581          RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1582          int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset);
1583          SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1584          SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1585          SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1586          MemOps.push_back(Store);
1587          ++GPR_idx;
1588          if (isMachoABI) ArgOffset += PtrByteSize;
1589        } else {
1590          ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
1591          break;
1592        }
1593      }
1594      continue;
1595    }
1596
1597    switch (ObjectVT.getSimpleVT()) {
1598    default: assert(0 && "Unhandled argument type!");
1599    case MVT::i32:
1600      if (!isPPC64) {
1601        // Double word align in ELF
1602        if (Align && isELF32_ABI) GPR_idx += (GPR_idx % 2);
1603
1604        if (GPR_idx != Num_GPR_Regs) {
1605          unsigned VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1606          RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1607          ArgVal = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
1608          ++GPR_idx;
1609        } else {
1610          needsLoad = true;
1611          ArgSize = PtrByteSize;
1612        }
1613        // Stack align in ELF
1614        if (needsLoad && Align && isELF32_ABI)
1615          ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1616        // All int arguments reserve stack space in Macho ABI.
1617        if (isMachoABI || needsLoad) ArgOffset += PtrByteSize;
1618        break;
1619      }
1620      // FALLTHROUGH
1621    case MVT::i64:  // PPC64
1622      if (GPR_idx != Num_GPR_Regs) {
1623        unsigned VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
1624        RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1625        ArgVal = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1626
1627        if (ObjectVT == MVT::i32) {
1628          // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
1629          // value to MVT::i64 and then truncate to the correct register size.
1630          if (Flags.isSExt())
1631            ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
1632                                 DAG.getValueType(ObjectVT));
1633          else if (Flags.isZExt())
1634            ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
1635                                 DAG.getValueType(ObjectVT));
1636
1637          ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
1638        }
1639
1640        ++GPR_idx;
1641      } else {
1642        needsLoad = true;
1643        ArgSize = PtrByteSize;
1644      }
1645      // All int arguments reserve stack space in Macho ABI.
1646      if (isMachoABI || needsLoad) ArgOffset += 8;
1647      break;
1648
1649    case MVT::f32:
1650    case MVT::f64:
1651      // Every 4 bytes of argument space consumes one of the GPRs available for
1652      // argument passing.
1653      if (GPR_idx != Num_GPR_Regs && isMachoABI) {
1654        ++GPR_idx;
1655        if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
1656          ++GPR_idx;
1657      }
1658      if (FPR_idx != Num_FPR_Regs) {
1659        unsigned VReg;
1660        if (ObjectVT == MVT::f32)
1661          VReg = RegInfo.createVirtualRegister(&PPC::F4RCRegClass);
1662        else
1663          VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
1664        RegInfo.addLiveIn(FPR[FPR_idx], VReg);
1665        ArgVal = DAG.getCopyFromReg(Root, dl, VReg, ObjectVT);
1666        ++FPR_idx;
1667      } else {
1668        needsLoad = true;
1669      }
1670
1671      // Stack align in ELF
1672      if (needsLoad && Align && isELF32_ABI)
1673        ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
1674      // All FP arguments reserve stack space in Macho ABI.
1675      if (isMachoABI || needsLoad) ArgOffset += isPPC64 ? 8 : ObjSize;
1676      break;
1677    case MVT::v4f32:
1678    case MVT::v4i32:
1679    case MVT::v8i16:
1680    case MVT::v16i8:
1681      // Note that vector arguments in registers don't reserve stack space,
1682      // except in varargs functions.
1683      if (VR_idx != Num_VR_Regs) {
1684        unsigned VReg = RegInfo.createVirtualRegister(&PPC::VRRCRegClass);
1685        RegInfo.addLiveIn(VR[VR_idx], VReg);
1686        ArgVal = DAG.getCopyFromReg(Root, dl, VReg, ObjectVT);
1687        if (isVarArg) {
1688          while ((ArgOffset % 16) != 0) {
1689            ArgOffset += PtrByteSize;
1690            if (GPR_idx != Num_GPR_Regs)
1691              GPR_idx++;
1692          }
1693          ArgOffset += 16;
1694          GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs);
1695        }
1696        ++VR_idx;
1697      } else {
1698        if (!isVarArg && !isPPC64) {
1699          // Vectors go after all the nonvectors.
1700          CurArgOffset = VecArgOffset;
1701          VecArgOffset += 16;
1702        } else {
1703          // Vectors are aligned.
1704          ArgOffset = ((ArgOffset+15)/16)*16;
1705          CurArgOffset = ArgOffset;
1706          ArgOffset += 16;
1707        }
1708        needsLoad = true;
1709      }
1710      break;
1711    }
1712
1713    // We need to load the argument to a virtual register if we determined above
1714    // that we ran out of physical registers of the appropriate type.
1715    if (needsLoad) {
1716      int FI = MFI->CreateFixedObject(ObjSize,
1717                                      CurArgOffset + (ArgSize - ObjSize),
1718                                      isImmutable);
1719      SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1720      ArgVal = DAG.getLoad(ObjectVT, dl, Root, FIN, NULL, 0);
1721    }
1722
1723    ArgValues.push_back(ArgVal);
1724  }
1725
1726  // Set the size that is at least reserved in caller of this function.  Tail
1727  // call optimized function's reserved stack space needs to be aligned so that
1728  // taking the difference between two stack areas will result in an aligned
1729  // stack.
1730  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1731  // Add the Altivec parameters at the end, if needed.
1732  if (nAltivecParamsAtEnd) {
1733    MinReservedArea = ((MinReservedArea+15)/16)*16;
1734    MinReservedArea += 16*nAltivecParamsAtEnd;
1735  }
1736  MinReservedArea =
1737    std::max(MinReservedArea,
1738             PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
1739  unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
1740    getStackAlignment();
1741  unsigned AlignMask = TargetAlign-1;
1742  MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1743  FI->setMinReservedArea(MinReservedArea);
1744
1745  // If the function takes variable number of arguments, make a frame index for
1746  // the start of the first vararg value... for expansion of llvm.va_start.
1747  if (isVarArg) {
1748
1749    int depth;
1750    if (isELF32_ABI) {
1751      VarArgsNumGPR = GPR_idx;
1752      VarArgsNumFPR = FPR_idx;
1753
1754      // Make room for Num_GPR_Regs, Num_FPR_Regs and for a possible frame
1755      // pointer.
1756      depth = -(Num_GPR_Regs * PtrVT.getSizeInBits()/8 +
1757                Num_FPR_Regs * MVT(MVT::f64).getSizeInBits()/8 +
1758                PtrVT.getSizeInBits()/8);
1759
1760      VarArgsStackOffset = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1761                                                  ArgOffset);
1762
1763    }
1764    else
1765      depth = ArgOffset;
1766
1767    VarArgsFrameIndex = MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1768                                               depth);
1769    SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1770
1771    // In ELF 32 ABI, the fixed integer arguments of a variadic function are
1772    // stored to the VarArgsFrameIndex on the stack.
1773    if (isELF32_ABI) {
1774      for (GPR_idx = 0; GPR_idx != VarArgsNumGPR; ++GPR_idx) {
1775        SDValue Val = DAG.getRegister(GPR[GPR_idx], PtrVT);
1776        SDValue Store = DAG.getStore(Root, dl, Val, FIN, NULL, 0);
1777        MemOps.push_back(Store);
1778        // Increment the address by four for the next argument to store
1779        SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1780        FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1781      }
1782    }
1783
1784    // If this function is vararg, store any remaining integer argument regs
1785    // to their spots on the stack so that they may be loaded by deferencing the
1786    // result of va_next.
1787    for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
1788      unsigned VReg;
1789      if (isPPC64)
1790        VReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
1791      else
1792        VReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
1793
1794      RegInfo.addLiveIn(GPR[GPR_idx], VReg);
1795      SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, PtrVT);
1796      SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1797      MemOps.push_back(Store);
1798      // Increment the address by four for the next argument to store
1799      SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1800      FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1801    }
1802
1803    // In ELF 32 ABI, the double arguments are stored to the VarArgsFrameIndex
1804    // on the stack.
1805    if (isELF32_ABI) {
1806      for (FPR_idx = 0; FPR_idx != VarArgsNumFPR; ++FPR_idx) {
1807        SDValue Val = DAG.getRegister(FPR[FPR_idx], MVT::f64);
1808        SDValue Store = DAG.getStore(Root, dl, Val, FIN, NULL, 0);
1809        MemOps.push_back(Store);
1810        // Increment the address by eight for the next argument to store
1811        SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
1812                                           PtrVT);
1813        FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1814      }
1815
1816      for (; FPR_idx != Num_FPR_Regs; ++FPR_idx) {
1817        unsigned VReg;
1818        VReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
1819
1820        RegInfo.addLiveIn(FPR[FPR_idx], VReg);
1821        SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::f64);
1822        SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1823        MemOps.push_back(Store);
1824        // Increment the address by eight for the next argument to store
1825        SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
1826                                           PtrVT);
1827        FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1828      }
1829    }
1830  }
1831
1832  if (!MemOps.empty())
1833    Root = DAG.getNode(ISD::TokenFactor, dl,
1834                       MVT::Other, &MemOps[0], MemOps.size());
1835
1836  ArgValues.push_back(Root);
1837
1838  // Return the new list of results.
1839  return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1840                     &ArgValues[0], ArgValues.size());
1841}
1842
1843/// CalculateParameterAndLinkageAreaSize - Get the size of the paramter plus
1844/// linkage area.
1845static unsigned
1846CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
1847                                     bool isPPC64,
1848                                     bool isMachoABI,
1849                                     bool isVarArg,
1850                                     unsigned CC,
1851                                     CallSDNode *TheCall,
1852                                     unsigned &nAltivecParamsAtEnd) {
1853  // Count how many bytes are to be pushed on the stack, including the linkage
1854  // area, and parameter passing area.  We start with 24/48 bytes, which is
1855  // prereserved space for [SP][CR][LR][3 x unused].
1856  unsigned NumBytes = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
1857  unsigned NumOps = TheCall->getNumArgs();
1858  unsigned PtrByteSize = isPPC64 ? 8 : 4;
1859
1860  // Add up all the space actually used.
1861  // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
1862  // they all go in registers, but we must reserve stack space for them for
1863  // possible use by the caller.  In varargs or 64-bit calls, parameters are
1864  // assigned stack space in order, with padding so Altivec parameters are
1865  // 16-byte aligned.
1866  nAltivecParamsAtEnd = 0;
1867  for (unsigned i = 0; i != NumOps; ++i) {
1868    SDValue Arg = TheCall->getArg(i);
1869    ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1870    MVT ArgVT = Arg.getValueType();
1871    // Varargs Altivec parameters are padded to a 16 byte boundary.
1872    if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
1873        ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
1874      if (!isVarArg && !isPPC64) {
1875        // Non-varargs Altivec parameters go after all the non-Altivec
1876        // parameters; handle those later so we know how much padding we need.
1877        nAltivecParamsAtEnd++;
1878        continue;
1879      }
1880      // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
1881      NumBytes = ((NumBytes+15)/16)*16;
1882    }
1883    NumBytes += CalculateStackSlotSize(Arg, Flags, isVarArg, PtrByteSize);
1884  }
1885
1886   // Allow for Altivec parameters at the end, if needed.
1887  if (nAltivecParamsAtEnd) {
1888    NumBytes = ((NumBytes+15)/16)*16;
1889    NumBytes += 16*nAltivecParamsAtEnd;
1890  }
1891
1892  // The prolog code of the callee may store up to 8 GPR argument registers to
1893  // the stack, allowing va_start to index over them in memory if its varargs.
1894  // Because we cannot tell if this is needed on the caller side, we have to
1895  // conservatively assume that it is needed.  As such, make sure we have at
1896  // least enough stack space for the caller to store the 8 GPRs.
1897  NumBytes = std::max(NumBytes,
1898                      PPCFrameInfo::getMinCallFrameSize(isPPC64, isMachoABI));
1899
1900  // Tail call needs the stack to be aligned.
1901  if (CC==CallingConv::Fast && PerformTailCallOpt) {
1902    unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameInfo()->
1903      getStackAlignment();
1904    unsigned AlignMask = TargetAlign-1;
1905    NumBytes = (NumBytes + AlignMask) & ~AlignMask;
1906  }
1907
1908  return NumBytes;
1909}
1910
1911/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
1912/// adjusted to accomodate the arguments for the tailcall.
1913static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool IsTailCall,
1914                                   unsigned ParamSize) {
1915
1916  if (!IsTailCall) return 0;
1917
1918  PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
1919  unsigned CallerMinReservedArea = FI->getMinReservedArea();
1920  int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
1921  // Remember only if the new adjustement is bigger.
1922  if (SPDiff < FI->getTailCallSPDelta())
1923    FI->setTailCallSPDelta(SPDiff);
1924
1925  return SPDiff;
1926}
1927
1928/// IsEligibleForTailCallElimination - Check to see whether the next instruction
1929/// following the call is a return. A function is eligible if caller/callee
1930/// calling conventions match, currently only fastcc supports tail calls, and
1931/// the function CALL is immediatly followed by a RET.
1932bool
1933PPCTargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1934                                                     SDValue Ret,
1935                                                     SelectionDAG& DAG) const {
1936  // Variable argument functions are not supported.
1937  if (!PerformTailCallOpt || TheCall->isVarArg())
1938    return false;
1939
1940  if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1941    MachineFunction &MF = DAG.getMachineFunction();
1942    unsigned CallerCC = MF.getFunction()->getCallingConv();
1943    unsigned CalleeCC = TheCall->getCallingConv();
1944    if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1945      // Functions containing by val parameters are not supported.
1946      for (unsigned i = 0; i != TheCall->getNumArgs(); i++) {
1947         ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1948         if (Flags.isByVal()) return false;
1949      }
1950
1951      SDValue Callee = TheCall->getCallee();
1952      // Non PIC/GOT  tail calls are supported.
1953      if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1954        return true;
1955
1956      // At the moment we can only do local tail calls (in same module, hidden
1957      // or protected) if we are generating PIC.
1958      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1959        return G->getGlobal()->hasHiddenVisibility()
1960            || G->getGlobal()->hasProtectedVisibility();
1961    }
1962  }
1963
1964  return false;
1965}
1966
1967/// isCallCompatibleAddress - Return the immediate to use if the specified
1968/// 32-bit value is representable in the immediate field of a BxA instruction.
1969static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
1970  ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
1971  if (!C) return 0;
1972
1973  int Addr = C->getZExtValue();
1974  if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
1975      (Addr << 6 >> 6) != Addr)
1976    return 0;  // Top 6 bits have to be sext of immediate.
1977
1978  return DAG.getConstant((int)C->getZExtValue() >> 2,
1979                         DAG.getTargetLoweringInfo().getPointerTy()).getNode();
1980}
1981
1982namespace {
1983
1984struct TailCallArgumentInfo {
1985  SDValue Arg;
1986  SDValue FrameIdxOp;
1987  int       FrameIdx;
1988
1989  TailCallArgumentInfo() : FrameIdx(0) {}
1990};
1991
1992}
1993
1994/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
1995static void
1996StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
1997                                           SDValue Chain,
1998                   const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
1999                   SmallVector<SDValue, 8> &MemOpChains,
2000                   DebugLoc dl) {
2001  for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2002    SDValue Arg = TailCallArgs[i].Arg;
2003    SDValue FIN = TailCallArgs[i].FrameIdxOp;
2004    int FI = TailCallArgs[i].FrameIdx;
2005    // Store relative to framepointer.
2006    MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2007                                       PseudoSourceValue::getFixedStack(FI),
2008                                       0));
2009  }
2010}
2011
2012/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2013/// the appropriate stack slot for the tail call optimized function call.
2014static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2015                                               MachineFunction &MF,
2016                                               SDValue Chain,
2017                                               SDValue OldRetAddr,
2018                                               SDValue OldFP,
2019                                               int SPDiff,
2020                                               bool isPPC64,
2021                                               bool isMachoABI,
2022                                               DebugLoc dl) {
2023  if (SPDiff) {
2024    // Calculate the new stack slot for the return address.
2025    int SlotSize = isPPC64 ? 8 : 4;
2026    int NewRetAddrLoc = SPDiff + PPCFrameInfo::getReturnSaveOffset(isPPC64,
2027                                                                   isMachoABI);
2028    int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2029                                                          NewRetAddrLoc);
2030    int NewFPLoc = SPDiff + PPCFrameInfo::getFramePointerSaveOffset(isPPC64,
2031                                                                    isMachoABI);
2032    int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc);
2033
2034    MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2035    SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2036    Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2037                         PseudoSourceValue::getFixedStack(NewRetAddr), 0);
2038    SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2039    Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2040                         PseudoSourceValue::getFixedStack(NewFPIdx), 0);
2041  }
2042  return Chain;
2043}
2044
2045/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2046/// the position of the argument.
2047static void
2048CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2049                         SDValue Arg, int SPDiff, unsigned ArgOffset,
2050                      SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2051  int Offset = ArgOffset + SPDiff;
2052  uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2053  int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
2054  MVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2055  SDValue FIN = DAG.getFrameIndex(FI, VT);
2056  TailCallArgumentInfo Info;
2057  Info.Arg = Arg;
2058  Info.FrameIdxOp = FIN;
2059  Info.FrameIdx = FI;
2060  TailCallArguments.push_back(Info);
2061}
2062
2063/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2064/// stack slot. Returns the chain as result and the loaded frame pointers in
2065/// LROpOut/FPOpout. Used when tail calling.
2066SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2067                                                        int SPDiff,
2068                                                        SDValue Chain,
2069                                                        SDValue &LROpOut,
2070                                                        SDValue &FPOpOut,
2071                                                        DebugLoc dl) {
2072  if (SPDiff) {
2073    // Load the LR and FP stack slot for later adjusting.
2074    MVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2075    LROpOut = getReturnAddrFrameIndex(DAG);
2076    LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, NULL, 0);
2077    Chain = SDValue(LROpOut.getNode(), 1);
2078    FPOpOut = getFramePointerFrameIndex(DAG);
2079    FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, NULL, 0);
2080    Chain = SDValue(FPOpOut.getNode(), 1);
2081  }
2082  return Chain;
2083}
2084
2085/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2086/// by "Src" to address "Dst" of size "Size".  Alignment information is
2087/// specified by the specific parameter attribute. The copy will be passed as
2088/// a byval function parameter.
2089/// Sometimes what we are copying is the end of a larger object, the part that
2090/// does not fit in registers.
2091static SDValue
2092CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2093                          ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2094                          unsigned Size, DebugLoc dl) {
2095  SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
2096  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2097                       false, NULL, 0, NULL, 0);
2098}
2099
2100/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
2101/// tail calls.
2102static void
2103LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
2104                 SDValue Arg, SDValue PtrOff, int SPDiff,
2105                 unsigned ArgOffset, bool isPPC64, bool isTailCall,
2106                 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
2107                 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments,
2108                 DebugLoc dl) {
2109  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2110  if (!isTailCall) {
2111    if (isVector) {
2112      SDValue StackPtr;
2113      if (isPPC64)
2114        StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2115      else
2116        StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2117      PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2118                           DAG.getConstant(ArgOffset, PtrVT));
2119    }
2120    MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0));
2121  // Calculate and remember argument location.
2122  } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
2123                                  TailCallArguments);
2124}
2125
2126SDValue PPCTargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG,
2127                                       const PPCSubtarget &Subtarget,
2128                                       TargetMachine &TM) {
2129  CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
2130  SDValue Chain  = TheCall->getChain();
2131  bool isVarArg   = TheCall->isVarArg();
2132  unsigned CC     = TheCall->getCallingConv();
2133  bool isTailCall = TheCall->isTailCall()
2134                 && CC == CallingConv::Fast && PerformTailCallOpt;
2135  SDValue Callee = TheCall->getCallee();
2136  unsigned NumOps  = TheCall->getNumArgs();
2137  DebugLoc dl = TheCall->getDebugLoc();
2138
2139  bool isMachoABI = Subtarget.isMachoABI();
2140  bool isELF32_ABI  = Subtarget.isELF32_ABI();
2141
2142  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2143  bool isPPC64 = PtrVT == MVT::i64;
2144  unsigned PtrByteSize = isPPC64 ? 8 : 4;
2145
2146  MachineFunction &MF = DAG.getMachineFunction();
2147
2148  // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
2149  // SelectExpr to use to put the arguments in the appropriate registers.
2150  std::vector<SDValue> args_to_use;
2151
2152  // Mark this function as potentially containing a function that contains a
2153  // tail call. As a consequence the frame pointer will be used for dynamicalloc
2154  // and restoring the callers stack pointer in this functions epilog. This is
2155  // done because by tail calling the called function might overwrite the value
2156  // in this function's (MF) stack pointer stack slot 0(SP).
2157  if (PerformTailCallOpt && CC==CallingConv::Fast)
2158    MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
2159
2160  unsigned nAltivecParamsAtEnd = 0;
2161
2162  // Count how many bytes are to be pushed on the stack, including the linkage
2163  // area, and parameter passing area.  We start with 24/48 bytes, which is
2164  // prereserved space for [SP][CR][LR][3 x unused].
2165  unsigned NumBytes =
2166    CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isMachoABI, isVarArg, CC,
2167                                         TheCall, nAltivecParamsAtEnd);
2168
2169  // Calculate by how many bytes the stack has to be adjusted in case of tail
2170  // call optimization.
2171  int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
2172
2173  // Adjust the stack pointer for the new arguments...
2174  // These operations are automatically eliminated by the prolog/epilog pass
2175  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2176  SDValue CallSeqStart = Chain;
2177
2178  // Load the return address and frame pointer so it can be move somewhere else
2179  // later.
2180  SDValue LROp, FPOp;
2181  Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
2182
2183  // Set up a copy of the stack pointer for use loading and storing any
2184  // arguments that may not fit in the registers available for argument
2185  // passing.
2186  SDValue StackPtr;
2187  if (isPPC64)
2188    StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2189  else
2190    StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2191
2192  // Figure out which arguments are going to go in registers, and which in
2193  // memory.  Also, if this is a vararg function, floating point operations
2194  // must be stored to our stack, and loaded into integer regs as well, if
2195  // any integer regs are available for argument passing.
2196  unsigned ArgOffset = PPCFrameInfo::getLinkageSize(isPPC64, isMachoABI);
2197  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2198
2199  static const unsigned GPR_32[] = {           // 32-bit registers.
2200    PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2201    PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2202  };
2203  static const unsigned GPR_64[] = {           // 64-bit registers.
2204    PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2205    PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2206  };
2207  static const unsigned *FPR = GetFPR(Subtarget);
2208
2209  static const unsigned VR[] = {
2210    PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2211    PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2212  };
2213  const unsigned NumGPRs = array_lengthof(GPR_32);
2214  const unsigned NumFPRs = isMachoABI ? 13 : 8;
2215  const unsigned NumVRs  = array_lengthof( VR);
2216
2217  const unsigned *GPR = isPPC64 ? GPR_64 : GPR_32;
2218
2219  std::vector<std::pair<unsigned, SDValue> > RegsToPass;
2220  SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
2221
2222  SmallVector<SDValue, 8> MemOpChains;
2223  for (unsigned i = 0; i != NumOps; ++i) {
2224    bool inMem = false;
2225    SDValue Arg = TheCall->getArg(i);
2226    ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
2227    // See if next argument requires stack alignment in ELF
2228    bool Align = Flags.isSplit();
2229
2230    // PtrOff will be used to store the current argument to the stack if a
2231    // register cannot be found for it.
2232    SDValue PtrOff;
2233
2234    // Stack align in ELF 32
2235    if (isELF32_ABI && Align)
2236      PtrOff = DAG.getConstant(ArgOffset + ((ArgOffset/4) % 2) * PtrByteSize,
2237                               StackPtr.getValueType());
2238    else
2239      PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
2240
2241    PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
2242
2243    // On PPC64, promote integers to 64-bit values.
2244    if (isPPC64 && Arg.getValueType() == MVT::i32) {
2245      // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
2246      unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2247      Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
2248    }
2249
2250    // FIXME Elf untested, what are alignment rules?
2251    // FIXME memcpy is used way more than necessary.  Correctness first.
2252    if (Flags.isByVal()) {
2253      unsigned Size = Flags.getByValSize();
2254      if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
2255      if (Size==1 || Size==2) {
2256        // Very small objects are passed right-justified.
2257        // Everything else is passed left-justified.
2258        MVT VT = (Size==1) ? MVT::i8 : MVT::i16;
2259        if (GPR_idx != NumGPRs) {
2260          SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
2261                                          NULL, 0, VT);
2262          MemOpChains.push_back(Load.getValue(1));
2263          RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2264          if (isMachoABI)
2265            ArgOffset += PtrByteSize;
2266        } else {
2267          SDValue Const = DAG.getConstant(4 - Size, PtrOff.getValueType());
2268          SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
2269          SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, AddPtr,
2270                                CallSeqStart.getNode()->getOperand(0),
2271                                Flags, DAG, Size, dl);
2272          // This must go outside the CALLSEQ_START..END.
2273          SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
2274                               CallSeqStart.getNode()->getOperand(1));
2275          DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
2276                                 NewCallSeqStart.getNode());
2277          Chain = CallSeqStart = NewCallSeqStart;
2278          ArgOffset += PtrByteSize;
2279        }
2280        continue;
2281      }
2282      // Copy entire object into memory.  There are cases where gcc-generated
2283      // code assumes it is there, even if it could be put entirely into
2284      // registers.  (This is not what the doc says.)
2285      SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
2286                            CallSeqStart.getNode()->getOperand(0),
2287                            Flags, DAG, Size, dl);
2288      // This must go outside the CALLSEQ_START..END.
2289      SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
2290                           CallSeqStart.getNode()->getOperand(1));
2291      DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode());
2292      Chain = CallSeqStart = NewCallSeqStart;
2293      // And copy the pieces of it that fit into registers.
2294      for (unsigned j=0; j<Size; j+=PtrByteSize) {
2295        SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
2296        SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2297        if (GPR_idx != NumGPRs) {
2298          SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, NULL, 0);
2299          MemOpChains.push_back(Load.getValue(1));
2300          RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2301          if (isMachoABI)
2302            ArgOffset += PtrByteSize;
2303        } else {
2304          ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
2305          break;
2306        }
2307      }
2308      continue;
2309    }
2310
2311    switch (Arg.getValueType().getSimpleVT()) {
2312    default: assert(0 && "Unexpected ValueType for argument!");
2313    case MVT::i32:
2314    case MVT::i64:
2315      // Double word align in ELF
2316      if (isELF32_ABI && Align) GPR_idx += (GPR_idx % 2);
2317      if (GPR_idx != NumGPRs) {
2318        RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
2319      } else {
2320        LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2321                         isPPC64, isTailCall, false, MemOpChains,
2322                         TailCallArguments, dl);
2323        inMem = true;
2324      }
2325      if (inMem || isMachoABI) {
2326        // Stack align in ELF
2327        if (isELF32_ABI && Align)
2328          ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
2329
2330        ArgOffset += PtrByteSize;
2331      }
2332      break;
2333    case MVT::f32:
2334    case MVT::f64:
2335      if (FPR_idx != NumFPRs) {
2336        RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
2337
2338        if (isVarArg) {
2339          SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0);
2340          MemOpChains.push_back(Store);
2341
2342          // Float varargs are always shadowed in available integer registers
2343          if (GPR_idx != NumGPRs) {
2344            SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, NULL, 0);
2345            MemOpChains.push_back(Load.getValue(1));
2346            if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
2347                                                                Load));
2348          }
2349          if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
2350            SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
2351            PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
2352            SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, NULL, 0);
2353            MemOpChains.push_back(Load.getValue(1));
2354            if (isMachoABI) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++],
2355                                                                Load));
2356          }
2357        } else {
2358          // If we have any FPRs remaining, we may also have GPRs remaining.
2359          // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
2360          // GPRs.
2361          if (isMachoABI) {
2362            if (GPR_idx != NumGPRs)
2363              ++GPR_idx;
2364            if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
2365                !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
2366              ++GPR_idx;
2367          }
2368        }
2369      } else {
2370        LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2371                         isPPC64, isTailCall, false, MemOpChains,
2372                         TailCallArguments, dl);
2373        inMem = true;
2374      }
2375      if (inMem || isMachoABI) {
2376        // Stack align in ELF
2377        if (isELF32_ABI && Align)
2378          ArgOffset += ((ArgOffset/4) % 2) * PtrByteSize;
2379        if (isPPC64)
2380          ArgOffset += 8;
2381        else
2382          ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
2383      }
2384      break;
2385    case MVT::v4f32:
2386    case MVT::v4i32:
2387    case MVT::v8i16:
2388    case MVT::v16i8:
2389      if (isVarArg) {
2390        // These go aligned on the stack, or in the corresponding R registers
2391        // when within range.  The Darwin PPC ABI doc claims they also go in
2392        // V registers; in fact gcc does this only for arguments that are
2393        // prototyped, not for those that match the ...  We do it for all
2394        // arguments, seems to work.
2395        while (ArgOffset % 16 !=0) {
2396          ArgOffset += PtrByteSize;
2397          if (GPR_idx != NumGPRs)
2398            GPR_idx++;
2399        }
2400        // We could elide this store in the case where the object fits
2401        // entirely in R registers.  Maybe later.
2402        PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2403                            DAG.getConstant(ArgOffset, PtrVT));
2404        SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, NULL, 0);
2405        MemOpChains.push_back(Store);
2406        if (VR_idx != NumVRs) {
2407          SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, NULL, 0);
2408          MemOpChains.push_back(Load.getValue(1));
2409          RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
2410        }
2411        ArgOffset += 16;
2412        for (unsigned i=0; i<16; i+=PtrByteSize) {
2413          if (GPR_idx == NumGPRs)
2414            break;
2415          SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
2416                                  DAG.getConstant(i, PtrVT));
2417          SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, NULL, 0);
2418          MemOpChains.push_back(Load.getValue(1));
2419          RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
2420        }
2421        break;
2422      }
2423
2424      // Non-varargs Altivec params generally go in registers, but have
2425      // stack space allocated at the end.
2426      if (VR_idx != NumVRs) {
2427        // Doesn't have GPR space allocated.
2428        RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
2429      } else if (nAltivecParamsAtEnd==0) {
2430        // We are emitting Altivec params in order.
2431        LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2432                         isPPC64, isTailCall, true, MemOpChains,
2433                         TailCallArguments, dl);
2434        ArgOffset += 16;
2435      }
2436      break;
2437    }
2438  }
2439  // If all Altivec parameters fit in registers, as they usually do,
2440  // they get stack space following the non-Altivec parameters.  We
2441  // don't track this here because nobody below needs it.
2442  // If there are more Altivec parameters than fit in registers emit
2443  // the stores here.
2444  if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
2445    unsigned j = 0;
2446    // Offset is aligned; skip 1st 12 params which go in V registers.
2447    ArgOffset = ((ArgOffset+15)/16)*16;
2448    ArgOffset += 12*16;
2449    for (unsigned i = 0; i != NumOps; ++i) {
2450      SDValue Arg = TheCall->getArg(i);
2451      MVT ArgType = Arg.getValueType();
2452      if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
2453          ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
2454        if (++j > NumVRs) {
2455          SDValue PtrOff;
2456          // We are emitting Altivec params in order.
2457          LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
2458                           isPPC64, isTailCall, true, MemOpChains,
2459                           TailCallArguments, dl);
2460          ArgOffset += 16;
2461        }
2462      }
2463    }
2464  }
2465
2466  if (!MemOpChains.empty())
2467    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2468                        &MemOpChains[0], MemOpChains.size());
2469
2470  // Build a sequence of copy-to-reg nodes chained together with token chain
2471  // and flag operands which copy the outgoing args into the appropriate regs.
2472  SDValue InFlag;
2473  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2474    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2475                             RegsToPass[i].second, InFlag);
2476    InFlag = Chain.getValue(1);
2477  }
2478
2479  // With the ELF 32 ABI, set CR6 to true if this is a vararg call.
2480  if (isVarArg && isELF32_ABI) {
2481    SDValue SetCR(DAG.getTargetNode(PPC::CRSET, dl, MVT::i32), 0);
2482    Chain = DAG.getCopyToReg(Chain, dl, PPC::CR1EQ, SetCR, InFlag);
2483    InFlag = Chain.getValue(1);
2484  }
2485
2486  // Emit a sequence of copyto/copyfrom virtual registers for arguments that
2487  // might overwrite each other in case of tail call optimization.
2488  if (isTailCall) {
2489    SmallVector<SDValue, 8> MemOpChains2;
2490    // Do not flag preceeding copytoreg stuff together with the following stuff.
2491    InFlag = SDValue();
2492    StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
2493                                      MemOpChains2, dl);
2494    if (!MemOpChains2.empty())
2495      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2496                          &MemOpChains2[0], MemOpChains2.size());
2497
2498    // Store the return address to the appropriate stack slot.
2499    Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
2500                                          isPPC64, isMachoABI, dl);
2501  }
2502
2503  // Emit callseq_end just before tailcall node.
2504  if (isTailCall) {
2505    Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2506                               DAG.getIntPtrConstant(0, true), InFlag);
2507    InFlag = Chain.getValue(1);
2508  }
2509
2510  std::vector<MVT> NodeTys;
2511  NodeTys.push_back(MVT::Other);   // Returns a chain
2512  NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
2513
2514  SmallVector<SDValue, 8> Ops;
2515  unsigned CallOpc = isMachoABI? PPCISD::CALL_Macho : PPCISD::CALL_ELF;
2516
2517  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2518  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2519  // node so that legalize doesn't hack it.
2520  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2521    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
2522  else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
2523    Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType());
2524  else if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
2525    // If this is an absolute destination address, use the munged value.
2526    Callee = SDValue(Dest, 0);
2527  else {
2528    // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
2529    // to do the call, we can't use PPCISD::CALL.
2530    SDValue MTCTROps[] = {Chain, Callee, InFlag};
2531    Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
2532                        2 + (InFlag.getNode() != 0));
2533    InFlag = Chain.getValue(1);
2534
2535    // Copy the callee address into R12/X12 on darwin.
2536    if (isMachoABI) {
2537      unsigned Reg = Callee.getValueType() == MVT::i32 ? PPC::R12 : PPC::X12;
2538      Chain = DAG.getCopyToReg(Chain, dl, Reg, Callee, InFlag);
2539      InFlag = Chain.getValue(1);
2540    }
2541
2542    NodeTys.clear();
2543    NodeTys.push_back(MVT::Other);
2544    NodeTys.push_back(MVT::Flag);
2545    Ops.push_back(Chain);
2546    CallOpc = isMachoABI ? PPCISD::BCTRL_Macho : PPCISD::BCTRL_ELF;
2547    Callee.setNode(0);
2548    // Add CTR register as callee so a bctr can be emitted later.
2549    if (isTailCall)
2550      Ops.push_back(DAG.getRegister(PPC::CTR, getPointerTy()));
2551  }
2552
2553  // If this is a direct call, pass the chain and the callee.
2554  if (Callee.getNode()) {
2555    Ops.push_back(Chain);
2556    Ops.push_back(Callee);
2557  }
2558  // If this is a tail call add stack pointer delta.
2559  if (isTailCall)
2560    Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
2561
2562  // Add argument registers to the end of the list so that they are known live
2563  // into the call.
2564  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2565    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2566                                  RegsToPass[i].second.getValueType()));
2567
2568  // When performing tail call optimization the callee pops its arguments off
2569  // the stack. Account for this here so these bytes can be pushed back on in
2570  // PPCRegisterInfo::eliminateCallFramePseudoInstr.
2571  int BytesCalleePops =
2572    (CC==CallingConv::Fast && PerformTailCallOpt) ? NumBytes : 0;
2573
2574  if (InFlag.getNode())
2575    Ops.push_back(InFlag);
2576
2577  // Emit tail call.
2578  if (isTailCall) {
2579    assert(InFlag.getNode() &&
2580           "Flag must be set. Depend on flag being set in LowerRET");
2581    Chain = DAG.getNode(PPCISD::TAILCALL, dl,
2582                        TheCall->getVTList(), &Ops[0], Ops.size());
2583    return SDValue(Chain.getNode(), Op.getResNo());
2584  }
2585
2586  Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
2587  InFlag = Chain.getValue(1);
2588
2589  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2590                             DAG.getIntPtrConstant(BytesCalleePops, true),
2591                             InFlag);
2592  if (TheCall->getValueType(0) != MVT::Other)
2593    InFlag = Chain.getValue(1);
2594
2595  SmallVector<SDValue, 16> ResultVals;
2596  SmallVector<CCValAssign, 16> RVLocs;
2597  unsigned CallerCC = DAG.getMachineFunction().getFunction()->getCallingConv();
2598  CCState CCInfo(CallerCC, isVarArg, TM, RVLocs);
2599  CCInfo.AnalyzeCallResult(TheCall, RetCC_PPC);
2600
2601  // Copy all of the result registers out of their specified physreg.
2602  for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2603    CCValAssign &VA = RVLocs[i];
2604    MVT VT = VA.getValVT();
2605    assert(VA.isRegLoc() && "Can only return in registers!");
2606    Chain = DAG.getCopyFromReg(Chain, dl,
2607                               VA.getLocReg(), VT, InFlag).getValue(1);
2608    ResultVals.push_back(Chain.getValue(0));
2609    InFlag = Chain.getValue(2);
2610  }
2611
2612  // If the function returns void, just return the chain.
2613  if (RVLocs.empty())
2614    return Chain;
2615
2616  // Otherwise, merge everything together with a MERGE_VALUES node.
2617  ResultVals.push_back(Chain);
2618  SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
2619                            &ResultVals[0], ResultVals.size());
2620  return Res.getValue(Op.getResNo());
2621}
2622
2623SDValue PPCTargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG,
2624                                      TargetMachine &TM) {
2625  SmallVector<CCValAssign, 16> RVLocs;
2626  unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
2627  bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
2628  DebugLoc dl = Op.getDebugLoc();
2629  CCState CCInfo(CC, isVarArg, TM, RVLocs);
2630  CCInfo.AnalyzeReturn(Op.getNode(), RetCC_PPC);
2631
2632  // If this is the first return lowered for this function, add the regs to the
2633  // liveout set for the function.
2634  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2635    for (unsigned i = 0; i != RVLocs.size(); ++i)
2636      DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2637  }
2638
2639  SDValue Chain = Op.getOperand(0);
2640
2641  Chain = GetPossiblePreceedingTailCall(Chain, PPCISD::TAILCALL);
2642  if (Chain.getOpcode() == PPCISD::TAILCALL) {
2643    SDValue TailCall = Chain;
2644    SDValue TargetAddress = TailCall.getOperand(1);
2645    SDValue StackAdjustment = TailCall.getOperand(2);
2646
2647    assert(((TargetAddress.getOpcode() == ISD::Register &&
2648             cast<RegisterSDNode>(TargetAddress)->getReg() == PPC::CTR) ||
2649            TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
2650            TargetAddress.getOpcode() == ISD::TargetGlobalAddress ||
2651            isa<ConstantSDNode>(TargetAddress)) &&
2652    "Expecting an global address, external symbol, absolute value or register");
2653
2654    assert(StackAdjustment.getOpcode() == ISD::Constant &&
2655           "Expecting a const value");
2656
2657    SmallVector<SDValue,8> Operands;
2658    Operands.push_back(Chain.getOperand(0));
2659    Operands.push_back(TargetAddress);
2660    Operands.push_back(StackAdjustment);
2661    // Copy registers used by the call. Last operand is a flag so it is not
2662    // copied.
2663    for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
2664      Operands.push_back(Chain.getOperand(i));
2665    }
2666    return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Operands[0],
2667                       Operands.size());
2668  }
2669
2670  SDValue Flag;
2671
2672  // Copy the result values into the output registers.
2673  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2674    CCValAssign &VA = RVLocs[i];
2675    assert(VA.isRegLoc() && "Can only return in registers!");
2676    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2677                             Op.getOperand(i*2+1), Flag);
2678    Flag = Chain.getValue(1);
2679  }
2680
2681  if (Flag.getNode())
2682    return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
2683  else
2684    return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
2685}
2686
2687SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
2688                                   const PPCSubtarget &Subtarget) {
2689  // When we pop the dynamic allocation we need to restore the SP link.
2690  DebugLoc dl = Op.getDebugLoc();
2691
2692  // Get the corect type for pointers.
2693  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2694
2695  // Construct the stack pointer operand.
2696  bool IsPPC64 = Subtarget.isPPC64();
2697  unsigned SP = IsPPC64 ? PPC::X1 : PPC::R1;
2698  SDValue StackPtr = DAG.getRegister(SP, PtrVT);
2699
2700  // Get the operands for the STACKRESTORE.
2701  SDValue Chain = Op.getOperand(0);
2702  SDValue SaveSP = Op.getOperand(1);
2703
2704  // Load the old link SP.
2705  SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, NULL, 0);
2706
2707  // Restore the stack pointer.
2708  Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
2709
2710  // Store the old link SP.
2711  return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, NULL, 0);
2712}
2713
2714
2715
2716SDValue
2717PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
2718  MachineFunction &MF = DAG.getMachineFunction();
2719  bool IsPPC64 = PPCSubTarget.isPPC64();
2720  bool isMachoABI = PPCSubTarget.isMachoABI();
2721  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2722
2723  // Get current frame pointer save index.  The users of this index will be
2724  // primarily DYNALLOC instructions.
2725  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2726  int RASI = FI->getReturnAddrSaveIndex();
2727
2728  // If the frame pointer save index hasn't been defined yet.
2729  if (!RASI) {
2730    // Find out what the fix offset of the frame pointer save area.
2731    int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, isMachoABI);
2732    // Allocate the frame index for frame pointer save area.
2733    RASI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, LROffset);
2734    // Save the result.
2735    FI->setReturnAddrSaveIndex(RASI);
2736  }
2737  return DAG.getFrameIndex(RASI, PtrVT);
2738}
2739
2740SDValue
2741PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
2742  MachineFunction &MF = DAG.getMachineFunction();
2743  bool IsPPC64 = PPCSubTarget.isPPC64();
2744  bool isMachoABI = PPCSubTarget.isMachoABI();
2745  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2746
2747  // Get current frame pointer save index.  The users of this index will be
2748  // primarily DYNALLOC instructions.
2749  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2750  int FPSI = FI->getFramePointerSaveIndex();
2751
2752  // If the frame pointer save index hasn't been defined yet.
2753  if (!FPSI) {
2754    // Find out what the fix offset of the frame pointer save area.
2755    int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, isMachoABI);
2756
2757    // Allocate the frame index for frame pointer save area.
2758    FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset);
2759    // Save the result.
2760    FI->setFramePointerSaveIndex(FPSI);
2761  }
2762  return DAG.getFrameIndex(FPSI, PtrVT);
2763}
2764
2765SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
2766                                         SelectionDAG &DAG,
2767                                         const PPCSubtarget &Subtarget) {
2768  // Get the inputs.
2769  SDValue Chain = Op.getOperand(0);
2770  SDValue Size  = Op.getOperand(1);
2771  DebugLoc dl = Op.getDebugLoc();
2772
2773  // Get the corect type for pointers.
2774  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2775  // Negate the size.
2776  SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
2777                                  DAG.getConstant(0, PtrVT), Size);
2778  // Construct a node for the frame pointer save index.
2779  SDValue FPSIdx = getFramePointerFrameIndex(DAG);
2780  // Build a DYNALLOC node.
2781  SDValue Ops[3] = { Chain, NegSize, FPSIdx };
2782  SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
2783  return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
2784}
2785
2786/// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
2787/// possible.
2788SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
2789  // Not FP? Not a fsel.
2790  if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
2791      !Op.getOperand(2).getValueType().isFloatingPoint())
2792    return Op;
2793
2794  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2795
2796  // Cannot handle SETEQ/SETNE.
2797  if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
2798
2799  MVT ResVT = Op.getValueType();
2800  MVT CmpVT = Op.getOperand(0).getValueType();
2801  SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
2802  SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
2803  DebugLoc dl = Op.getDebugLoc();
2804
2805  // If the RHS of the comparison is a 0.0, we don't need to do the
2806  // subtraction at all.
2807  if (isFloatingPointZero(RHS))
2808    switch (CC) {
2809    default: break;       // SETUO etc aren't handled by fsel.
2810    case ISD::SETULT:
2811    case ISD::SETLT:
2812      std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2813    case ISD::SETOGE:
2814    case ISD::SETGE:
2815      if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
2816        LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
2817      return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
2818    case ISD::SETUGT:
2819    case ISD::SETGT:
2820      std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
2821    case ISD::SETOLE:
2822    case ISD::SETLE:
2823      if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
2824        LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
2825      return DAG.getNode(PPCISD::FSEL, dl, ResVT,
2826                         DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
2827    }
2828
2829  SDValue Cmp;
2830  switch (CC) {
2831  default: break;       // SETUO etc aren't handled by fsel.
2832  case ISD::SETULT:
2833  case ISD::SETLT:
2834    Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
2835    if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2836      Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2837      return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
2838  case ISD::SETOGE:
2839  case ISD::SETGE:
2840    Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
2841    if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2842      Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2843      return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
2844  case ISD::SETUGT:
2845  case ISD::SETGT:
2846    Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
2847    if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2848      Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2849      return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
2850  case ISD::SETOLE:
2851  case ISD::SETLE:
2852    Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
2853    if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
2854      Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
2855      return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
2856  }
2857  return Op;
2858}
2859
2860// FIXME: Split this code up when LegalizeDAGTypes lands.
2861SDValue PPCTargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG,
2862                                           DebugLoc dl) {
2863  assert(Op.getOperand(0).getValueType().isFloatingPoint());
2864  SDValue Src = Op.getOperand(0);
2865  if (Src.getValueType() == MVT::f32)
2866    Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
2867
2868  SDValue Tmp;
2869  switch (Op.getValueType().getSimpleVT()) {
2870  default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
2871  case MVT::i32:
2872    Tmp = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Src);
2873    break;
2874  case MVT::i64:
2875    Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
2876    break;
2877  }
2878
2879  // Convert the FP value to an int value through memory.
2880  SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
2881
2882  // Emit a store to the stack slot.
2883  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, NULL, 0);
2884
2885  // Result is a load from the stack slot.  If loading 4 bytes, make sure to
2886  // add in a bias.
2887  if (Op.getValueType() == MVT::i32)
2888    FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
2889                        DAG.getConstant(4, FIPtr.getValueType()));
2890  return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, NULL, 0);
2891}
2892
2893SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2894  DebugLoc dl = Op.getDebugLoc();
2895  // Don't handle ppc_fp128 here; let it be lowered to a libcall.
2896  if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
2897    return SDValue();
2898
2899  if (Op.getOperand(0).getValueType() == MVT::i64) {
2900    SDValue Bits = DAG.getNode(ISD::BIT_CONVERT, dl,
2901                               MVT::f64, Op.getOperand(0));
2902    SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
2903    if (Op.getValueType() == MVT::f32)
2904      FP = DAG.getNode(ISD::FP_ROUND, dl,
2905                       MVT::f32, FP, DAG.getIntPtrConstant(0));
2906    return FP;
2907  }
2908
2909  assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2910         "Unhandled SINT_TO_FP type in custom expander!");
2911  // Since we only generate this in 64-bit mode, we can take advantage of
2912  // 64-bit registers.  In particular, sign extend the input value into the
2913  // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
2914  // then lfd it and fcfid it.
2915  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
2916  int FrameIdx = FrameInfo->CreateStackObject(8, 8);
2917  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2918  SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
2919
2920  SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
2921                                Op.getOperand(0));
2922
2923  // STD the extended value into the stack slot.
2924  MachineMemOperand MO(PseudoSourceValue::getFixedStack(FrameIdx),
2925                       MachineMemOperand::MOStore, 0, 8, 8);
2926  SDValue Store = DAG.getNode(PPCISD::STD_32, dl, MVT::Other,
2927                                DAG.getEntryNode(), Ext64, FIdx,
2928                                DAG.getMemOperand(MO));
2929  // Load the value as a double.
2930  SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, NULL, 0);
2931
2932  // FCFID it and return it.
2933  SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
2934  if (Op.getValueType() == MVT::f32)
2935    FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
2936  return FP;
2937}
2938
2939SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
2940  DebugLoc dl = Op.getDebugLoc();
2941  /*
2942   The rounding mode is in bits 30:31 of FPSR, and has the following
2943   settings:
2944     00 Round to nearest
2945     01 Round to 0
2946     10 Round to +inf
2947     11 Round to -inf
2948
2949  FLT_ROUNDS, on the other hand, expects the following:
2950    -1 Undefined
2951     0 Round to 0
2952     1 Round to nearest
2953     2 Round to +inf
2954     3 Round to -inf
2955
2956  To perform the conversion, we do:
2957    ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
2958  */
2959
2960  MachineFunction &MF = DAG.getMachineFunction();
2961  MVT VT = Op.getValueType();
2962  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2963  std::vector<MVT> NodeTys;
2964  SDValue MFFSreg, InFlag;
2965
2966  // Save FP Control Word to register
2967  NodeTys.push_back(MVT::f64);    // return register
2968  NodeTys.push_back(MVT::Flag);   // unused in this context
2969  SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
2970
2971  // Save FP register to stack slot
2972  int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
2973  SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
2974  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
2975                                 StackSlot, NULL, 0);
2976
2977  // Load FP Control Word from low 32 bits of stack slot.
2978  SDValue Four = DAG.getConstant(4, PtrVT);
2979  SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
2980  SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, NULL, 0);
2981
2982  // Transform as necessary
2983  SDValue CWD1 =
2984    DAG.getNode(ISD::AND, dl, MVT::i32,
2985                CWD, DAG.getConstant(3, MVT::i32));
2986  SDValue CWD2 =
2987    DAG.getNode(ISD::SRL, dl, MVT::i32,
2988                DAG.getNode(ISD::AND, dl, MVT::i32,
2989                            DAG.getNode(ISD::XOR, dl, MVT::i32,
2990                                        CWD, DAG.getConstant(3, MVT::i32)),
2991                            DAG.getConstant(3, MVT::i32)),
2992                DAG.getConstant(1, MVT::i32));
2993
2994  SDValue RetVal =
2995    DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
2996
2997  return DAG.getNode((VT.getSizeInBits() < 16 ?
2998                      ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
2999}
3000
3001SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) {
3002  MVT VT = Op.getValueType();
3003  unsigned BitWidth = VT.getSizeInBits();
3004  DebugLoc dl = Op.getDebugLoc();
3005  assert(Op.getNumOperands() == 3 &&
3006         VT == Op.getOperand(1).getValueType() &&
3007         "Unexpected SHL!");
3008
3009  // Expand into a bunch of logical ops.  Note that these ops
3010  // depend on the PPC behavior for oversized shift amounts.
3011  SDValue Lo = Op.getOperand(0);
3012  SDValue Hi = Op.getOperand(1);
3013  SDValue Amt = Op.getOperand(2);
3014  MVT AmtVT = Amt.getValueType();
3015
3016  SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3017                             DAG.getConstant(BitWidth, AmtVT), Amt);
3018  SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
3019  SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
3020  SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
3021  SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3022                             DAG.getConstant(-BitWidth, AmtVT));
3023  SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
3024  SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3025  SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
3026  SDValue OutOps[] = { OutLo, OutHi };
3027  return DAG.getMergeValues(OutOps, 2, dl);
3028}
3029
3030SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) {
3031  MVT VT = Op.getValueType();
3032  DebugLoc dl = Op.getDebugLoc();
3033  unsigned BitWidth = VT.getSizeInBits();
3034  assert(Op.getNumOperands() == 3 &&
3035         VT == Op.getOperand(1).getValueType() &&
3036         "Unexpected SRL!");
3037
3038  // Expand into a bunch of logical ops.  Note that these ops
3039  // depend on the PPC behavior for oversized shift amounts.
3040  SDValue Lo = Op.getOperand(0);
3041  SDValue Hi = Op.getOperand(1);
3042  SDValue Amt = Op.getOperand(2);
3043  MVT AmtVT = Amt.getValueType();
3044
3045  SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3046                             DAG.getConstant(BitWidth, AmtVT), Amt);
3047  SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3048  SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3049  SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3050  SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3051                             DAG.getConstant(-BitWidth, AmtVT));
3052  SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
3053  SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3054  SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
3055  SDValue OutOps[] = { OutLo, OutHi };
3056  return DAG.getMergeValues(OutOps, 2, dl);
3057}
3058
3059SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) {
3060  DebugLoc dl = Op.getDebugLoc();
3061  MVT VT = Op.getValueType();
3062  unsigned BitWidth = VT.getSizeInBits();
3063  assert(Op.getNumOperands() == 3 &&
3064         VT == Op.getOperand(1).getValueType() &&
3065         "Unexpected SRA!");
3066
3067  // Expand into a bunch of logical ops, followed by a select_cc.
3068  SDValue Lo = Op.getOperand(0);
3069  SDValue Hi = Op.getOperand(1);
3070  SDValue Amt = Op.getOperand(2);
3071  MVT AmtVT = Amt.getValueType();
3072
3073  SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3074                             DAG.getConstant(BitWidth, AmtVT), Amt);
3075  SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3076  SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3077  SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3078  SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3079                             DAG.getConstant(-BitWidth, AmtVT));
3080  SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
3081  SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
3082  SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
3083                                  Tmp4, Tmp6, ISD::SETLE);
3084  SDValue OutOps[] = { OutLo, OutHi };
3085  return DAG.getMergeValues(OutOps, 2, dl);
3086}
3087
3088//===----------------------------------------------------------------------===//
3089// Vector related lowering.
3090//
3091
3092/// BuildSplatI - Build a canonical splati of Val with an element size of
3093/// SplatSize.  Cast the result to VT.
3094static SDValue BuildSplatI(int Val, unsigned SplatSize, MVT VT,
3095                             SelectionDAG &DAG, DebugLoc dl) {
3096  assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
3097
3098  static const MVT VTys[] = { // canonical VT to use for each size.
3099    MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
3100  };
3101
3102  MVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
3103
3104  // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
3105  if (Val == -1)
3106    SplatSize = 1;
3107
3108  MVT CanonicalVT = VTys[SplatSize-1];
3109
3110  // Build a canonical splat for this value.
3111  SDValue Elt = DAG.getConstant(Val, MVT::i32);
3112  SmallVector<SDValue, 8> Ops;
3113  Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
3114  SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
3115                              &Ops[0], Ops.size());
3116  return DAG.getNode(ISD::BIT_CONVERT, dl, ReqVT, Res);
3117}
3118
3119/// BuildIntrinsicOp - Return a binary operator intrinsic node with the
3120/// specified intrinsic ID.
3121static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
3122                                SelectionDAG &DAG, DebugLoc dl,
3123                                MVT DestVT = MVT::Other) {
3124  if (DestVT == MVT::Other) DestVT = LHS.getValueType();
3125  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
3126                     DAG.getConstant(IID, MVT::i32), LHS, RHS);
3127}
3128
3129/// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
3130/// specified intrinsic ID.
3131static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
3132                                SDValue Op2, SelectionDAG &DAG,
3133                                DebugLoc dl, MVT DestVT = MVT::Other) {
3134  if (DestVT == MVT::Other) DestVT = Op0.getValueType();
3135  return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
3136                     DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
3137}
3138
3139
3140/// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
3141/// amount.  The result has the specified value type.
3142static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
3143                             MVT VT, SelectionDAG &DAG, DebugLoc dl) {
3144  // Force LHS/RHS to be the right type.
3145  LHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, LHS);
3146  RHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, RHS);
3147
3148  int Ops[16];
3149  for (unsigned i = 0; i != 16; ++i)
3150    Ops[i] = i + Amt;
3151  SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
3152  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, T);
3153}
3154
3155// If this is a case we can't handle, return null and let the default
3156// expansion code take care of it.  If we CAN select this case, and if it
3157// selects to a single instruction, return Op.  Otherwise, if we can codegen
3158// this case more efficiently than a constant pool load, lower it to the
3159// sequence of ops that should be used.
3160SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3161  DebugLoc dl = Op.getDebugLoc();
3162  BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3163  assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
3164
3165  // Check if this is a splat of a constant value.
3166  APInt APSplatBits, APSplatUndef;
3167  unsigned SplatBitSize;
3168  bool HasAnyUndefs;
3169  if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
3170                             HasAnyUndefs) || SplatBitSize > 32)
3171    return SDValue();
3172
3173  unsigned SplatBits = APSplatBits.getZExtValue();
3174  unsigned SplatUndef = APSplatUndef.getZExtValue();
3175  unsigned SplatSize = SplatBitSize / 8;
3176
3177  // First, handle single instruction cases.
3178
3179  // All zeros?
3180  if (SplatBits == 0) {
3181    // Canonicalize all zero vectors to be v4i32.
3182    if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
3183      SDValue Z = DAG.getConstant(0, MVT::i32);
3184      Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
3185      Op = DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Z);
3186    }
3187    return Op;
3188  }
3189
3190  // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
3191  int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
3192                    (32-SplatBitSize));
3193  if (SextVal >= -16 && SextVal <= 15)
3194    return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
3195
3196
3197  // Two instruction sequences.
3198
3199  // If this value is in the range [-32,30] and is even, use:
3200  //    tmp = VSPLTI[bhw], result = add tmp, tmp
3201  if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
3202    SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
3203    Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
3204    return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3205  }
3206
3207  // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
3208  // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
3209  // for fneg/fabs.
3210  if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
3211    // Make -1 and vspltisw -1:
3212    SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
3213
3214    // Make the VSLW intrinsic, computing 0x8000_0000.
3215    SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
3216                                   OnesV, DAG, dl);
3217
3218    // xor by OnesV to invert it.
3219    Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
3220    return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3221  }
3222
3223  // Check to see if this is a wide variety of vsplti*, binop self cases.
3224  static const signed char SplatCsts[] = {
3225    -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
3226    -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
3227  };
3228
3229  for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
3230    // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
3231    // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
3232    int i = SplatCsts[idx];
3233
3234    // Figure out what shift amount will be used by altivec if shifted by i in
3235    // this splat size.
3236    unsigned TypeShiftAmt = i & (SplatBitSize-1);
3237
3238    // vsplti + shl self.
3239    if (SextVal == (i << (int)TypeShiftAmt)) {
3240      SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3241      static const unsigned IIDs[] = { // Intrinsic to use for each size.
3242        Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
3243        Intrinsic::ppc_altivec_vslw
3244      };
3245      Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3246      return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3247    }
3248
3249    // vsplti + srl self.
3250    if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3251      SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3252      static const unsigned IIDs[] = { // Intrinsic to use for each size.
3253        Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
3254        Intrinsic::ppc_altivec_vsrw
3255      };
3256      Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3257      return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3258    }
3259
3260    // vsplti + sra self.
3261    if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
3262      SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3263      static const unsigned IIDs[] = { // Intrinsic to use for each size.
3264        Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
3265        Intrinsic::ppc_altivec_vsraw
3266      };
3267      Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3268      return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3269    }
3270
3271    // vsplti + rol self.
3272    if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
3273                         ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
3274      SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
3275      static const unsigned IIDs[] = { // Intrinsic to use for each size.
3276        Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
3277        Intrinsic::ppc_altivec_vrlw
3278      };
3279      Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
3280      return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Res);
3281    }
3282
3283    // t = vsplti c, result = vsldoi t, t, 1
3284    if (SextVal == ((i << 8) | (i >> (TypeShiftAmt-8)))) {
3285      SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3286      return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
3287    }
3288    // t = vsplti c, result = vsldoi t, t, 2
3289    if (SextVal == ((i << 16) | (i >> (TypeShiftAmt-16)))) {
3290      SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3291      return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
3292    }
3293    // t = vsplti c, result = vsldoi t, t, 3
3294    if (SextVal == ((i << 24) | (i >> (TypeShiftAmt-24)))) {
3295      SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
3296      return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
3297    }
3298  }
3299
3300  // Three instruction sequences.
3301
3302  // Odd, in range [17,31]:  (vsplti C)-(vsplti -16).
3303  if (SextVal >= 0 && SextVal <= 31) {
3304    SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
3305    SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
3306    LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
3307    return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), LHS);
3308  }
3309  // Odd, in range [-31,-17]:  (vsplti C)+(vsplti -16).
3310  if (SextVal >= -31 && SextVal <= 0) {
3311    SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
3312    SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
3313    LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
3314    return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), LHS);
3315  }
3316
3317  return SDValue();
3318}
3319
3320/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
3321/// the specified operations to build the shuffle.
3322static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
3323                                      SDValue RHS, SelectionDAG &DAG,
3324                                      DebugLoc dl) {
3325  unsigned OpNum = (PFEntry >> 26) & 0x0F;
3326  unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
3327  unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
3328
3329  enum {
3330    OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
3331    OP_VMRGHW,
3332    OP_VMRGLW,
3333    OP_VSPLTISW0,
3334    OP_VSPLTISW1,
3335    OP_VSPLTISW2,
3336    OP_VSPLTISW3,
3337    OP_VSLDOI4,
3338    OP_VSLDOI8,
3339    OP_VSLDOI12
3340  };
3341
3342  if (OpNum == OP_COPY) {
3343    if (LHSID == (1*9+2)*9+3) return LHS;
3344    assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
3345    return RHS;
3346  }
3347
3348  SDValue OpLHS, OpRHS;
3349  OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
3350  OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
3351
3352  int ShufIdxs[16];
3353  switch (OpNum) {
3354  default: assert(0 && "Unknown i32 permute!");
3355  case OP_VMRGHW:
3356    ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
3357    ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
3358    ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
3359    ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
3360    break;
3361  case OP_VMRGLW:
3362    ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
3363    ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
3364    ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
3365    ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
3366    break;
3367  case OP_VSPLTISW0:
3368    for (unsigned i = 0; i != 16; ++i)
3369      ShufIdxs[i] = (i&3)+0;
3370    break;
3371  case OP_VSPLTISW1:
3372    for (unsigned i = 0; i != 16; ++i)
3373      ShufIdxs[i] = (i&3)+4;
3374    break;
3375  case OP_VSPLTISW2:
3376    for (unsigned i = 0; i != 16; ++i)
3377      ShufIdxs[i] = (i&3)+8;
3378    break;
3379  case OP_VSPLTISW3:
3380    for (unsigned i = 0; i != 16; ++i)
3381      ShufIdxs[i] = (i&3)+12;
3382    break;
3383  case OP_VSLDOI4:
3384    return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
3385  case OP_VSLDOI8:
3386    return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
3387  case OP_VSLDOI12:
3388    return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
3389  }
3390  MVT VT = OpLHS.getValueType();
3391  OpLHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OpLHS);
3392  OpRHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OpRHS);
3393  SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
3394  return DAG.getNode(ISD::BIT_CONVERT, dl, VT, T);
3395}
3396
3397/// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
3398/// is a shuffle we can handle in a single instruction, return it.  Otherwise,
3399/// return the code it can be lowered into.  Worst case, it can always be
3400/// lowered into a vperm.
3401SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
3402                                               SelectionDAG &DAG) {
3403  DebugLoc dl = Op.getDebugLoc();
3404  SDValue V1 = Op.getOperand(0);
3405  SDValue V2 = Op.getOperand(1);
3406  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3407  MVT VT = Op.getValueType();
3408
3409  // Cases that are handled by instructions that take permute immediates
3410  // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
3411  // selected by the instruction selector.
3412  if (V2.getOpcode() == ISD::UNDEF) {
3413    if (PPC::isSplatShuffleMask(SVOp, 1) ||
3414        PPC::isSplatShuffleMask(SVOp, 2) ||
3415        PPC::isSplatShuffleMask(SVOp, 4) ||
3416        PPC::isVPKUWUMShuffleMask(SVOp, true) ||
3417        PPC::isVPKUHUMShuffleMask(SVOp, true) ||
3418        PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
3419        PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
3420        PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
3421        PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
3422        PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
3423        PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
3424        PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
3425      return Op;
3426    }
3427  }
3428
3429  // Altivec has a variety of "shuffle immediates" that take two vector inputs
3430  // and produce a fixed permutation.  If any of these match, do not lower to
3431  // VPERM.
3432  if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
3433      PPC::isVPKUHUMShuffleMask(SVOp, false) ||
3434      PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
3435      PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
3436      PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
3437      PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
3438      PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
3439      PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
3440      PPC::isVMRGHShuffleMask(SVOp, 4, false))
3441    return Op;
3442
3443  // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
3444  // perfect shuffle table to emit an optimal matching sequence.
3445  SmallVector<int, 16> PermMask;
3446  SVOp->getMask(PermMask);
3447
3448  unsigned PFIndexes[4];
3449  bool isFourElementShuffle = true;
3450  for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
3451    unsigned EltNo = 8;   // Start out undef.
3452    for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
3453      if (PermMask[i*4+j] < 0)
3454        continue;   // Undef, ignore it.
3455
3456      unsigned ByteSource = PermMask[i*4+j];
3457      if ((ByteSource & 3) != j) {
3458        isFourElementShuffle = false;
3459        break;
3460      }
3461
3462      if (EltNo == 8) {
3463        EltNo = ByteSource/4;
3464      } else if (EltNo != ByteSource/4) {
3465        isFourElementShuffle = false;
3466        break;
3467      }
3468    }
3469    PFIndexes[i] = EltNo;
3470  }
3471
3472  // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
3473  // perfect shuffle vector to determine if it is cost effective to do this as
3474  // discrete instructions, or whether we should use a vperm.
3475  if (isFourElementShuffle) {
3476    // Compute the index in the perfect shuffle table.
3477    unsigned PFTableIndex =
3478      PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
3479
3480    unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
3481    unsigned Cost  = (PFEntry >> 30);
3482
3483    // Determining when to avoid vperm is tricky.  Many things affect the cost
3484    // of vperm, particularly how many times the perm mask needs to be computed.
3485    // For example, if the perm mask can be hoisted out of a loop or is already
3486    // used (perhaps because there are multiple permutes with the same shuffle
3487    // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
3488    // the loop requires an extra register.
3489    //
3490    // As a compromise, we only emit discrete instructions if the shuffle can be
3491    // generated in 3 or fewer operations.  When we have loop information
3492    // available, if this block is within a loop, we should avoid using vperm
3493    // for 3-operation perms and use a constant pool load instead.
3494    if (Cost < 3)
3495      return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
3496  }
3497
3498  // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
3499  // vector that will get spilled to the constant pool.
3500  if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
3501
3502  // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
3503  // that it is in input element units, not in bytes.  Convert now.
3504  MVT EltVT = V1.getValueType().getVectorElementType();
3505  unsigned BytesPerElement = EltVT.getSizeInBits()/8;
3506
3507  SmallVector<SDValue, 16> ResultMask;
3508  for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
3509    unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
3510
3511    for (unsigned j = 0; j != BytesPerElement; ++j)
3512      ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
3513                                           MVT::i32));
3514  }
3515
3516  SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
3517                                    &ResultMask[0], ResultMask.size());
3518  return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
3519}
3520
3521/// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
3522/// altivec comparison.  If it is, return true and fill in Opc/isDot with
3523/// information about the intrinsic.
3524static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
3525                                  bool &isDot) {
3526  unsigned IntrinsicID =
3527    cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
3528  CompareOpc = -1;
3529  isDot = false;
3530  switch (IntrinsicID) {
3531  default: return false;
3532    // Comparison predicates.
3533  case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
3534  case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
3535  case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
3536  case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
3537  case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
3538  case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
3539  case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
3540  case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
3541  case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
3542  case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
3543  case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
3544  case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
3545  case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
3546
3547    // Normal Comparisons.
3548  case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
3549  case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
3550  case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
3551  case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
3552  case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
3553  case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
3554  case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
3555  case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
3556  case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
3557  case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
3558  case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
3559  case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
3560  case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
3561  }
3562  return true;
3563}
3564
3565/// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
3566/// lower, do it, otherwise return null.
3567SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3568                                                     SelectionDAG &DAG) {
3569  // If this is a lowered altivec predicate compare, CompareOpc is set to the
3570  // opcode number of the comparison.
3571  DebugLoc dl = Op.getDebugLoc();
3572  int CompareOpc;
3573  bool isDot;
3574  if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
3575    return SDValue();    // Don't custom lower most intrinsics.
3576
3577  // If this is a non-dot comparison, make the VCMP node and we are done.
3578  if (!isDot) {
3579    SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
3580                                Op.getOperand(1), Op.getOperand(2),
3581                                DAG.getConstant(CompareOpc, MVT::i32));
3582    return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Tmp);
3583  }
3584
3585  // Create the PPCISD altivec 'dot' comparison node.
3586  SDValue Ops[] = {
3587    Op.getOperand(2),  // LHS
3588    Op.getOperand(3),  // RHS
3589    DAG.getConstant(CompareOpc, MVT::i32)
3590  };
3591  std::vector<MVT> VTs;
3592  VTs.push_back(Op.getOperand(2).getValueType());
3593  VTs.push_back(MVT::Flag);
3594  SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
3595
3596  // Now that we have the comparison, emit a copy from the CR to a GPR.
3597  // This is flagged to the above dot comparison.
3598  SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
3599                                DAG.getRegister(PPC::CR6, MVT::i32),
3600                                CompNode.getValue(1));
3601
3602  // Unpack the result based on how the target uses it.
3603  unsigned BitNo;   // Bit # of CR6.
3604  bool InvertBit;   // Invert result?
3605  switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
3606  default:  // Can't happen, don't crash on invalid number though.
3607  case 0:   // Return the value of the EQ bit of CR6.
3608    BitNo = 0; InvertBit = false;
3609    break;
3610  case 1:   // Return the inverted value of the EQ bit of CR6.
3611    BitNo = 0; InvertBit = true;
3612    break;
3613  case 2:   // Return the value of the LT bit of CR6.
3614    BitNo = 2; InvertBit = false;
3615    break;
3616  case 3:   // Return the inverted value of the LT bit of CR6.
3617    BitNo = 2; InvertBit = true;
3618    break;
3619  }
3620
3621  // Shift the bit into the low position.
3622  Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
3623                      DAG.getConstant(8-(3-BitNo), MVT::i32));
3624  // Isolate the bit.
3625  Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
3626                      DAG.getConstant(1, MVT::i32));
3627
3628  // If we are supposed to, toggle the bit.
3629  if (InvertBit)
3630    Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
3631                        DAG.getConstant(1, MVT::i32));
3632  return Flags;
3633}
3634
3635SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
3636                                                   SelectionDAG &DAG) {
3637  DebugLoc dl = Op.getDebugLoc();
3638  // Create a stack slot that is 16-byte aligned.
3639  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3640  int FrameIdx = FrameInfo->CreateStackObject(16, 16);
3641  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3642  SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
3643
3644  // Store the input value into Value#0 of the stack slot.
3645  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
3646                                 Op.getOperand(0), FIdx, NULL, 0);
3647  // Load it out.
3648  return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, NULL, 0);
3649}
3650
3651SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) {
3652  DebugLoc dl = Op.getDebugLoc();
3653  if (Op.getValueType() == MVT::v4i32) {
3654    SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3655
3656    SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
3657    SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
3658
3659    SDValue RHSSwap =   // = vrlw RHS, 16
3660      BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
3661
3662    // Shrinkify inputs to v8i16.
3663    LHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, LHS);
3664    RHS = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, RHS);
3665    RHSSwap = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, RHSSwap);
3666
3667    // Low parts multiplied together, generating 32-bit results (we ignore the
3668    // top parts).
3669    SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
3670                                        LHS, RHS, DAG, dl, MVT::v4i32);
3671
3672    SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
3673                                      LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
3674    // Shift the high parts up 16 bits.
3675    HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
3676                              Neg16, DAG, dl);
3677    return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
3678  } else if (Op.getValueType() == MVT::v8i16) {
3679    SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3680
3681    SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
3682
3683    return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
3684                            LHS, RHS, Zero, DAG, dl);
3685  } else if (Op.getValueType() == MVT::v16i8) {
3686    SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3687
3688    // Multiply the even 8-bit parts, producing 16-bit sums.
3689    SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
3690                                           LHS, RHS, DAG, dl, MVT::v8i16);
3691    EvenParts = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, EvenParts);
3692
3693    // Multiply the odd 8-bit parts, producing 16-bit sums.
3694    SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
3695                                          LHS, RHS, DAG, dl, MVT::v8i16);
3696    OddParts = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, OddParts);
3697
3698    // Merge the results together.
3699    int Ops[16];
3700    for (unsigned i = 0; i != 8; ++i) {
3701      Ops[i*2  ] = 2*i+1;
3702      Ops[i*2+1] = 2*i+1+16;
3703    }
3704    return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
3705  } else {
3706    assert(0 && "Unknown mul to lower!");
3707    abort();
3708  }
3709}
3710
3711/// LowerOperation - Provide custom lowering hooks for some operations.
3712///
3713SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
3714  switch (Op.getOpcode()) {
3715  default: assert(0 && "Wasn't expecting to be able to lower this!");
3716  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
3717  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
3718  case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
3719  case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
3720  case ISD::SETCC:              return LowerSETCC(Op, DAG);
3721  case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
3722  case ISD::VASTART:
3723    return LowerVASTART(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
3724                        VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
3725
3726  case ISD::VAARG:
3727    return LowerVAARG(Op, DAG, VarArgsFrameIndex, VarArgsStackOffset,
3728                      VarArgsNumGPR, VarArgsNumFPR, PPCSubTarget);
3729
3730  case ISD::FORMAL_ARGUMENTS:
3731    return LowerFORMAL_ARGUMENTS(Op, DAG, VarArgsFrameIndex,
3732                                 VarArgsStackOffset, VarArgsNumGPR,
3733                                 VarArgsNumFPR, PPCSubTarget);
3734
3735  case ISD::CALL:               return LowerCALL(Op, DAG, PPCSubTarget,
3736                                                 getTargetMachine());
3737  case ISD::RET:                return LowerRET(Op, DAG, getTargetMachine());
3738  case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
3739  case ISD::DYNAMIC_STACKALLOC:
3740    return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
3741
3742  case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
3743  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG,
3744                                                       Op.getDebugLoc());
3745  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
3746  case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
3747
3748  // Lower 64-bit shifts.
3749  case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
3750  case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
3751  case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
3752
3753  // Vector-related lowering.
3754  case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
3755  case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
3756  case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3757  case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
3758  case ISD::MUL:                return LowerMUL(Op, DAG);
3759
3760  // Frame & Return address.
3761  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
3762  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
3763  }
3764  return SDValue();
3765}
3766
3767void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
3768                                           SmallVectorImpl<SDValue>&Results,
3769                                           SelectionDAG &DAG) {
3770  DebugLoc dl = N->getDebugLoc();
3771  switch (N->getOpcode()) {
3772  default:
3773    assert(false && "Do not know how to custom type legalize this operation!");
3774    return;
3775  case ISD::FP_ROUND_INREG: {
3776    assert(N->getValueType(0) == MVT::ppcf128);
3777    assert(N->getOperand(0).getValueType() == MVT::ppcf128);
3778    SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
3779                             MVT::f64, N->getOperand(0),
3780                             DAG.getIntPtrConstant(0));
3781    SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
3782                             MVT::f64, N->getOperand(0),
3783                             DAG.getIntPtrConstant(1));
3784
3785    // This sequence changes FPSCR to do round-to-zero, adds the two halves
3786    // of the long double, and puts FPSCR back the way it was.  We do not
3787    // actually model FPSCR.
3788    std::vector<MVT> NodeTys;
3789    SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
3790
3791    NodeTys.push_back(MVT::f64);   // Return register
3792    NodeTys.push_back(MVT::Flag);    // Returns a flag for later insns
3793    Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
3794    MFFSreg = Result.getValue(0);
3795    InFlag = Result.getValue(1);
3796
3797    NodeTys.clear();
3798    NodeTys.push_back(MVT::Flag);   // Returns a flag
3799    Ops[0] = DAG.getConstant(31, MVT::i32);
3800    Ops[1] = InFlag;
3801    Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
3802    InFlag = Result.getValue(0);
3803
3804    NodeTys.clear();
3805    NodeTys.push_back(MVT::Flag);   // Returns a flag
3806    Ops[0] = DAG.getConstant(30, MVT::i32);
3807    Ops[1] = InFlag;
3808    Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
3809    InFlag = Result.getValue(0);
3810
3811    NodeTys.clear();
3812    NodeTys.push_back(MVT::f64);    // result of add
3813    NodeTys.push_back(MVT::Flag);   // Returns a flag
3814    Ops[0] = Lo;
3815    Ops[1] = Hi;
3816    Ops[2] = InFlag;
3817    Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
3818    FPreg = Result.getValue(0);
3819    InFlag = Result.getValue(1);
3820
3821    NodeTys.clear();
3822    NodeTys.push_back(MVT::f64);
3823    Ops[0] = DAG.getConstant(1, MVT::i32);
3824    Ops[1] = MFFSreg;
3825    Ops[2] = FPreg;
3826    Ops[3] = InFlag;
3827    Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
3828    FPreg = Result.getValue(0);
3829
3830    // We know the low half is about to be thrown away, so just use something
3831    // convenient.
3832    Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
3833                                FPreg, FPreg));
3834    return;
3835  }
3836  case ISD::FP_TO_SINT:
3837    Results.push_back(LowerFP_TO_SINT(SDValue(N, 0), DAG, dl));
3838    return;
3839  }
3840}
3841
3842
3843//===----------------------------------------------------------------------===//
3844//  Other Lowering Code
3845//===----------------------------------------------------------------------===//
3846
3847MachineBasicBlock *
3848PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
3849                                    bool is64bit, unsigned BinOpcode) const {
3850  // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
3851  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3852
3853  const BasicBlock *LLVM_BB = BB->getBasicBlock();
3854  MachineFunction *F = BB->getParent();
3855  MachineFunction::iterator It = BB;
3856  ++It;
3857
3858  unsigned dest = MI->getOperand(0).getReg();
3859  unsigned ptrA = MI->getOperand(1).getReg();
3860  unsigned ptrB = MI->getOperand(2).getReg();
3861  unsigned incr = MI->getOperand(3).getReg();
3862  DebugLoc dl = MI->getDebugLoc();
3863
3864  MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
3865  MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
3866  F->insert(It, loopMBB);
3867  F->insert(It, exitMBB);
3868  exitMBB->transferSuccessors(BB);
3869
3870  MachineRegisterInfo &RegInfo = F->getRegInfo();
3871  unsigned TmpReg = (!BinOpcode) ? incr :
3872    RegInfo.createVirtualRegister(
3873       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
3874                 (const TargetRegisterClass *) &PPC::GPRCRegClass);
3875
3876  //  thisMBB:
3877  //   ...
3878  //   fallthrough --> loopMBB
3879  BB->addSuccessor(loopMBB);
3880
3881  //  loopMBB:
3882  //   l[wd]arx dest, ptr
3883  //   add r0, dest, incr
3884  //   st[wd]cx. r0, ptr
3885  //   bne- loopMBB
3886  //   fallthrough --> exitMBB
3887  BB = loopMBB;
3888  BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
3889    .addReg(ptrA).addReg(ptrB);
3890  if (BinOpcode)
3891    BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
3892  BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
3893    .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
3894  BuildMI(BB, dl, TII->get(PPC::BCC))
3895    .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
3896  BB->addSuccessor(loopMBB);
3897  BB->addSuccessor(exitMBB);
3898
3899  //  exitMBB:
3900  //   ...
3901  BB = exitMBB;
3902  return BB;
3903}
3904
3905MachineBasicBlock *
3906PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
3907                                            MachineBasicBlock *BB,
3908                                            bool is8bit,    // operation
3909                                            unsigned BinOpcode) const {
3910  // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
3911  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
3912  // In 64 bit mode we have to use 64 bits for addresses, even though the
3913  // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
3914  // registers without caring whether they're 32 or 64, but here we're
3915  // doing actual arithmetic on the addresses.
3916  bool is64bit = PPCSubTarget.isPPC64();
3917
3918  const BasicBlock *LLVM_BB = BB->getBasicBlock();
3919  MachineFunction *F = BB->getParent();
3920  MachineFunction::iterator It = BB;
3921  ++It;
3922
3923  unsigned dest = MI->getOperand(0).getReg();
3924  unsigned ptrA = MI->getOperand(1).getReg();
3925  unsigned ptrB = MI->getOperand(2).getReg();
3926  unsigned incr = MI->getOperand(3).getReg();
3927  DebugLoc dl = MI->getDebugLoc();
3928
3929  MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
3930  MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
3931  F->insert(It, loopMBB);
3932  F->insert(It, exitMBB);
3933  exitMBB->transferSuccessors(BB);
3934
3935  MachineRegisterInfo &RegInfo = F->getRegInfo();
3936  const TargetRegisterClass *RC =
3937    is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
3938              (const TargetRegisterClass *) &PPC::GPRCRegClass;
3939  unsigned PtrReg = RegInfo.createVirtualRegister(RC);
3940  unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
3941  unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
3942  unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
3943  unsigned MaskReg = RegInfo.createVirtualRegister(RC);
3944  unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
3945  unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
3946  unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
3947  unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
3948  unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
3949  unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
3950  unsigned Ptr1Reg;
3951  unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
3952
3953  //  thisMBB:
3954  //   ...
3955  //   fallthrough --> loopMBB
3956  BB->addSuccessor(loopMBB);
3957
3958  // The 4-byte load must be aligned, while a char or short may be
3959  // anywhere in the word.  Hence all this nasty bookkeeping code.
3960  //   add ptr1, ptrA, ptrB [copy if ptrA==0]
3961  //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
3962  //   xori shift, shift1, 24 [16]
3963  //   rlwinm ptr, ptr1, 0, 0, 29
3964  //   slw incr2, incr, shift
3965  //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
3966  //   slw mask, mask2, shift
3967  //  loopMBB:
3968  //   lwarx tmpDest, ptr
3969  //   add tmp, tmpDest, incr2
3970  //   andc tmp2, tmpDest, mask
3971  //   and tmp3, tmp, mask
3972  //   or tmp4, tmp3, tmp2
3973  //   stwcx. tmp4, ptr
3974  //   bne- loopMBB
3975  //   fallthrough --> exitMBB
3976  //   srw dest, tmpDest, shift
3977
3978  if (ptrA!=PPC::R0) {
3979    Ptr1Reg = RegInfo.createVirtualRegister(RC);
3980    BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
3981      .addReg(ptrA).addReg(ptrB);
3982  } else {
3983    Ptr1Reg = ptrB;
3984  }
3985  BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
3986      .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
3987  BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
3988      .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
3989  if (is64bit)
3990    BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
3991      .addReg(Ptr1Reg).addImm(0).addImm(61);
3992  else
3993    BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
3994      .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
3995  BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
3996      .addReg(incr).addReg(ShiftReg);
3997  if (is8bit)
3998    BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
3999  else {
4000    BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
4001    BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
4002  }
4003  BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
4004      .addReg(Mask2Reg).addReg(ShiftReg);
4005
4006  BB = loopMBB;
4007  BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
4008    .addReg(PPC::R0).addReg(PtrReg);
4009  if (BinOpcode)
4010    BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
4011      .addReg(Incr2Reg).addReg(TmpDestReg);
4012  BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
4013    .addReg(TmpDestReg).addReg(MaskReg);
4014  BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
4015    .addReg(TmpReg).addReg(MaskReg);
4016  BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
4017    .addReg(Tmp3Reg).addReg(Tmp2Reg);
4018  BuildMI(BB, dl, TII->get(PPC::STWCX))
4019    .addReg(Tmp4Reg).addReg(PPC::R0).addReg(PtrReg);
4020  BuildMI(BB, dl, TII->get(PPC::BCC))
4021    .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
4022  BB->addSuccessor(loopMBB);
4023  BB->addSuccessor(exitMBB);
4024
4025  //  exitMBB:
4026  //   ...
4027  BB = exitMBB;
4028  BuildMI(BB, dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg).addReg(ShiftReg);
4029  return BB;
4030}
4031
4032MachineBasicBlock *
4033PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4034                                               MachineBasicBlock *BB) const {
4035  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4036
4037  // To "insert" these instructions we actually have to insert their
4038  // control-flow patterns.
4039  const BasicBlock *LLVM_BB = BB->getBasicBlock();
4040  MachineFunction::iterator It = BB;
4041  ++It;
4042
4043  MachineFunction *F = BB->getParent();
4044
4045  if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
4046      MI->getOpcode() == PPC::SELECT_CC_I8 ||
4047      MI->getOpcode() == PPC::SELECT_CC_F4 ||
4048      MI->getOpcode() == PPC::SELECT_CC_F8 ||
4049      MI->getOpcode() == PPC::SELECT_CC_VRRC) {
4050
4051    // The incoming instruction knows the destination vreg to set, the
4052    // condition code register to branch on, the true/false values to
4053    // select between, and a branch opcode to use.
4054
4055    //  thisMBB:
4056    //  ...
4057    //   TrueVal = ...
4058    //   cmpTY ccX, r1, r2
4059    //   bCC copy1MBB
4060    //   fallthrough --> copy0MBB
4061    MachineBasicBlock *thisMBB = BB;
4062    MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4063    MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4064    unsigned SelectPred = MI->getOperand(4).getImm();
4065    DebugLoc dl = MI->getDebugLoc();
4066    BuildMI(BB, dl, TII->get(PPC::BCC))
4067      .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
4068    F->insert(It, copy0MBB);
4069    F->insert(It, sinkMBB);
4070    // Update machine-CFG edges by transferring all successors of the current
4071    // block to the new block which will contain the Phi node for the select.
4072    sinkMBB->transferSuccessors(BB);
4073    // Next, add the true and fallthrough blocks as its successors.
4074    BB->addSuccessor(copy0MBB);
4075    BB->addSuccessor(sinkMBB);
4076
4077    //  copy0MBB:
4078    //   %FalseValue = ...
4079    //   # fallthrough to sinkMBB
4080    BB = copy0MBB;
4081
4082    // Update machine-CFG edges
4083    BB->addSuccessor(sinkMBB);
4084
4085    //  sinkMBB:
4086    //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
4087    //  ...
4088    BB = sinkMBB;
4089    BuildMI(BB, dl, TII->get(PPC::PHI), MI->getOperand(0).getReg())
4090      .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
4091      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
4092  }
4093  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
4094    BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
4095  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
4096    BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
4097  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
4098    BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
4099  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
4100    BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
4101
4102  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
4103    BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
4104  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
4105    BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
4106  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
4107    BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
4108  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
4109    BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
4110
4111  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
4112    BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
4113  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
4114    BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
4115  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
4116    BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
4117  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
4118    BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
4119
4120  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
4121    BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
4122  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
4123    BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
4124  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
4125    BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
4126  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
4127    BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
4128
4129  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
4130    BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
4131  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
4132    BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
4133  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
4134    BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
4135  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
4136    BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
4137
4138  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
4139    BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
4140  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
4141    BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
4142  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
4143    BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
4144  else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
4145    BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
4146
4147  else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
4148    BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
4149  else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
4150    BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
4151  else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
4152    BB = EmitAtomicBinary(MI, BB, false, 0);
4153  else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
4154    BB = EmitAtomicBinary(MI, BB, true, 0);
4155
4156  else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
4157           MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
4158    bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
4159
4160    unsigned dest   = MI->getOperand(0).getReg();
4161    unsigned ptrA   = MI->getOperand(1).getReg();
4162    unsigned ptrB   = MI->getOperand(2).getReg();
4163    unsigned oldval = MI->getOperand(3).getReg();
4164    unsigned newval = MI->getOperand(4).getReg();
4165    DebugLoc dl     = MI->getDebugLoc();
4166
4167    MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
4168    MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
4169    MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
4170    MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4171    F->insert(It, loop1MBB);
4172    F->insert(It, loop2MBB);
4173    F->insert(It, midMBB);
4174    F->insert(It, exitMBB);
4175    exitMBB->transferSuccessors(BB);
4176
4177    //  thisMBB:
4178    //   ...
4179    //   fallthrough --> loopMBB
4180    BB->addSuccessor(loop1MBB);
4181
4182    // loop1MBB:
4183    //   l[wd]arx dest, ptr
4184    //   cmp[wd] dest, oldval
4185    //   bne- midMBB
4186    // loop2MBB:
4187    //   st[wd]cx. newval, ptr
4188    //   bne- loopMBB
4189    //   b exitBB
4190    // midMBB:
4191    //   st[wd]cx. dest, ptr
4192    // exitBB:
4193    BB = loop1MBB;
4194    BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
4195      .addReg(ptrA).addReg(ptrB);
4196    BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
4197      .addReg(oldval).addReg(dest);
4198    BuildMI(BB, dl, TII->get(PPC::BCC))
4199      .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
4200    BB->addSuccessor(loop2MBB);
4201    BB->addSuccessor(midMBB);
4202
4203    BB = loop2MBB;
4204    BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4205      .addReg(newval).addReg(ptrA).addReg(ptrB);
4206    BuildMI(BB, dl, TII->get(PPC::BCC))
4207      .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
4208    BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
4209    BB->addSuccessor(loop1MBB);
4210    BB->addSuccessor(exitMBB);
4211
4212    BB = midMBB;
4213    BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4214      .addReg(dest).addReg(ptrA).addReg(ptrB);
4215    BB->addSuccessor(exitMBB);
4216
4217    //  exitMBB:
4218    //   ...
4219    BB = exitMBB;
4220  } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
4221             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
4222    // We must use 64-bit registers for addresses when targeting 64-bit,
4223    // since we're actually doing arithmetic on them.  Other registers
4224    // can be 32-bit.
4225    bool is64bit = PPCSubTarget.isPPC64();
4226    bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
4227
4228    unsigned dest   = MI->getOperand(0).getReg();
4229    unsigned ptrA   = MI->getOperand(1).getReg();
4230    unsigned ptrB   = MI->getOperand(2).getReg();
4231    unsigned oldval = MI->getOperand(3).getReg();
4232    unsigned newval = MI->getOperand(4).getReg();
4233    DebugLoc dl     = MI->getDebugLoc();
4234
4235    MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
4236    MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
4237    MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
4238    MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4239    F->insert(It, loop1MBB);
4240    F->insert(It, loop2MBB);
4241    F->insert(It, midMBB);
4242    F->insert(It, exitMBB);
4243    exitMBB->transferSuccessors(BB);
4244
4245    MachineRegisterInfo &RegInfo = F->getRegInfo();
4246    const TargetRegisterClass *RC =
4247      is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
4248                (const TargetRegisterClass *) &PPC::GPRCRegClass;
4249    unsigned PtrReg = RegInfo.createVirtualRegister(RC);
4250    unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
4251    unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
4252    unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
4253    unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
4254    unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
4255    unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
4256    unsigned MaskReg = RegInfo.createVirtualRegister(RC);
4257    unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
4258    unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
4259    unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
4260    unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
4261    unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
4262    unsigned Ptr1Reg;
4263    unsigned TmpReg = RegInfo.createVirtualRegister(RC);
4264    //  thisMBB:
4265    //   ...
4266    //   fallthrough --> loopMBB
4267    BB->addSuccessor(loop1MBB);
4268
4269    // The 4-byte load must be aligned, while a char or short may be
4270    // anywhere in the word.  Hence all this nasty bookkeeping code.
4271    //   add ptr1, ptrA, ptrB [copy if ptrA==0]
4272    //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
4273    //   xori shift, shift1, 24 [16]
4274    //   rlwinm ptr, ptr1, 0, 0, 29
4275    //   slw newval2, newval, shift
4276    //   slw oldval2, oldval,shift
4277    //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
4278    //   slw mask, mask2, shift
4279    //   and newval3, newval2, mask
4280    //   and oldval3, oldval2, mask
4281    // loop1MBB:
4282    //   lwarx tmpDest, ptr
4283    //   and tmp, tmpDest, mask
4284    //   cmpw tmp, oldval3
4285    //   bne- midMBB
4286    // loop2MBB:
4287    //   andc tmp2, tmpDest, mask
4288    //   or tmp4, tmp2, newval3
4289    //   stwcx. tmp4, ptr
4290    //   bne- loop1MBB
4291    //   b exitBB
4292    // midMBB:
4293    //   stwcx. tmpDest, ptr
4294    // exitBB:
4295    //   srw dest, tmpDest, shift
4296    if (ptrA!=PPC::R0) {
4297      Ptr1Reg = RegInfo.createVirtualRegister(RC);
4298      BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
4299        .addReg(ptrA).addReg(ptrB);
4300    } else {
4301      Ptr1Reg = ptrB;
4302    }
4303    BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
4304        .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
4305    BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
4306        .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
4307    if (is64bit)
4308      BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
4309        .addReg(Ptr1Reg).addImm(0).addImm(61);
4310    else
4311      BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
4312        .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
4313    BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
4314        .addReg(newval).addReg(ShiftReg);
4315    BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
4316        .addReg(oldval).addReg(ShiftReg);
4317    if (is8bit)
4318      BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
4319    else {
4320      BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
4321      BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
4322        .addReg(Mask3Reg).addImm(65535);
4323    }
4324    BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
4325        .addReg(Mask2Reg).addReg(ShiftReg);
4326    BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
4327        .addReg(NewVal2Reg).addReg(MaskReg);
4328    BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
4329        .addReg(OldVal2Reg).addReg(MaskReg);
4330
4331    BB = loop1MBB;
4332    BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
4333        .addReg(PPC::R0).addReg(PtrReg);
4334    BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
4335        .addReg(TmpDestReg).addReg(MaskReg);
4336    BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
4337        .addReg(TmpReg).addReg(OldVal3Reg);
4338    BuildMI(BB, dl, TII->get(PPC::BCC))
4339        .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
4340    BB->addSuccessor(loop2MBB);
4341    BB->addSuccessor(midMBB);
4342
4343    BB = loop2MBB;
4344    BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
4345        .addReg(TmpDestReg).addReg(MaskReg);
4346    BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
4347        .addReg(Tmp2Reg).addReg(NewVal3Reg);
4348    BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
4349        .addReg(PPC::R0).addReg(PtrReg);
4350    BuildMI(BB, dl, TII->get(PPC::BCC))
4351      .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
4352    BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
4353    BB->addSuccessor(loop1MBB);
4354    BB->addSuccessor(exitMBB);
4355
4356    BB = midMBB;
4357    BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
4358      .addReg(PPC::R0).addReg(PtrReg);
4359    BB->addSuccessor(exitMBB);
4360
4361    //  exitMBB:
4362    //   ...
4363    BB = exitMBB;
4364    BuildMI(BB, dl, TII->get(PPC::SRW),dest).addReg(TmpReg).addReg(ShiftReg);
4365  } else {
4366    assert(0 && "Unexpected instr type to insert");
4367  }
4368
4369  F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
4370  return BB;
4371}
4372
4373//===----------------------------------------------------------------------===//
4374// Target Optimization Hooks
4375//===----------------------------------------------------------------------===//
4376
4377SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
4378                                             DAGCombinerInfo &DCI) const {
4379  TargetMachine &TM = getTargetMachine();
4380  SelectionDAG &DAG = DCI.DAG;
4381  DebugLoc dl = N->getDebugLoc();
4382  switch (N->getOpcode()) {
4383  default: break;
4384  case PPCISD::SHL:
4385    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4386      if (C->getZExtValue() == 0)   // 0 << V -> 0.
4387        return N->getOperand(0);
4388    }
4389    break;
4390  case PPCISD::SRL:
4391    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4392      if (C->getZExtValue() == 0)   // 0 >>u V -> 0.
4393        return N->getOperand(0);
4394    }
4395    break;
4396  case PPCISD::SRA:
4397    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
4398      if (C->getZExtValue() == 0 ||   //  0 >>s V -> 0.
4399          C->isAllOnesValue())    // -1 >>s V -> -1.
4400        return N->getOperand(0);
4401    }
4402    break;
4403
4404  case ISD::SINT_TO_FP:
4405    if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
4406      if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
4407        // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
4408        // We allow the src/dst to be either f32/f64, but the intermediate
4409        // type must be i64.
4410        if (N->getOperand(0).getValueType() == MVT::i64 &&
4411            N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
4412          SDValue Val = N->getOperand(0).getOperand(0);
4413          if (Val.getValueType() == MVT::f32) {
4414            Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
4415            DCI.AddToWorklist(Val.getNode());
4416          }
4417
4418          Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
4419          DCI.AddToWorklist(Val.getNode());
4420          Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
4421          DCI.AddToWorklist(Val.getNode());
4422          if (N->getValueType(0) == MVT::f32) {
4423            Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
4424                              DAG.getIntPtrConstant(0));
4425            DCI.AddToWorklist(Val.getNode());
4426          }
4427          return Val;
4428        } else if (N->getOperand(0).getValueType() == MVT::i32) {
4429          // If the intermediate type is i32, we can avoid the load/store here
4430          // too.
4431        }
4432      }
4433    }
4434    break;
4435  case ISD::STORE:
4436    // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
4437    if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
4438        !cast<StoreSDNode>(N)->isTruncatingStore() &&
4439        N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
4440        N->getOperand(1).getValueType() == MVT::i32 &&
4441        N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
4442      SDValue Val = N->getOperand(1).getOperand(0);
4443      if (Val.getValueType() == MVT::f32) {
4444        Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
4445        DCI.AddToWorklist(Val.getNode());
4446      }
4447      Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
4448      DCI.AddToWorklist(Val.getNode());
4449
4450      Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
4451                        N->getOperand(2), N->getOperand(3));
4452      DCI.AddToWorklist(Val.getNode());
4453      return Val;
4454    }
4455
4456    // Turn STORE (BSWAP) -> sthbrx/stwbrx.
4457    if (N->getOperand(1).getOpcode() == ISD::BSWAP &&
4458        N->getOperand(1).getNode()->hasOneUse() &&
4459        (N->getOperand(1).getValueType() == MVT::i32 ||
4460         N->getOperand(1).getValueType() == MVT::i16)) {
4461      SDValue BSwapOp = N->getOperand(1).getOperand(0);
4462      // Do an any-extend to 32-bits if this is a half-word input.
4463      if (BSwapOp.getValueType() == MVT::i16)
4464        BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
4465
4466      return DAG.getNode(PPCISD::STBRX, dl, MVT::Other, N->getOperand(0),
4467                         BSwapOp, N->getOperand(2), N->getOperand(3),
4468                         DAG.getValueType(N->getOperand(1).getValueType()));
4469    }
4470    break;
4471  case ISD::BSWAP:
4472    // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
4473    if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
4474        N->getOperand(0).hasOneUse() &&
4475        (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
4476      SDValue Load = N->getOperand(0);
4477      LoadSDNode *LD = cast<LoadSDNode>(Load);
4478      // Create the byte-swapping load.
4479      std::vector<MVT> VTs;
4480      VTs.push_back(MVT::i32);
4481      VTs.push_back(MVT::Other);
4482      SDValue MO = DAG.getMemOperand(LD->getMemOperand());
4483      SDValue Ops[] = {
4484        LD->getChain(),    // Chain
4485        LD->getBasePtr(),  // Ptr
4486        MO,                // MemOperand
4487        DAG.getValueType(N->getValueType(0)) // VT
4488      };
4489      SDValue BSLoad = DAG.getNode(PPCISD::LBRX, dl, VTs, Ops, 4);
4490
4491      // If this is an i16 load, insert the truncate.
4492      SDValue ResVal = BSLoad;
4493      if (N->getValueType(0) == MVT::i16)
4494        ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
4495
4496      // First, combine the bswap away.  This makes the value produced by the
4497      // load dead.
4498      DCI.CombineTo(N, ResVal);
4499
4500      // Next, combine the load away, we give it a bogus result value but a real
4501      // chain result.  The result value is dead because the bswap is dead.
4502      DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
4503
4504      // Return N so it doesn't get rechecked!
4505      return SDValue(N, 0);
4506    }
4507
4508    break;
4509  case PPCISD::VCMP: {
4510    // If a VCMPo node already exists with exactly the same operands as this
4511    // node, use its result instead of this node (VCMPo computes both a CR6 and
4512    // a normal output).
4513    //
4514    if (!N->getOperand(0).hasOneUse() &&
4515        !N->getOperand(1).hasOneUse() &&
4516        !N->getOperand(2).hasOneUse()) {
4517
4518      // Scan all of the users of the LHS, looking for VCMPo's that match.
4519      SDNode *VCMPoNode = 0;
4520
4521      SDNode *LHSN = N->getOperand(0).getNode();
4522      for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
4523           UI != E; ++UI)
4524        if (UI->getOpcode() == PPCISD::VCMPo &&
4525            UI->getOperand(1) == N->getOperand(1) &&
4526            UI->getOperand(2) == N->getOperand(2) &&
4527            UI->getOperand(0) == N->getOperand(0)) {
4528          VCMPoNode = *UI;
4529          break;
4530        }
4531
4532      // If there is no VCMPo node, or if the flag value has a single use, don't
4533      // transform this.
4534      if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
4535        break;
4536
4537      // Look at the (necessarily single) use of the flag value.  If it has a
4538      // chain, this transformation is more complex.  Note that multiple things
4539      // could use the value result, which we should ignore.
4540      SDNode *FlagUser = 0;
4541      for (SDNode::use_iterator UI = VCMPoNode->use_begin();
4542           FlagUser == 0; ++UI) {
4543        assert(UI != VCMPoNode->use_end() && "Didn't find user!");
4544        SDNode *User = *UI;
4545        for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
4546          if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
4547            FlagUser = User;
4548            break;
4549          }
4550        }
4551      }
4552
4553      // If the user is a MFCR instruction, we know this is safe.  Otherwise we
4554      // give up for right now.
4555      if (FlagUser->getOpcode() == PPCISD::MFCR)
4556        return SDValue(VCMPoNode, 0);
4557    }
4558    break;
4559  }
4560  case ISD::BR_CC: {
4561    // If this is a branch on an altivec predicate comparison, lower this so
4562    // that we don't have to do a MFCR: instead, branch directly on CR6.  This
4563    // lowering is done pre-legalize, because the legalizer lowers the predicate
4564    // compare down to code that is difficult to reassemble.
4565    ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4566    SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
4567    int CompareOpc;
4568    bool isDot;
4569
4570    if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
4571        isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
4572        getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
4573      assert(isDot && "Can't compare against a vector result!");
4574
4575      // If this is a comparison against something other than 0/1, then we know
4576      // that the condition is never/always true.
4577      unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
4578      if (Val != 0 && Val != 1) {
4579        if (CC == ISD::SETEQ)      // Cond never true, remove branch.
4580          return N->getOperand(0);
4581        // Always !=, turn it into an unconditional branch.
4582        return DAG.getNode(ISD::BR, dl, MVT::Other,
4583                           N->getOperand(0), N->getOperand(4));
4584      }
4585
4586      bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
4587
4588      // Create the PPCISD altivec 'dot' comparison node.
4589      std::vector<MVT> VTs;
4590      SDValue Ops[] = {
4591        LHS.getOperand(2),  // LHS of compare
4592        LHS.getOperand(3),  // RHS of compare
4593        DAG.getConstant(CompareOpc, MVT::i32)
4594      };
4595      VTs.push_back(LHS.getOperand(2).getValueType());
4596      VTs.push_back(MVT::Flag);
4597      SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
4598
4599      // Unpack the result based on how the target uses it.
4600      PPC::Predicate CompOpc;
4601      switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
4602      default:  // Can't happen, don't crash on invalid number though.
4603      case 0:   // Branch on the value of the EQ bit of CR6.
4604        CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
4605        break;
4606      case 1:   // Branch on the inverted value of the EQ bit of CR6.
4607        CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
4608        break;
4609      case 2:   // Branch on the value of the LT bit of CR6.
4610        CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
4611        break;
4612      case 3:   // Branch on the inverted value of the LT bit of CR6.
4613        CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
4614        break;
4615      }
4616
4617      return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
4618                         DAG.getConstant(CompOpc, MVT::i32),
4619                         DAG.getRegister(PPC::CR6, MVT::i32),
4620                         N->getOperand(4), CompNode.getValue(1));
4621    }
4622    break;
4623  }
4624  }
4625
4626  return SDValue();
4627}
4628
4629//===----------------------------------------------------------------------===//
4630// Inline Assembly Support
4631//===----------------------------------------------------------------------===//
4632
4633void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
4634                                                       const APInt &Mask,
4635                                                       APInt &KnownZero,
4636                                                       APInt &KnownOne,
4637                                                       const SelectionDAG &DAG,
4638                                                       unsigned Depth) const {
4639  KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
4640  switch (Op.getOpcode()) {
4641  default: break;
4642  case PPCISD::LBRX: {
4643    // lhbrx is known to have the top bits cleared out.
4644    if (cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::i16)
4645      KnownZero = 0xFFFF0000;
4646    break;
4647  }
4648  case ISD::INTRINSIC_WO_CHAIN: {
4649    switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
4650    default: break;
4651    case Intrinsic::ppc_altivec_vcmpbfp_p:
4652    case Intrinsic::ppc_altivec_vcmpeqfp_p:
4653    case Intrinsic::ppc_altivec_vcmpequb_p:
4654    case Intrinsic::ppc_altivec_vcmpequh_p:
4655    case Intrinsic::ppc_altivec_vcmpequw_p:
4656    case Intrinsic::ppc_altivec_vcmpgefp_p:
4657    case Intrinsic::ppc_altivec_vcmpgtfp_p:
4658    case Intrinsic::ppc_altivec_vcmpgtsb_p:
4659    case Intrinsic::ppc_altivec_vcmpgtsh_p:
4660    case Intrinsic::ppc_altivec_vcmpgtsw_p:
4661    case Intrinsic::ppc_altivec_vcmpgtub_p:
4662    case Intrinsic::ppc_altivec_vcmpgtuh_p:
4663    case Intrinsic::ppc_altivec_vcmpgtuw_p:
4664      KnownZero = ~1U;  // All bits but the low one are known to be zero.
4665      break;
4666    }
4667  }
4668  }
4669}
4670
4671
4672/// getConstraintType - Given a constraint, return the type of
4673/// constraint it is for this target.
4674PPCTargetLowering::ConstraintType
4675PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
4676  if (Constraint.size() == 1) {
4677    switch (Constraint[0]) {
4678    default: break;
4679    case 'b':
4680    case 'r':
4681    case 'f':
4682    case 'v':
4683    case 'y':
4684      return C_RegisterClass;
4685    }
4686  }
4687  return TargetLowering::getConstraintType(Constraint);
4688}
4689
4690std::pair<unsigned, const TargetRegisterClass*>
4691PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
4692                                                MVT VT) const {
4693  if (Constraint.size() == 1) {
4694    // GCC RS6000 Constraint Letters
4695    switch (Constraint[0]) {
4696    case 'b':   // R1-R31
4697    case 'r':   // R0-R31
4698      if (VT == MVT::i64 && PPCSubTarget.isPPC64())
4699        return std::make_pair(0U, PPC::G8RCRegisterClass);
4700      return std::make_pair(0U, PPC::GPRCRegisterClass);
4701    case 'f':
4702      if (VT == MVT::f32)
4703        return std::make_pair(0U, PPC::F4RCRegisterClass);
4704      else if (VT == MVT::f64)
4705        return std::make_pair(0U, PPC::F8RCRegisterClass);
4706      break;
4707    case 'v':
4708      return std::make_pair(0U, PPC::VRRCRegisterClass);
4709    case 'y':   // crrc
4710      return std::make_pair(0U, PPC::CRRCRegisterClass);
4711    }
4712  }
4713
4714  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4715}
4716
4717
4718/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4719/// vector.  If it is invalid, don't add anything to Ops. If hasMemory is true
4720/// it means one of the asm constraint of the inline asm instruction being
4721/// processed is 'm'.
4722void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, char Letter,
4723                                                     bool hasMemory,
4724                                                     std::vector<SDValue>&Ops,
4725                                                     SelectionDAG &DAG) const {
4726  SDValue Result(0,0);
4727  switch (Letter) {
4728  default: break;
4729  case 'I':
4730  case 'J':
4731  case 'K':
4732  case 'L':
4733  case 'M':
4734  case 'N':
4735  case 'O':
4736  case 'P': {
4737    ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
4738    if (!CST) return; // Must be an immediate to match.
4739    unsigned Value = CST->getZExtValue();
4740    switch (Letter) {
4741    default: assert(0 && "Unknown constraint letter!");
4742    case 'I':  // "I" is a signed 16-bit constant.
4743      if ((short)Value == (int)Value)
4744        Result = DAG.getTargetConstant(Value, Op.getValueType());
4745      break;
4746    case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
4747    case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
4748      if ((short)Value == 0)
4749        Result = DAG.getTargetConstant(Value, Op.getValueType());
4750      break;
4751    case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
4752      if ((Value >> 16) == 0)
4753        Result = DAG.getTargetConstant(Value, Op.getValueType());
4754      break;
4755    case 'M':  // "M" is a constant that is greater than 31.
4756      if (Value > 31)
4757        Result = DAG.getTargetConstant(Value, Op.getValueType());
4758      break;
4759    case 'N':  // "N" is a positive constant that is an exact power of two.
4760      if ((int)Value > 0 && isPowerOf2_32(Value))
4761        Result = DAG.getTargetConstant(Value, Op.getValueType());
4762      break;
4763    case 'O':  // "O" is the constant zero.
4764      if (Value == 0)
4765        Result = DAG.getTargetConstant(Value, Op.getValueType());
4766      break;
4767    case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
4768      if ((short)-Value == (int)-Value)
4769        Result = DAG.getTargetConstant(Value, Op.getValueType());
4770      break;
4771    }
4772    break;
4773  }
4774  }
4775
4776  if (Result.getNode()) {
4777    Ops.push_back(Result);
4778    return;
4779  }
4780
4781  // Handle standard constraint letters.
4782  TargetLowering::LowerAsmOperandForConstraint(Op, Letter, hasMemory, Ops, DAG);
4783}
4784
4785// isLegalAddressingMode - Return true if the addressing mode represented
4786// by AM is legal for this target, for a load/store of the specified type.
4787bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
4788                                              const Type *Ty) const {
4789  // FIXME: PPC does not allow r+i addressing modes for vectors!
4790
4791  // PPC allows a sign-extended 16-bit immediate field.
4792  if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
4793    return false;
4794
4795  // No global is ever allowed as a base.
4796  if (AM.BaseGV)
4797    return false;
4798
4799  // PPC only support r+r,
4800  switch (AM.Scale) {
4801  case 0:  // "r+i" or just "i", depending on HasBaseReg.
4802    break;
4803  case 1:
4804    if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
4805      return false;
4806    // Otherwise we have r+r or r+i.
4807    break;
4808  case 2:
4809    if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
4810      return false;
4811    // Allow 2*r as r+r.
4812    break;
4813  default:
4814    // No other scales are supported.
4815    return false;
4816  }
4817
4818  return true;
4819}
4820
4821/// isLegalAddressImmediate - Return true if the integer value can be used
4822/// as the offset of the target addressing mode for load / store of the
4823/// given type.
4824bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,const Type *Ty) const{
4825  // PPC allows a sign-extended 16-bit immediate field.
4826  return (V > -(1 << 16) && V < (1 << 16)-1);
4827}
4828
4829bool PPCTargetLowering::isLegalAddressImmediate(llvm::GlobalValue* GV) const {
4830  return false;
4831}
4832
4833SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
4834  DebugLoc dl = Op.getDebugLoc();
4835  // Depths > 0 not supported yet!
4836  if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
4837    return SDValue();
4838
4839  MachineFunction &MF = DAG.getMachineFunction();
4840  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4841
4842  // Just load the return address off the stack.
4843  SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
4844
4845  // Make sure the function really does not optimize away the store of the RA
4846  // to the stack.
4847  FuncInfo->setLRStoreRequired();
4848  return DAG.getLoad(getPointerTy(), dl,
4849                     DAG.getEntryNode(), RetAddrFI, NULL, 0);
4850}
4851
4852SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
4853  DebugLoc dl = Op.getDebugLoc();
4854  // Depths > 0 not supported yet!
4855  if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
4856    return SDValue();
4857
4858  MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4859  bool isPPC64 = PtrVT == MVT::i64;
4860
4861  MachineFunction &MF = DAG.getMachineFunction();
4862  MachineFrameInfo *MFI = MF.getFrameInfo();
4863  bool is31 = (NoFramePointerElim || MFI->hasVarSizedObjects())
4864                  && MFI->getStackSize();
4865
4866  if (isPPC64)
4867    return DAG.getCopyFromReg(DAG.getEntryNode(), dl, is31 ? PPC::X31 : PPC::X1,
4868      MVT::i64);
4869  else
4870    return DAG.getCopyFromReg(DAG.getEntryNode(), dl, is31 ? PPC::R31 : PPC::R1,
4871      MVT::i32);
4872}
4873
4874bool
4875PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4876  // The PowerPC target isn't yet aware of offsets.
4877  return false;
4878}
4879