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