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