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