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