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