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