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