[PowerPC] Expand v2i64 shifts
[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 "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
38 using namespace llvm;
39
40 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
41 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
42
43 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
44 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
45
46 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
47 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
48
49 // FIXME: Remove this once the bug has been fixed!
50 extern cl::opt<bool> ANDIGlueBug;
51
52 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
53   if (TM.getSubtargetImpl()->isDarwin())
54     return new TargetLoweringObjectFileMachO();
55
56   if (TM.getSubtargetImpl()->isSVR4ABI())
57     return new PPC64LinuxTargetObjectFile();
58
59   return new TargetLoweringObjectFileELF();
60 }
61
62 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
63   : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
64   const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
65
66   setPow2DivIsCheap();
67
68   // Use _setjmp/_longjmp instead of setjmp/longjmp.
69   setUseUnderscoreSetJmp(true);
70   setUseUnderscoreLongJmp(true);
71
72   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73   // arguments are at least 4/8 bytes aligned.
74   bool isPPC64 = Subtarget->isPPC64();
75   setMinStackArgumentAlignment(isPPC64 ? 8:4);
76
77   // Set up the register classes.
78   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
81
82   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
85
86   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87
88   // PowerPC has pre-inc load and store's.
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99
100   if (Subtarget->useCRBits()) {
101     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
102
103     if (isPPC64 || Subtarget->hasFPCVT()) {
104       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106                          isPPC64 ? MVT::i64 : MVT::i32);
107       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
109                          isPPC64 ? MVT::i64 : MVT::i32);
110     } else {
111       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
113     }
114
115     // PowerPC does not support direct load / store of condition registers
116     setOperationAction(ISD::LOAD, MVT::i1, Custom);
117     setOperationAction(ISD::STORE, MVT::i1, Custom);
118
119     // FIXME: Remove this once the ANDI glue bug is fixed:
120     if (ANDIGlueBug)
121       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
122
123     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
129
130     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
131   }
132
133   // This is used in the ppcf128->int sequence.  Note it has different semantics
134   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
135   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
136
137   // We do not currently implement these libm ops for PowerPC.
138   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
140   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
142   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
144
145   // PowerPC has no SREM/UREM instructions
146   setOperationAction(ISD::SREM, MVT::i32, Expand);
147   setOperationAction(ISD::UREM, MVT::i32, Expand);
148   setOperationAction(ISD::SREM, MVT::i64, Expand);
149   setOperationAction(ISD::UREM, MVT::i64, Expand);
150
151   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
160
161   // We don't support sin/cos/sqrt/fmod/pow
162   setOperationAction(ISD::FSIN , MVT::f64, Expand);
163   setOperationAction(ISD::FCOS , MVT::f64, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165   setOperationAction(ISD::FREM , MVT::f64, Expand);
166   setOperationAction(ISD::FPOW , MVT::f64, Expand);
167   setOperationAction(ISD::FMA  , MVT::f64, Legal);
168   setOperationAction(ISD::FSIN , MVT::f32, Expand);
169   setOperationAction(ISD::FCOS , MVT::f32, Expand);
170   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171   setOperationAction(ISD::FREM , MVT::f32, Expand);
172   setOperationAction(ISD::FPOW , MVT::f32, Expand);
173   setOperationAction(ISD::FMA  , MVT::f32, Legal);
174
175   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
176
177   // If we're enabling GP optimizations, use hardware square root
178   if (!Subtarget->hasFSQRT() &&
179       !(TM.Options.UnsafeFPMath &&
180         Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget->hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath &&
185         Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
186     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
187
188   if (Subtarget->hasFCPSGN()) {
189     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
191   } else {
192     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
194   }
195
196   if (Subtarget->hasFPRND()) {
197     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
199     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200     setOperationAction(ISD::FROUND, MVT::f64, Legal);
201
202     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
204     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205     setOperationAction(ISD::FROUND, MVT::f32, Legal);
206   }
207
208   // PowerPC does not have BSWAP, CTPOP or CTTZ
209   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
210   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
214   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
217
218   if (Subtarget->hasPOPCNTD()) {
219     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
220     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
221   } else {
222     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
223     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
224   }
225
226   // PowerPC does not have ROTR
227   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
228   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
229
230   if (!Subtarget->useCRBits()) {
231     // PowerPC does not have Select
232     setOperationAction(ISD::SELECT, MVT::i32, Expand);
233     setOperationAction(ISD::SELECT, MVT::i64, Expand);
234     setOperationAction(ISD::SELECT, MVT::f32, Expand);
235     setOperationAction(ISD::SELECT, MVT::f64, Expand);
236   }
237
238   // PowerPC wants to turn select_cc of FP into fsel when possible.
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
241
242   // PowerPC wants to optimize integer setcc a bit
243   if (!Subtarget->useCRBits())
244     setOperationAction(ISD::SETCC, MVT::i32, Custom);
245
246   // PowerPC does not have BRCOND which requires SetCC
247   if (!Subtarget->useCRBits())
248     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
249
250   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
251
252   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254
255   // PowerPC does not have [U|S]INT_TO_FP
256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
258
259   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
263
264   // We cannot sextinreg(i1).  Expand to shifts.
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
266
267   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269   // support continuation, user-level threading, and etc.. As a result, no
270   // other SjLj exception interfaces are implemented and please don't build
271   // your own exception handling based on them.
272   // LLVM/Clang supports zero-cost DWARF exception handling.
273   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
275
276   // We want to legalize GlobalAddress and ConstantPool nodes into the
277   // appropriate instructions to materialize the address.
278   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
281   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
282   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
283   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
286   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
287   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
288
289   // TRAP is legal.
290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
291
292   // TRAMPOLINE is custom lowered.
293   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
295
296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
298
299   if (Subtarget->isSVR4ABI()) {
300     if (isPPC64) {
301       // VAARG always uses double-word chunks, so promote anything smaller.
302       setOperationAction(ISD::VAARG, MVT::i1, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::i8, Promote);
305       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306       setOperationAction(ISD::VAARG, MVT::i16, Promote);
307       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308       setOperationAction(ISD::VAARG, MVT::i32, Promote);
309       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310       setOperationAction(ISD::VAARG, MVT::Other, Expand);
311     } else {
312       // VAARG is custom lowered with the 32-bit SVR4 ABI.
313       setOperationAction(ISD::VAARG, MVT::Other, Custom);
314       setOperationAction(ISD::VAARG, MVT::i64, Custom);
315     }
316   } else
317     setOperationAction(ISD::VAARG, MVT::Other, Expand);
318
319   if (Subtarget->isSVR4ABI() && !isPPC64)
320     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
322   else
323     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
324
325   // Use the default implementation.
326   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
327   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
328   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
329   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
331
332   // We want to custom lower some of our intrinsics.
333   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
334
335   // To handle counter-based loop conditions.
336   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
337
338   // Comparisons that require checking two conditions.
339   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
351
352   if (Subtarget->has64BitSupport()) {
353     // They also have instructions for converting between i64 and fp.
354     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358     // This is just the low 32 bits of a (signed) fp->i64 conversion.
359     // We cannot do this with Promote because i64 is not a legal type.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
361
362     if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
363       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
364   } else {
365     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
367   }
368
369   // With the instructions enabled under FPCVT, we can do everything.
370   if (PPCSubTarget.hasFPCVT()) {
371     if (Subtarget->has64BitSupport()) {
372       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
376     }
377
378     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
382   }
383
384   if (Subtarget->use64BitRegs()) {
385     // 64-bit PowerPC implementations can support i64 types directly
386     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389     // 64-bit PowerPC wants to expand i128 shifts itself.
390     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
393   } else {
394     // 32-bit PowerPC wants to expand i64 shifts itself.
395     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
398   }
399
400   if (Subtarget->hasAltivec()) {
401     // First set operation action for all vector types to expand. Then we
402     // will selectively turn on ones that can be effectively codegen'd.
403     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
406
407       // add/sub are legal for all supported vector VT's.
408       setOperationAction(ISD::ADD , VT, Legal);
409       setOperationAction(ISD::SUB , VT, Legal);
410
411       // We promote all shuffles to v16i8.
412       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
414
415       // We promote all non-typed operations to v4i32.
416       setOperationAction(ISD::AND   , VT, Promote);
417       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
418       setOperationAction(ISD::OR    , VT, Promote);
419       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
420       setOperationAction(ISD::XOR   , VT, Promote);
421       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
422       setOperationAction(ISD::LOAD  , VT, Promote);
423       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
424       setOperationAction(ISD::SELECT, VT, Promote);
425       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426       setOperationAction(ISD::STORE, VT, Promote);
427       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
428
429       // No other operations are legal.
430       setOperationAction(ISD::MUL , VT, Expand);
431       setOperationAction(ISD::SDIV, VT, Expand);
432       setOperationAction(ISD::SREM, VT, Expand);
433       setOperationAction(ISD::UDIV, VT, Expand);
434       setOperationAction(ISD::UREM, VT, Expand);
435       setOperationAction(ISD::FDIV, VT, Expand);
436       setOperationAction(ISD::FREM, VT, Expand);
437       setOperationAction(ISD::FNEG, VT, Expand);
438       setOperationAction(ISD::FSQRT, VT, Expand);
439       setOperationAction(ISD::FLOG, VT, Expand);
440       setOperationAction(ISD::FLOG10, VT, Expand);
441       setOperationAction(ISD::FLOG2, VT, Expand);
442       setOperationAction(ISD::FEXP, VT, Expand);
443       setOperationAction(ISD::FEXP2, VT, Expand);
444       setOperationAction(ISD::FSIN, VT, Expand);
445       setOperationAction(ISD::FCOS, VT, Expand);
446       setOperationAction(ISD::FABS, VT, Expand);
447       setOperationAction(ISD::FPOWI, VT, Expand);
448       setOperationAction(ISD::FFLOOR, VT, Expand);
449       setOperationAction(ISD::FCEIL,  VT, Expand);
450       setOperationAction(ISD::FTRUNC, VT, Expand);
451       setOperationAction(ISD::FRINT,  VT, Expand);
452       setOperationAction(ISD::FNEARBYINT, VT, Expand);
453       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458       setOperationAction(ISD::UDIVREM, VT, Expand);
459       setOperationAction(ISD::SDIVREM, VT, Expand);
460       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461       setOperationAction(ISD::FPOW, VT, Expand);
462       setOperationAction(ISD::CTPOP, VT, Expand);
463       setOperationAction(ISD::CTLZ, VT, Expand);
464       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
465       setOperationAction(ISD::CTTZ, VT, Expand);
466       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
467       setOperationAction(ISD::VSELECT, VT, Expand);
468       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
469
470       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
471            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
472         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
473         setTruncStoreAction(VT, InnerVT, Expand);
474       }
475       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
476       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
477       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
478     }
479
480     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
481     // with merges, splats, etc.
482     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
483
484     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
485     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
486     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
487     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
488     setOperationAction(ISD::SELECT, MVT::v4i32,
489                        Subtarget->useCRBits() ? Legal : Expand);
490     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
491     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
492     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
493     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
494     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
495     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
496     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
497     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
498     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
499
500     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
501     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
502     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
503     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
504
505     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
506     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
507
508     if (TM.Options.UnsafeFPMath || Subtarget->hasVSX()) {
509       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
510       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
511     }
512
513     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
515     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
516
517     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
518     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
519
520     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
521     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
522     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
523     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
524
525     // Altivec does not contain unordered floating-point compare instructions
526     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
527     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
528     setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
529     setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
530     setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
531     setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
532
533     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
534     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
535
536     if (Subtarget->hasVSX()) {
537       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
538
539       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
540       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
541       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
542       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
543       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
544
545       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
546
547       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
548       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
549
550       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
551       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
552
553       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
554       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
555       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
556       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
557       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
558
559       // Share the Altivec comparison restrictions.
560       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
561       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
562       setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
563       setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
564       setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
565       setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
566
567       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
568       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
569
570       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
571       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
572
573       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
574
575       addRegisterClass(MVT::f64, &PPC::VSRCRegClass);
576
577       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
578       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
579
580       // VSX v2i64 only supports non-arithmetic operations.
581       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
582       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
583
584       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
585       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
586       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
587
588       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
589       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
590       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
591       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
592
593       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
594
595       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
596       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
597       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
598       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
599
600       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
601     }
602   }
603
604   if (Subtarget->has64BitSupport()) {
605     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
606     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
607   }
608
609   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
610   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
611   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
612   setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
613
614   setBooleanContents(ZeroOrOneBooleanContent);
615   // Altivec instructions set fields to all zeros or all ones.
616   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
617
618   if (isPPC64) {
619     setStackPointerRegisterToSaveRestore(PPC::X1);
620     setExceptionPointerRegister(PPC::X3);
621     setExceptionSelectorRegister(PPC::X4);
622   } else {
623     setStackPointerRegisterToSaveRestore(PPC::R1);
624     setExceptionPointerRegister(PPC::R3);
625     setExceptionSelectorRegister(PPC::R4);
626   }
627
628   // We have target-specific dag combine patterns for the following nodes:
629   setTargetDAGCombine(ISD::SINT_TO_FP);
630   setTargetDAGCombine(ISD::LOAD);
631   setTargetDAGCombine(ISD::STORE);
632   setTargetDAGCombine(ISD::BR_CC);
633   if (Subtarget->useCRBits())
634     setTargetDAGCombine(ISD::BRCOND);
635   setTargetDAGCombine(ISD::BSWAP);
636   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
637
638   setTargetDAGCombine(ISD::SIGN_EXTEND);
639   setTargetDAGCombine(ISD::ZERO_EXTEND);
640   setTargetDAGCombine(ISD::ANY_EXTEND);
641
642   if (Subtarget->useCRBits()) {
643     setTargetDAGCombine(ISD::TRUNCATE);
644     setTargetDAGCombine(ISD::SETCC);
645     setTargetDAGCombine(ISD::SELECT_CC);
646   }
647
648   // Use reciprocal estimates.
649   if (TM.Options.UnsafeFPMath) {
650     setTargetDAGCombine(ISD::FDIV);
651     setTargetDAGCombine(ISD::FSQRT);
652   }
653
654   // Darwin long double math library functions have $LDBL128 appended.
655   if (Subtarget->isDarwin()) {
656     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
657     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
658     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
659     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
660     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
661     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
662     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
663     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
664     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
665     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
666   }
667
668   // With 32 condition bits, we don't need to sink (and duplicate) compares
669   // aggressively in CodeGenPrep.
670   if (Subtarget->useCRBits())
671     setHasMultipleConditionRegisters();
672
673   setMinFunctionAlignment(2);
674   if (PPCSubTarget.isDarwin())
675     setPrefFunctionAlignment(4);
676
677   if (isPPC64 && Subtarget->isJITCodeModel())
678     // Temporary workaround for the inability of PPC64 JIT to handle jump
679     // tables.
680     setSupportJumpTables(false);
681
682   setInsertFencesForAtomic(true);
683
684   if (Subtarget->enableMachineScheduler())
685     setSchedulingPreference(Sched::Source);
686   else
687     setSchedulingPreference(Sched::Hybrid);
688
689   computeRegisterProperties();
690
691   // The Freescale cores does better with aggressive inlining of memcpy and
692   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
693   if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
694       Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
695     MaxStoresPerMemset = 32;
696     MaxStoresPerMemsetOptSize = 16;
697     MaxStoresPerMemcpy = 32;
698     MaxStoresPerMemcpyOptSize = 8;
699     MaxStoresPerMemmove = 32;
700     MaxStoresPerMemmoveOptSize = 8;
701
702     setPrefFunctionAlignment(4);
703   }
704 }
705
706 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
707 /// the desired ByVal argument alignment.
708 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
709                              unsigned MaxMaxAlign) {
710   if (MaxAlign == MaxMaxAlign)
711     return;
712   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
713     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
714       MaxAlign = 32;
715     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
716       MaxAlign = 16;
717   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
718     unsigned EltAlign = 0;
719     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
720     if (EltAlign > MaxAlign)
721       MaxAlign = EltAlign;
722   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
723     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
724       unsigned EltAlign = 0;
725       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
726       if (EltAlign > MaxAlign)
727         MaxAlign = EltAlign;
728       if (MaxAlign == MaxMaxAlign)
729         break;
730     }
731   }
732 }
733
734 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
735 /// function arguments in the caller parameter area.
736 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
737   // Darwin passes everything on 4 byte boundary.
738   if (PPCSubTarget.isDarwin())
739     return 4;
740
741   // 16byte and wider vectors are passed on 16byte boundary.
742   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
743   unsigned Align = PPCSubTarget.isPPC64() ? 8 : 4;
744   if (PPCSubTarget.hasAltivec() || PPCSubTarget.hasQPX())
745     getMaxByValAlign(Ty, Align, PPCSubTarget.hasQPX() ? 32 : 16);
746   return Align;
747 }
748
749 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
750   switch (Opcode) {
751   default: return 0;
752   case PPCISD::FSEL:            return "PPCISD::FSEL";
753   case PPCISD::FCFID:           return "PPCISD::FCFID";
754   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
755   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
756   case PPCISD::FRE:             return "PPCISD::FRE";
757   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
758   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
759   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
760   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
761   case PPCISD::VPERM:           return "PPCISD::VPERM";
762   case PPCISD::Hi:              return "PPCISD::Hi";
763   case PPCISD::Lo:              return "PPCISD::Lo";
764   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
765   case PPCISD::TOC_RESTORE:     return "PPCISD::TOC_RESTORE";
766   case PPCISD::LOAD:            return "PPCISD::LOAD";
767   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
768   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
769   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
770   case PPCISD::SRL:             return "PPCISD::SRL";
771   case PPCISD::SRA:             return "PPCISD::SRA";
772   case PPCISD::SHL:             return "PPCISD::SHL";
773   case PPCISD::CALL:            return "PPCISD::CALL";
774   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
775   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
776   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
777   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
778   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
779   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
780   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
781   case PPCISD::VCMP:            return "PPCISD::VCMP";
782   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
783   case PPCISD::LBRX:            return "PPCISD::LBRX";
784   case PPCISD::STBRX:           return "PPCISD::STBRX";
785   case PPCISD::LARX:            return "PPCISD::LARX";
786   case PPCISD::STCX:            return "PPCISD::STCX";
787   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
788   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
789   case PPCISD::BDZ:             return "PPCISD::BDZ";
790   case PPCISD::MFFS:            return "PPCISD::MFFS";
791   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
792   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
793   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
794   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
795   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
796   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
797   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
798   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
799   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
800   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
801   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
802   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
803   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
804   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
805   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
806   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
807   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
808   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
809   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
810   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
811   case PPCISD::SC:              return "PPCISD::SC";
812   }
813 }
814
815 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
816   if (!VT.isVector())
817     return PPCSubTarget.useCRBits() ? MVT::i1 : MVT::i32;
818   return VT.changeVectorElementTypeToInteger();
819 }
820
821 //===----------------------------------------------------------------------===//
822 // Node matching predicates, for use by the tblgen matching code.
823 //===----------------------------------------------------------------------===//
824
825 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
826 static bool isFloatingPointZero(SDValue Op) {
827   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
828     return CFP->getValueAPF().isZero();
829   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
830     // Maybe this has already been legalized into the constant pool?
831     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
832       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
833         return CFP->getValueAPF().isZero();
834   }
835   return false;
836 }
837
838 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
839 /// true if Op is undef or if it matches the specified value.
840 static bool isConstantOrUndef(int Op, int Val) {
841   return Op < 0 || Op == Val;
842 }
843
844 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
845 /// VPKUHUM instruction.
846 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
847   if (!isUnary) {
848     for (unsigned i = 0; i != 16; ++i)
849       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+1))
850         return false;
851   } else {
852     for (unsigned i = 0; i != 8; ++i)
853       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+1) ||
854           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+1))
855         return false;
856   }
857   return true;
858 }
859
860 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
861 /// VPKUWUM instruction.
862 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
863   if (!isUnary) {
864     for (unsigned i = 0; i != 16; i += 2)
865       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
866           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
867         return false;
868   } else {
869     for (unsigned i = 0; i != 8; i += 2)
870       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
871           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3) ||
872           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+2) ||
873           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+3))
874         return false;
875   }
876   return true;
877 }
878
879 /// isVMerge - Common function, used to match vmrg* shuffles.
880 ///
881 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
882                      unsigned LHSStart, unsigned RHSStart) {
883   if (N->getValueType(0) != MVT::v16i8)
884     return false;
885   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
886          "Unsupported merge size!");
887
888   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
889     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
890       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
891                              LHSStart+j+i*UnitSize) ||
892           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
893                              RHSStart+j+i*UnitSize))
894         return false;
895     }
896   return true;
897 }
898
899 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
900 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
901 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
902                              bool isUnary) {
903   if (!isUnary)
904     return isVMerge(N, UnitSize, 8, 24);
905   return isVMerge(N, UnitSize, 8, 8);
906 }
907
908 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
909 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
910 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
911                              bool isUnary) {
912   if (!isUnary)
913     return isVMerge(N, UnitSize, 0, 16);
914   return isVMerge(N, UnitSize, 0, 0);
915 }
916
917
918 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
919 /// amount, otherwise return -1.
920 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
921   if (N->getValueType(0) != MVT::v16i8)
922     return false;
923
924   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
925
926   // Find the first non-undef value in the shuffle mask.
927   unsigned i;
928   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
929     /*search*/;
930
931   if (i == 16) return -1;  // all undef.
932
933   // Otherwise, check to see if the rest of the elements are consecutively
934   // numbered from this value.
935   unsigned ShiftAmt = SVOp->getMaskElt(i);
936   if (ShiftAmt < i) return -1;
937   ShiftAmt -= i;
938
939   if (!isUnary) {
940     // Check the rest of the elements to see if they are consecutive.
941     for (++i; i != 16; ++i)
942       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
943         return -1;
944   } else {
945     // Check the rest of the elements to see if they are consecutive.
946     for (++i; i != 16; ++i)
947       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
948         return -1;
949   }
950   return ShiftAmt;
951 }
952
953 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
954 /// specifies a splat of a single element that is suitable for input to
955 /// VSPLTB/VSPLTH/VSPLTW.
956 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
957   assert(N->getValueType(0) == MVT::v16i8 &&
958          (EltSize == 1 || EltSize == 2 || EltSize == 4));
959
960   // This is a splat operation if each element of the permute is the same, and
961   // if the value doesn't reference the second vector.
962   unsigned ElementBase = N->getMaskElt(0);
963
964   // FIXME: Handle UNDEF elements too!
965   if (ElementBase >= 16)
966     return false;
967
968   // Check that the indices are consecutive, in the case of a multi-byte element
969   // splatted with a v16i8 mask.
970   for (unsigned i = 1; i != EltSize; ++i)
971     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
972       return false;
973
974   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
975     if (N->getMaskElt(i) < 0) continue;
976     for (unsigned j = 0; j != EltSize; ++j)
977       if (N->getMaskElt(i+j) != N->getMaskElt(j))
978         return false;
979   }
980   return true;
981 }
982
983 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
984 /// are -0.0.
985 bool PPC::isAllNegativeZeroVector(SDNode *N) {
986   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
987
988   APInt APVal, APUndef;
989   unsigned BitSize;
990   bool HasAnyUndefs;
991
992   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
993     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
994       return CFP->getValueAPF().isNegZero();
995
996   return false;
997 }
998
999 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1000 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1001 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
1002   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1003   assert(isSplatShuffleMask(SVOp, EltSize));
1004   return SVOp->getMaskElt(0) / EltSize;
1005 }
1006
1007 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1008 /// by using a vspltis[bhw] instruction of the specified element size, return
1009 /// the constant being splatted.  The ByteSize field indicates the number of
1010 /// bytes of each element [124] -> [bhw].
1011 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1012   SDValue OpVal(0, 0);
1013
1014   // If ByteSize of the splat is bigger than the element size of the
1015   // build_vector, then we have a case where we are checking for a splat where
1016   // multiple elements of the buildvector are folded together into a single
1017   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1018   unsigned EltSize = 16/N->getNumOperands();
1019   if (EltSize < ByteSize) {
1020     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1021     SDValue UniquedVals[4];
1022     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1023
1024     // See if all of the elements in the buildvector agree across.
1025     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1026       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1027       // If the element isn't a constant, bail fully out.
1028       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1029
1030
1031       if (UniquedVals[i&(Multiple-1)].getNode() == 0)
1032         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1033       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1034         return SDValue();  // no match.
1035     }
1036
1037     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1038     // either constant or undef values that are identical for each chunk.  See
1039     // if these chunks can form into a larger vspltis*.
1040
1041     // Check to see if all of the leading entries are either 0 or -1.  If
1042     // neither, then this won't fit into the immediate field.
1043     bool LeadingZero = true;
1044     bool LeadingOnes = true;
1045     for (unsigned i = 0; i != Multiple-1; ++i) {
1046       if (UniquedVals[i].getNode() == 0) continue;  // Must have been undefs.
1047
1048       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1049       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1050     }
1051     // Finally, check the least significant entry.
1052     if (LeadingZero) {
1053       if (UniquedVals[Multiple-1].getNode() == 0)
1054         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1055       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1056       if (Val < 16)
1057         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1058     }
1059     if (LeadingOnes) {
1060       if (UniquedVals[Multiple-1].getNode() == 0)
1061         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1062       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1063       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1064         return DAG.getTargetConstant(Val, MVT::i32);
1065     }
1066
1067     return SDValue();
1068   }
1069
1070   // Check to see if this buildvec has a single non-undef value in its elements.
1071   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1072     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1073     if (OpVal.getNode() == 0)
1074       OpVal = N->getOperand(i);
1075     else if (OpVal != N->getOperand(i))
1076       return SDValue();
1077   }
1078
1079   if (OpVal.getNode() == 0) return SDValue();  // All UNDEF: use implicit def.
1080
1081   unsigned ValSizeInBytes = EltSize;
1082   uint64_t Value = 0;
1083   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1084     Value = CN->getZExtValue();
1085   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1086     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1087     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1088   }
1089
1090   // If the splat value is larger than the element value, then we can never do
1091   // this splat.  The only case that we could fit the replicated bits into our
1092   // immediate field for would be zero, and we prefer to use vxor for it.
1093   if (ValSizeInBytes < ByteSize) return SDValue();
1094
1095   // If the element value is larger than the splat value, cut it in half and
1096   // check to see if the two halves are equal.  Continue doing this until we
1097   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1098   while (ValSizeInBytes > ByteSize) {
1099     ValSizeInBytes >>= 1;
1100
1101     // If the top half equals the bottom half, we're still ok.
1102     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1103          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1104       return SDValue();
1105   }
1106
1107   // Properly sign extend the value.
1108   int MaskVal = SignExtend32(Value, ByteSize * 8);
1109
1110   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1111   if (MaskVal == 0) return SDValue();
1112
1113   // Finally, if this value fits in a 5 bit sext field, return it
1114   if (SignExtend32<5>(MaskVal) == MaskVal)
1115     return DAG.getTargetConstant(MaskVal, MVT::i32);
1116   return SDValue();
1117 }
1118
1119 //===----------------------------------------------------------------------===//
1120 //  Addressing Mode Selection
1121 //===----------------------------------------------------------------------===//
1122
1123 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1124 /// or 64-bit immediate, and if the value can be accurately represented as a
1125 /// sign extension from a 16-bit value.  If so, this returns true and the
1126 /// immediate.
1127 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1128   if (N->getOpcode() != ISD::Constant)
1129     return false;
1130
1131   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1132   if (N->getValueType(0) == MVT::i32)
1133     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1134   else
1135     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1136 }
1137 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1138   return isIntS16Immediate(Op.getNode(), Imm);
1139 }
1140
1141
1142 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1143 /// can be represented as an indexed [r+r] operation.  Returns false if it
1144 /// can be more efficiently represented with [r+imm].
1145 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1146                                             SDValue &Index,
1147                                             SelectionDAG &DAG) const {
1148   short imm = 0;
1149   if (N.getOpcode() == ISD::ADD) {
1150     if (isIntS16Immediate(N.getOperand(1), imm))
1151       return false;    // r+i
1152     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1153       return false;    // r+i
1154
1155     Base = N.getOperand(0);
1156     Index = N.getOperand(1);
1157     return true;
1158   } else if (N.getOpcode() == ISD::OR) {
1159     if (isIntS16Immediate(N.getOperand(1), imm))
1160       return false;    // r+i can fold it if we can.
1161
1162     // If this is an or of disjoint bitfields, we can codegen this as an add
1163     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1164     // disjoint.
1165     APInt LHSKnownZero, LHSKnownOne;
1166     APInt RHSKnownZero, RHSKnownOne;
1167     DAG.ComputeMaskedBits(N.getOperand(0),
1168                           LHSKnownZero, LHSKnownOne);
1169
1170     if (LHSKnownZero.getBoolValue()) {
1171       DAG.ComputeMaskedBits(N.getOperand(1),
1172                             RHSKnownZero, RHSKnownOne);
1173       // If all of the bits are known zero on the LHS or RHS, the add won't
1174       // carry.
1175       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1176         Base = N.getOperand(0);
1177         Index = N.getOperand(1);
1178         return true;
1179       }
1180     }
1181   }
1182
1183   return false;
1184 }
1185
1186 // If we happen to be doing an i64 load or store into a stack slot that has
1187 // less than a 4-byte alignment, then the frame-index elimination may need to
1188 // use an indexed load or store instruction (because the offset may not be a
1189 // multiple of 4). The extra register needed to hold the offset comes from the
1190 // register scavenger, and it is possible that the scavenger will need to use
1191 // an emergency spill slot. As a result, we need to make sure that a spill slot
1192 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1193 // stack slot.
1194 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1195   // FIXME: This does not handle the LWA case.
1196   if (VT != MVT::i64)
1197     return;
1198
1199   // NOTE: We'll exclude negative FIs here, which come from argument
1200   // lowering, because there are no known test cases triggering this problem
1201   // using packed structures (or similar). We can remove this exclusion if
1202   // we find such a test case. The reason why this is so test-case driven is
1203   // because this entire 'fixup' is only to prevent crashes (from the
1204   // register scavenger) on not-really-valid inputs. For example, if we have:
1205   //   %a = alloca i1
1206   //   %b = bitcast i1* %a to i64*
1207   //   store i64* a, i64 b
1208   // then the store should really be marked as 'align 1', but is not. If it
1209   // were marked as 'align 1' then the indexed form would have been
1210   // instruction-selected initially, and the problem this 'fixup' is preventing
1211   // won't happen regardless.
1212   if (FrameIdx < 0)
1213     return;
1214
1215   MachineFunction &MF = DAG.getMachineFunction();
1216   MachineFrameInfo *MFI = MF.getFrameInfo();
1217
1218   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1219   if (Align >= 4)
1220     return;
1221
1222   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1223   FuncInfo->setHasNonRISpills();
1224 }
1225
1226 /// Returns true if the address N can be represented by a base register plus
1227 /// a signed 16-bit displacement [r+imm], and if it is not better
1228 /// represented as reg+reg.  If Aligned is true, only accept displacements
1229 /// suitable for STD and friends, i.e. multiples of 4.
1230 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1231                                             SDValue &Base,
1232                                             SelectionDAG &DAG,
1233                                             bool Aligned) const {
1234   // FIXME dl should come from parent load or store, not from address
1235   SDLoc dl(N);
1236   // If this can be more profitably realized as r+r, fail.
1237   if (SelectAddressRegReg(N, Disp, Base, DAG))
1238     return false;
1239
1240   if (N.getOpcode() == ISD::ADD) {
1241     short imm = 0;
1242     if (isIntS16Immediate(N.getOperand(1), imm) &&
1243         (!Aligned || (imm & 3) == 0)) {
1244       Disp = DAG.getTargetConstant(imm, N.getValueType());
1245       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1246         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1247         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1248       } else {
1249         Base = N.getOperand(0);
1250       }
1251       return true; // [r+i]
1252     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1253       // Match LOAD (ADD (X, Lo(G))).
1254       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1255              && "Cannot handle constant offsets yet!");
1256       Disp = N.getOperand(1).getOperand(0);  // The global address.
1257       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1258              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1259              Disp.getOpcode() == ISD::TargetConstantPool ||
1260              Disp.getOpcode() == ISD::TargetJumpTable);
1261       Base = N.getOperand(0);
1262       return true;  // [&g+r]
1263     }
1264   } else if (N.getOpcode() == ISD::OR) {
1265     short imm = 0;
1266     if (isIntS16Immediate(N.getOperand(1), imm) &&
1267         (!Aligned || (imm & 3) == 0)) {
1268       // If this is an or of disjoint bitfields, we can codegen this as an add
1269       // (for better address arithmetic) if the LHS and RHS of the OR are
1270       // provably disjoint.
1271       APInt LHSKnownZero, LHSKnownOne;
1272       DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1273
1274       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1275         // If all of the bits are known zero on the LHS or RHS, the add won't
1276         // carry.
1277         Base = N.getOperand(0);
1278         Disp = DAG.getTargetConstant(imm, N.getValueType());
1279         return true;
1280       }
1281     }
1282   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1283     // Loading from a constant address.
1284
1285     // If this address fits entirely in a 16-bit sext immediate field, codegen
1286     // this as "d, 0"
1287     short Imm;
1288     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1289       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1290       Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1291                              CN->getValueType(0));
1292       return true;
1293     }
1294
1295     // Handle 32-bit sext immediates with LIS + addr mode.
1296     if ((CN->getValueType(0) == MVT::i32 ||
1297          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1298         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1299       int Addr = (int)CN->getZExtValue();
1300
1301       // Otherwise, break this down into an LIS + disp.
1302       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1303
1304       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1305       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1306       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1307       return true;
1308     }
1309   }
1310
1311   Disp = DAG.getTargetConstant(0, getPointerTy());
1312   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1313     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1314     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1315   } else
1316     Base = N;
1317   return true;      // [r+0]
1318 }
1319
1320 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1321 /// represented as an indexed [r+r] operation.
1322 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1323                                                 SDValue &Index,
1324                                                 SelectionDAG &DAG) const {
1325   // Check to see if we can easily represent this as an [r+r] address.  This
1326   // will fail if it thinks that the address is more profitably represented as
1327   // reg+imm, e.g. where imm = 0.
1328   if (SelectAddressRegReg(N, Base, Index, DAG))
1329     return true;
1330
1331   // If the operand is an addition, always emit this as [r+r], since this is
1332   // better (for code size, and execution, as the memop does the add for free)
1333   // than emitting an explicit add.
1334   if (N.getOpcode() == ISD::ADD) {
1335     Base = N.getOperand(0);
1336     Index = N.getOperand(1);
1337     return true;
1338   }
1339
1340   // Otherwise, do it the hard way, using R0 as the base register.
1341   Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1342                          N.getValueType());
1343   Index = N;
1344   return true;
1345 }
1346
1347 /// getPreIndexedAddressParts - returns true by value, base pointer and
1348 /// offset pointer and addressing mode by reference if the node's address
1349 /// can be legally represented as pre-indexed load / store address.
1350 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1351                                                   SDValue &Offset,
1352                                                   ISD::MemIndexedMode &AM,
1353                                                   SelectionDAG &DAG) const {
1354   if (DisablePPCPreinc) return false;
1355
1356   bool isLoad = true;
1357   SDValue Ptr;
1358   EVT VT;
1359   unsigned Alignment;
1360   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1361     Ptr = LD->getBasePtr();
1362     VT = LD->getMemoryVT();
1363     Alignment = LD->getAlignment();
1364   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1365     Ptr = ST->getBasePtr();
1366     VT  = ST->getMemoryVT();
1367     Alignment = ST->getAlignment();
1368     isLoad = false;
1369   } else
1370     return false;
1371
1372   // PowerPC doesn't have preinc load/store instructions for vectors.
1373   if (VT.isVector())
1374     return false;
1375
1376   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1377
1378     // Common code will reject creating a pre-inc form if the base pointer
1379     // is a frame index, or if N is a store and the base pointer is either
1380     // the same as or a predecessor of the value being stored.  Check for
1381     // those situations here, and try with swapped Base/Offset instead.
1382     bool Swap = false;
1383
1384     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1385       Swap = true;
1386     else if (!isLoad) {
1387       SDValue Val = cast<StoreSDNode>(N)->getValue();
1388       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1389         Swap = true;
1390     }
1391
1392     if (Swap)
1393       std::swap(Base, Offset);
1394
1395     AM = ISD::PRE_INC;
1396     return true;
1397   }
1398
1399   // LDU/STU can only handle immediates that are a multiple of 4.
1400   if (VT != MVT::i64) {
1401     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1402       return false;
1403   } else {
1404     // LDU/STU need an address with at least 4-byte alignment.
1405     if (Alignment < 4)
1406       return false;
1407
1408     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1409       return false;
1410   }
1411
1412   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1413     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1414     // sext i32 to i64 when addr mode is r+i.
1415     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1416         LD->getExtensionType() == ISD::SEXTLOAD &&
1417         isa<ConstantSDNode>(Offset))
1418       return false;
1419   }
1420
1421   AM = ISD::PRE_INC;
1422   return true;
1423 }
1424
1425 //===----------------------------------------------------------------------===//
1426 //  LowerOperation implementation
1427 //===----------------------------------------------------------------------===//
1428
1429 /// GetLabelAccessInfo - Return true if we should reference labels using a
1430 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1431 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1432                                unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1433   HiOpFlags = PPCII::MO_HA;
1434   LoOpFlags = PPCII::MO_LO;
1435
1436   // Don't use the pic base if not in PIC relocation model.  Or if we are on a
1437   // non-darwin platform.  We don't support PIC on other platforms yet.
1438   bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1439                TM.getSubtarget<PPCSubtarget>().isDarwin();
1440   if (isPIC) {
1441     HiOpFlags |= PPCII::MO_PIC_FLAG;
1442     LoOpFlags |= PPCII::MO_PIC_FLAG;
1443   }
1444
1445   // If this is a reference to a global value that requires a non-lazy-ptr, make
1446   // sure that instruction lowering adds it.
1447   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1448     HiOpFlags |= PPCII::MO_NLP_FLAG;
1449     LoOpFlags |= PPCII::MO_NLP_FLAG;
1450
1451     if (GV->hasHiddenVisibility()) {
1452       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1453       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1454     }
1455   }
1456
1457   return isPIC;
1458 }
1459
1460 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1461                              SelectionDAG &DAG) {
1462   EVT PtrVT = HiPart.getValueType();
1463   SDValue Zero = DAG.getConstant(0, PtrVT);
1464   SDLoc DL(HiPart);
1465
1466   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1467   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1468
1469   // With PIC, the first instruction is actually "GR+hi(&G)".
1470   if (isPIC)
1471     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1472                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1473
1474   // Generate non-pic code that has direct accesses to the constant pool.
1475   // The address of the global is just (hi(&g)+lo(&g)).
1476   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1477 }
1478
1479 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1480                                              SelectionDAG &DAG) const {
1481   EVT PtrVT = Op.getValueType();
1482   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1483   const Constant *C = CP->getConstVal();
1484
1485   // 64-bit SVR4 ABI code is always position-independent.
1486   // The actual address of the GlobalValue is stored in the TOC.
1487   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1488     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1489     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1490                        DAG.getRegister(PPC::X2, MVT::i64));
1491   }
1492
1493   unsigned MOHiFlag, MOLoFlag;
1494   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1495   SDValue CPIHi =
1496     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1497   SDValue CPILo =
1498     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1499   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1500 }
1501
1502 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1503   EVT PtrVT = Op.getValueType();
1504   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1505
1506   // 64-bit SVR4 ABI code is always position-independent.
1507   // The actual address of the GlobalValue is stored in the TOC.
1508   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1509     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1510     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1511                        DAG.getRegister(PPC::X2, MVT::i64));
1512   }
1513
1514   unsigned MOHiFlag, MOLoFlag;
1515   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1516   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1517   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1518   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1519 }
1520
1521 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1522                                              SelectionDAG &DAG) const {
1523   EVT PtrVT = Op.getValueType();
1524
1525   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1526
1527   unsigned MOHiFlag, MOLoFlag;
1528   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1529   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1530   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1531   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1532 }
1533
1534 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1535                                               SelectionDAG &DAG) const {
1536
1537   // FIXME: TLS addresses currently use medium model code sequences,
1538   // which is the most useful form.  Eventually support for small and
1539   // large models could be added if users need it, at the cost of
1540   // additional complexity.
1541   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1542   SDLoc dl(GA);
1543   const GlobalValue *GV = GA->getGlobal();
1544   EVT PtrVT = getPointerTy();
1545   bool is64bit = PPCSubTarget.isPPC64();
1546
1547   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1548
1549   if (Model == TLSModel::LocalExec) {
1550     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1551                                                PPCII::MO_TPREL_HA);
1552     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1553                                                PPCII::MO_TPREL_LO);
1554     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1555                                      is64bit ? MVT::i64 : MVT::i32);
1556     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1557     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1558   }
1559
1560   if (Model == TLSModel::InitialExec) {
1561     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1562     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1563                                                 PPCII::MO_TLS);
1564     SDValue GOTPtr;
1565     if (is64bit) {
1566       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1567       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1568                            PtrVT, GOTReg, TGA);
1569     } else
1570       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1571     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1572                                    PtrVT, TGA, GOTPtr);
1573     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1574   }
1575
1576   if (Model == TLSModel::GeneralDynamic) {
1577     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1578     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1579     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1580                                      GOTReg, TGA);
1581     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1582                                    GOTEntryHi, TGA);
1583
1584     // We need a chain node, and don't have one handy.  The underlying
1585     // call has no side effects, so using the function entry node
1586     // suffices.
1587     SDValue Chain = DAG.getEntryNode();
1588     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1589     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1590     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1591                                   PtrVT, ParmReg, TGA);
1592     // The return value from GET_TLS_ADDR really is in X3 already, but
1593     // some hacks are needed here to tie everything together.  The extra
1594     // copies dissolve during subsequent transforms.
1595     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1596     return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1597   }
1598
1599   if (Model == TLSModel::LocalDynamic) {
1600     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1601     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1602     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1603                                      GOTReg, TGA);
1604     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1605                                    GOTEntryHi, TGA);
1606
1607     // We need a chain node, and don't have one handy.  The underlying
1608     // call has no side effects, so using the function entry node
1609     // suffices.
1610     SDValue Chain = DAG.getEntryNode();
1611     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1612     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1613     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1614                                   PtrVT, ParmReg, TGA);
1615     // The return value from GET_TLSLD_ADDR really is in X3 already, but
1616     // some hacks are needed here to tie everything together.  The extra
1617     // copies dissolve during subsequent transforms.
1618     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1619     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1620                                       Chain, ParmReg, TGA);
1621     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1622   }
1623
1624   llvm_unreachable("Unknown TLS model!");
1625 }
1626
1627 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1628                                               SelectionDAG &DAG) const {
1629   EVT PtrVT = Op.getValueType();
1630   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1631   SDLoc DL(GSDN);
1632   const GlobalValue *GV = GSDN->getGlobal();
1633
1634   // 64-bit SVR4 ABI code is always position-independent.
1635   // The actual address of the GlobalValue is stored in the TOC.
1636   if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1637     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1638     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1639                        DAG.getRegister(PPC::X2, MVT::i64));
1640   }
1641
1642   unsigned MOHiFlag, MOLoFlag;
1643   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1644
1645   SDValue GAHi =
1646     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1647   SDValue GALo =
1648     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1649
1650   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1651
1652   // If the global reference is actually to a non-lazy-pointer, we have to do an
1653   // extra load to get the address of the global.
1654   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1655     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1656                       false, false, false, 0);
1657   return Ptr;
1658 }
1659
1660 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1661   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1662   SDLoc dl(Op);
1663
1664   // If we're comparing for equality to zero, expose the fact that this is
1665   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1666   // fold the new nodes.
1667   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1668     if (C->isNullValue() && CC == ISD::SETEQ) {
1669       EVT VT = Op.getOperand(0).getValueType();
1670       SDValue Zext = Op.getOperand(0);
1671       if (VT.bitsLT(MVT::i32)) {
1672         VT = MVT::i32;
1673         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1674       }
1675       unsigned Log2b = Log2_32(VT.getSizeInBits());
1676       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1677       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1678                                 DAG.getConstant(Log2b, MVT::i32));
1679       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1680     }
1681     // Leave comparisons against 0 and -1 alone for now, since they're usually
1682     // optimized.  FIXME: revisit this when we can custom lower all setcc
1683     // optimizations.
1684     if (C->isAllOnesValue() || C->isNullValue())
1685       return SDValue();
1686   }
1687
1688   // If we have an integer seteq/setne, turn it into a compare against zero
1689   // by xor'ing the rhs with the lhs, which is faster than setting a
1690   // condition register, reading it back out, and masking the correct bit.  The
1691   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1692   // the result to other bit-twiddling opportunities.
1693   EVT LHSVT = Op.getOperand(0).getValueType();
1694   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1695     EVT VT = Op.getValueType();
1696     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1697                                 Op.getOperand(1));
1698     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1699   }
1700   return SDValue();
1701 }
1702
1703 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1704                                       const PPCSubtarget &Subtarget) const {
1705   SDNode *Node = Op.getNode();
1706   EVT VT = Node->getValueType(0);
1707   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1708   SDValue InChain = Node->getOperand(0);
1709   SDValue VAListPtr = Node->getOperand(1);
1710   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1711   SDLoc dl(Node);
1712
1713   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1714
1715   // gpr_index
1716   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1717                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1718                                     false, false, 0);
1719   InChain = GprIndex.getValue(1);
1720
1721   if (VT == MVT::i64) {
1722     // Check if GprIndex is even
1723     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1724                                  DAG.getConstant(1, MVT::i32));
1725     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1726                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1727     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1728                                           DAG.getConstant(1, MVT::i32));
1729     // Align GprIndex to be even if it isn't
1730     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1731                            GprIndex);
1732   }
1733
1734   // fpr index is 1 byte after gpr
1735   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1736                                DAG.getConstant(1, MVT::i32));
1737
1738   // fpr
1739   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1740                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1741                                     false, false, 0);
1742   InChain = FprIndex.getValue(1);
1743
1744   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1745                                        DAG.getConstant(8, MVT::i32));
1746
1747   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1748                                         DAG.getConstant(4, MVT::i32));
1749
1750   // areas
1751   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1752                                      MachinePointerInfo(), false, false,
1753                                      false, 0);
1754   InChain = OverflowArea.getValue(1);
1755
1756   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1757                                     MachinePointerInfo(), false, false,
1758                                     false, 0);
1759   InChain = RegSaveArea.getValue(1);
1760
1761   // select overflow_area if index > 8
1762   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1763                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1764
1765   // adjustment constant gpr_index * 4/8
1766   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1767                                     VT.isInteger() ? GprIndex : FprIndex,
1768                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1769                                                     MVT::i32));
1770
1771   // OurReg = RegSaveArea + RegConstant
1772   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1773                                RegConstant);
1774
1775   // Floating types are 32 bytes into RegSaveArea
1776   if (VT.isFloatingPoint())
1777     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1778                          DAG.getConstant(32, MVT::i32));
1779
1780   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1781   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1782                                    VT.isInteger() ? GprIndex : FprIndex,
1783                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1784                                                    MVT::i32));
1785
1786   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1787                               VT.isInteger() ? VAListPtr : FprPtr,
1788                               MachinePointerInfo(SV),
1789                               MVT::i8, false, false, 0);
1790
1791   // determine if we should load from reg_save_area or overflow_area
1792   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1793
1794   // increase overflow_area by 4/8 if gpr/fpr > 8
1795   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1796                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1797                                           MVT::i32));
1798
1799   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1800                              OverflowAreaPlusN);
1801
1802   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1803                               OverflowAreaPtr,
1804                               MachinePointerInfo(),
1805                               MVT::i32, false, false, 0);
1806
1807   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1808                      false, false, false, 0);
1809 }
1810
1811 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1812                                        const PPCSubtarget &Subtarget) const {
1813   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1814
1815   // We have to copy the entire va_list struct:
1816   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1817   return DAG.getMemcpy(Op.getOperand(0), Op,
1818                        Op.getOperand(1), Op.getOperand(2),
1819                        DAG.getConstant(12, MVT::i32), 8, false, true,
1820                        MachinePointerInfo(), MachinePointerInfo());
1821 }
1822
1823 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1824                                                   SelectionDAG &DAG) const {
1825   return Op.getOperand(0);
1826 }
1827
1828 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1829                                                 SelectionDAG &DAG) const {
1830   SDValue Chain = Op.getOperand(0);
1831   SDValue Trmp = Op.getOperand(1); // trampoline
1832   SDValue FPtr = Op.getOperand(2); // nested function
1833   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1834   SDLoc dl(Op);
1835
1836   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1837   bool isPPC64 = (PtrVT == MVT::i64);
1838   Type *IntPtrTy =
1839     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1840                                                              *DAG.getContext());
1841
1842   TargetLowering::ArgListTy Args;
1843   TargetLowering::ArgListEntry Entry;
1844
1845   Entry.Ty = IntPtrTy;
1846   Entry.Node = Trmp; Args.push_back(Entry);
1847
1848   // TrampSize == (isPPC64 ? 48 : 40);
1849   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1850                                isPPC64 ? MVT::i64 : MVT::i32);
1851   Args.push_back(Entry);
1852
1853   Entry.Node = FPtr; Args.push_back(Entry);
1854   Entry.Node = Nest; Args.push_back(Entry);
1855
1856   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1857   TargetLowering::CallLoweringInfo CLI(Chain,
1858                                        Type::getVoidTy(*DAG.getContext()),
1859                                        false, false, false, false, 0,
1860                                        CallingConv::C,
1861                 /*isTailCall=*/false,
1862                                        /*doesNotRet=*/false,
1863                                        /*isReturnValueUsed=*/true,
1864                 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1865                 Args, DAG, dl);
1866   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1867
1868   return CallResult.second;
1869 }
1870
1871 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1872                                         const PPCSubtarget &Subtarget) const {
1873   MachineFunction &MF = DAG.getMachineFunction();
1874   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1875
1876   SDLoc dl(Op);
1877
1878   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1879     // vastart just stores the address of the VarArgsFrameIndex slot into the
1880     // memory location argument.
1881     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1882     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1883     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1884     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1885                         MachinePointerInfo(SV),
1886                         false, false, 0);
1887   }
1888
1889   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1890   // We suppose the given va_list is already allocated.
1891   //
1892   // typedef struct {
1893   //  char gpr;     /* index into the array of 8 GPRs
1894   //                 * stored in the register save area
1895   //                 * gpr=0 corresponds to r3,
1896   //                 * gpr=1 to r4, etc.
1897   //                 */
1898   //  char fpr;     /* index into the array of 8 FPRs
1899   //                 * stored in the register save area
1900   //                 * fpr=0 corresponds to f1,
1901   //                 * fpr=1 to f2, etc.
1902   //                 */
1903   //  char *overflow_arg_area;
1904   //                /* location on stack that holds
1905   //                 * the next overflow argument
1906   //                 */
1907   //  char *reg_save_area;
1908   //               /* where r3:r10 and f1:f8 (if saved)
1909   //                * are stored
1910   //                */
1911   // } va_list[1];
1912
1913
1914   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1915   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1916
1917
1918   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1919
1920   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1921                                             PtrVT);
1922   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1923                                  PtrVT);
1924
1925   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1926   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1927
1928   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1929   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1930
1931   uint64_t FPROffset = 1;
1932   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1933
1934   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1935
1936   // Store first byte : number of int regs
1937   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1938                                          Op.getOperand(1),
1939                                          MachinePointerInfo(SV),
1940                                          MVT::i8, false, false, 0);
1941   uint64_t nextOffset = FPROffset;
1942   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1943                                   ConstFPROffset);
1944
1945   // Store second byte : number of float regs
1946   SDValue secondStore =
1947     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1948                       MachinePointerInfo(SV, nextOffset), MVT::i8,
1949                       false, false, 0);
1950   nextOffset += StackOffset;
1951   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1952
1953   // Store second word : arguments given on stack
1954   SDValue thirdStore =
1955     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1956                  MachinePointerInfo(SV, nextOffset),
1957                  false, false, 0);
1958   nextOffset += FrameOffset;
1959   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1960
1961   // Store third word : arguments given in registers
1962   return DAG.getStore(thirdStore, dl, FR, nextPtr,
1963                       MachinePointerInfo(SV, nextOffset),
1964                       false, false, 0);
1965
1966 }
1967
1968 #include "PPCGenCallingConv.inc"
1969
1970 // Function whose sole purpose is to kill compiler warnings 
1971 // stemming from unused functions included from PPCGenCallingConv.inc.
1972 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
1973   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
1974 }
1975
1976 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1977                                       CCValAssign::LocInfo &LocInfo,
1978                                       ISD::ArgFlagsTy &ArgFlags,
1979                                       CCState &State) {
1980   return true;
1981 }
1982
1983 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1984                                              MVT &LocVT,
1985                                              CCValAssign::LocInfo &LocInfo,
1986                                              ISD::ArgFlagsTy &ArgFlags,
1987                                              CCState &State) {
1988   static const uint16_t ArgRegs[] = {
1989     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1990     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1991   };
1992   const unsigned NumArgRegs = array_lengthof(ArgRegs);
1993
1994   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1995
1996   // Skip one register if the first unallocated register has an even register
1997   // number and there are still argument registers available which have not been
1998   // allocated yet. RegNum is actually an index into ArgRegs, which means we
1999   // need to skip a register if RegNum is odd.
2000   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2001     State.AllocateReg(ArgRegs[RegNum]);
2002   }
2003
2004   // Always return false here, as this function only makes sure that the first
2005   // unallocated register has an odd register number and does not actually
2006   // allocate a register for the current argument.
2007   return false;
2008 }
2009
2010 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2011                                                MVT &LocVT,
2012                                                CCValAssign::LocInfo &LocInfo,
2013                                                ISD::ArgFlagsTy &ArgFlags,
2014                                                CCState &State) {
2015   static const uint16_t ArgRegs[] = {
2016     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2017     PPC::F8
2018   };
2019
2020   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2021
2022   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2023
2024   // If there is only one Floating-point register left we need to put both f64
2025   // values of a split ppc_fp128 value on the stack.
2026   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2027     State.AllocateReg(ArgRegs[RegNum]);
2028   }
2029
2030   // Always return false here, as this function only makes sure that the two f64
2031   // values a ppc_fp128 value is split into are both passed in registers or both
2032   // passed on the stack and does not actually allocate a register for the
2033   // current argument.
2034   return false;
2035 }
2036
2037 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2038 /// on Darwin.
2039 static const uint16_t *GetFPR() {
2040   static const uint16_t FPR[] = {
2041     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2042     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2043   };
2044
2045   return FPR;
2046 }
2047
2048 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2049 /// the stack.
2050 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2051                                        unsigned PtrByteSize) {
2052   unsigned ArgSize = ArgVT.getStoreSize();
2053   if (Flags.isByVal())
2054     ArgSize = Flags.getByValSize();
2055   ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2056
2057   return ArgSize;
2058 }
2059
2060 SDValue
2061 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2062                                         CallingConv::ID CallConv, bool isVarArg,
2063                                         const SmallVectorImpl<ISD::InputArg>
2064                                           &Ins,
2065                                         SDLoc dl, SelectionDAG &DAG,
2066                                         SmallVectorImpl<SDValue> &InVals)
2067                                           const {
2068   if (PPCSubTarget.isSVR4ABI()) {
2069     if (PPCSubTarget.isPPC64())
2070       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2071                                          dl, DAG, InVals);
2072     else
2073       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2074                                          dl, DAG, InVals);
2075   } else {
2076     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2077                                        dl, DAG, InVals);
2078   }
2079 }
2080
2081 SDValue
2082 PPCTargetLowering::LowerFormalArguments_32SVR4(
2083                                       SDValue Chain,
2084                                       CallingConv::ID CallConv, bool isVarArg,
2085                                       const SmallVectorImpl<ISD::InputArg>
2086                                         &Ins,
2087                                       SDLoc dl, SelectionDAG &DAG,
2088                                       SmallVectorImpl<SDValue> &InVals) const {
2089
2090   // 32-bit SVR4 ABI Stack Frame Layout:
2091   //              +-----------------------------------+
2092   //        +-->  |            Back chain             |
2093   //        |     +-----------------------------------+
2094   //        |     | Floating-point register save area |
2095   //        |     +-----------------------------------+
2096   //        |     |    General register save area     |
2097   //        |     +-----------------------------------+
2098   //        |     |          CR save word             |
2099   //        |     +-----------------------------------+
2100   //        |     |         VRSAVE save word          |
2101   //        |     +-----------------------------------+
2102   //        |     |         Alignment padding         |
2103   //        |     +-----------------------------------+
2104   //        |     |     Vector register save area     |
2105   //        |     +-----------------------------------+
2106   //        |     |       Local variable space        |
2107   //        |     +-----------------------------------+
2108   //        |     |        Parameter list area        |
2109   //        |     +-----------------------------------+
2110   //        |     |           LR save word            |
2111   //        |     +-----------------------------------+
2112   // SP-->  +---  |            Back chain             |
2113   //              +-----------------------------------+
2114   //
2115   // Specifications:
2116   //   System V Application Binary Interface PowerPC Processor Supplement
2117   //   AltiVec Technology Programming Interface Manual
2118
2119   MachineFunction &MF = DAG.getMachineFunction();
2120   MachineFrameInfo *MFI = MF.getFrameInfo();
2121   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2122
2123   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2124   // Potential tail calls could cause overwriting of argument stack slots.
2125   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2126                        (CallConv == CallingConv::Fast));
2127   unsigned PtrByteSize = 4;
2128
2129   // Assign locations to all of the incoming arguments.
2130   SmallVector<CCValAssign, 16> ArgLocs;
2131   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2132                  getTargetMachine(), ArgLocs, *DAG.getContext());
2133
2134   // Reserve space for the linkage area on the stack.
2135   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2136
2137   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2138
2139   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2140     CCValAssign &VA = ArgLocs[i];
2141
2142     // Arguments stored in registers.
2143     if (VA.isRegLoc()) {
2144       const TargetRegisterClass *RC;
2145       EVT ValVT = VA.getValVT();
2146
2147       switch (ValVT.getSimpleVT().SimpleTy) {
2148         default:
2149           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2150         case MVT::i1:
2151         case MVT::i32:
2152           RC = &PPC::GPRCRegClass;
2153           break;
2154         case MVT::f32:
2155           RC = &PPC::F4RCRegClass;
2156           break;
2157         case MVT::f64:
2158           RC = &PPC::F8RCRegClass;
2159           break;
2160         case MVT::v16i8:
2161         case MVT::v8i16:
2162         case MVT::v4i32:
2163         case MVT::v4f32:
2164         case MVT::v2f64:
2165         case MVT::v2i64:
2166           RC = &PPC::VRRCRegClass;
2167           break;
2168       }
2169
2170       // Transform the arguments stored in physical registers into virtual ones.
2171       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2172       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2173                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2174
2175       if (ValVT == MVT::i1)
2176         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2177
2178       InVals.push_back(ArgValue);
2179     } else {
2180       // Argument stored in memory.
2181       assert(VA.isMemLoc());
2182
2183       unsigned ArgSize = VA.getLocVT().getStoreSize();
2184       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2185                                       isImmutable);
2186
2187       // Create load nodes to retrieve arguments from the stack.
2188       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2189       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2190                                    MachinePointerInfo(),
2191                                    false, false, false, 0));
2192     }
2193   }
2194
2195   // Assign locations to all of the incoming aggregate by value arguments.
2196   // Aggregates passed by value are stored in the local variable space of the
2197   // caller's stack frame, right above the parameter list area.
2198   SmallVector<CCValAssign, 16> ByValArgLocs;
2199   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2200                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
2201
2202   // Reserve stack space for the allocations in CCInfo.
2203   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2204
2205   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2206
2207   // Area that is at least reserved in the caller of this function.
2208   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2209
2210   // Set the size that is at least reserved in caller of this function.  Tail
2211   // call optimized function's reserved stack space needs to be aligned so that
2212   // taking the difference between two stack areas will result in an aligned
2213   // stack.
2214   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2215
2216   MinReservedArea =
2217     std::max(MinReservedArea,
2218              PPCFrameLowering::getMinCallFrameSize(false, false));
2219
2220   unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2221     getStackAlignment();
2222   unsigned AlignMask = TargetAlign-1;
2223   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2224
2225   FI->setMinReservedArea(MinReservedArea);
2226
2227   SmallVector<SDValue, 8> MemOps;
2228
2229   // If the function takes variable number of arguments, make a frame index for
2230   // the start of the first vararg value... for expansion of llvm.va_start.
2231   if (isVarArg) {
2232     static const uint16_t GPArgRegs[] = {
2233       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2234       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2235     };
2236     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2237
2238     static const uint16_t FPArgRegs[] = {
2239       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2240       PPC::F8
2241     };
2242     const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2243
2244     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2245                                                           NumGPArgRegs));
2246     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2247                                                           NumFPArgRegs));
2248
2249     // Make room for NumGPArgRegs and NumFPArgRegs.
2250     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2251                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2252
2253     FuncInfo->setVarArgsStackOffset(
2254       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2255                              CCInfo.getNextStackOffset(), true));
2256
2257     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2258     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2259
2260     // The fixed integer arguments of a variadic function are stored to the
2261     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2262     // the result of va_next.
2263     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2264       // Get an existing live-in vreg, or add a new one.
2265       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2266       if (!VReg)
2267         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2268
2269       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2270       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2271                                    MachinePointerInfo(), false, false, 0);
2272       MemOps.push_back(Store);
2273       // Increment the address by four for the next argument to store
2274       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2275       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2276     }
2277
2278     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2279     // is set.
2280     // The double arguments are stored to the VarArgsFrameIndex
2281     // on the stack.
2282     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2283       // Get an existing live-in vreg, or add a new one.
2284       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2285       if (!VReg)
2286         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2287
2288       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2289       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2290                                    MachinePointerInfo(), false, false, 0);
2291       MemOps.push_back(Store);
2292       // Increment the address by eight for the next argument to store
2293       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2294                                          PtrVT);
2295       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2296     }
2297   }
2298
2299   if (!MemOps.empty())
2300     Chain = DAG.getNode(ISD::TokenFactor, dl,
2301                         MVT::Other, &MemOps[0], MemOps.size());
2302
2303   return Chain;
2304 }
2305
2306 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2307 // value to MVT::i64 and then truncate to the correct register size.
2308 SDValue
2309 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2310                                      SelectionDAG &DAG, SDValue ArgVal,
2311                                      SDLoc dl) const {
2312   if (Flags.isSExt())
2313     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2314                          DAG.getValueType(ObjectVT));
2315   else if (Flags.isZExt())
2316     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2317                          DAG.getValueType(ObjectVT));
2318
2319   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2320 }
2321
2322 // Set the size that is at least reserved in caller of this function.  Tail
2323 // call optimized functions' reserved stack space needs to be aligned so that
2324 // taking the difference between two stack areas will result in an aligned
2325 // stack.
2326 void
2327 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2328                                       unsigned nAltivecParamsAtEnd,
2329                                       unsigned MinReservedArea,
2330                                       bool isPPC64) const {
2331   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2332   // Add the Altivec parameters at the end, if needed.
2333   if (nAltivecParamsAtEnd) {
2334     MinReservedArea = ((MinReservedArea+15)/16)*16;
2335     MinReservedArea += 16*nAltivecParamsAtEnd;
2336   }
2337   MinReservedArea =
2338     std::max(MinReservedArea,
2339              PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2340   unsigned TargetAlign
2341     = DAG.getMachineFunction().getTarget().getFrameLowering()->
2342         getStackAlignment();
2343   unsigned AlignMask = TargetAlign-1;
2344   MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2345   FI->setMinReservedArea(MinReservedArea);
2346 }
2347
2348 SDValue
2349 PPCTargetLowering::LowerFormalArguments_64SVR4(
2350                                       SDValue Chain,
2351                                       CallingConv::ID CallConv, bool isVarArg,
2352                                       const SmallVectorImpl<ISD::InputArg>
2353                                         &Ins,
2354                                       SDLoc dl, SelectionDAG &DAG,
2355                                       SmallVectorImpl<SDValue> &InVals) const {
2356   // TODO: add description of PPC stack frame format, or at least some docs.
2357   //
2358   MachineFunction &MF = DAG.getMachineFunction();
2359   MachineFrameInfo *MFI = MF.getFrameInfo();
2360   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2361
2362   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2363   // Potential tail calls could cause overwriting of argument stack slots.
2364   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2365                        (CallConv == CallingConv::Fast));
2366   unsigned PtrByteSize = 8;
2367
2368   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2369   // Area that is at least reserved in caller of this function.
2370   unsigned MinReservedArea = ArgOffset;
2371
2372   static const uint16_t GPR[] = {
2373     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2374     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2375   };
2376
2377   static const uint16_t *FPR = GetFPR();
2378
2379   static const uint16_t VR[] = {
2380     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2381     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2382   };
2383
2384   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2385   const unsigned Num_FPR_Regs = 13;
2386   const unsigned Num_VR_Regs  = array_lengthof(VR);
2387
2388   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2389
2390   // Add DAG nodes to load the arguments or copy them out of registers.  On
2391   // entry to a function on PPC, the arguments start after the linkage area,
2392   // although the first ones are often in registers.
2393
2394   SmallVector<SDValue, 8> MemOps;
2395   unsigned nAltivecParamsAtEnd = 0;
2396   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2397   unsigned CurArgIdx = 0;
2398   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2399     SDValue ArgVal;
2400     bool needsLoad = false;
2401     EVT ObjectVT = Ins[ArgNo].VT;
2402     unsigned ObjSize = ObjectVT.getStoreSize();
2403     unsigned ArgSize = ObjSize;
2404     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2405     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2406     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2407
2408     unsigned CurArgOffset = ArgOffset;
2409
2410     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2411     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2412         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8 ||
2413         ObjectVT==MVT::v2f64 || ObjectVT==MVT::v2i64) {
2414       if (isVarArg) {
2415         MinReservedArea = ((MinReservedArea+15)/16)*16;
2416         MinReservedArea += CalculateStackSlotSize(ObjectVT,
2417                                                   Flags,
2418                                                   PtrByteSize);
2419       } else
2420         nAltivecParamsAtEnd++;
2421     } else
2422       // Calculate min reserved area.
2423       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2424                                                 Flags,
2425                                                 PtrByteSize);
2426
2427     // FIXME the codegen can be much improved in some cases.
2428     // We do not have to keep everything in memory.
2429     if (Flags.isByVal()) {
2430       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2431       ObjSize = Flags.getByValSize();
2432       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2433       // Empty aggregate parameters do not take up registers.  Examples:
2434       //   struct { } a;
2435       //   union  { } b;
2436       //   int c[0];
2437       // etc.  However, we have to provide a place-holder in InVals, so
2438       // pretend we have an 8-byte item at the current address for that
2439       // purpose.
2440       if (!ObjSize) {
2441         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2442         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2443         InVals.push_back(FIN);
2444         continue;
2445       }
2446
2447       unsigned BVAlign = Flags.getByValAlign();
2448       if (BVAlign > 8) {
2449         ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
2450         CurArgOffset = ArgOffset;
2451       }
2452
2453       // All aggregates smaller than 8 bytes must be passed right-justified.
2454       if (ObjSize < PtrByteSize)
2455         CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2456       // The value of the object is its address.
2457       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2458       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2459       InVals.push_back(FIN);
2460
2461       if (ObjSize < 8) {
2462         if (GPR_idx != Num_GPR_Regs) {
2463           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2464           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2465           SDValue Store;
2466
2467           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2468             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2469                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2470             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2471                                       MachinePointerInfo(FuncArg),
2472                                       ObjType, false, false, 0);
2473           } else {
2474             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2475             // store the whole register as-is to the parameter save area
2476             // slot.  The address of the parameter was already calculated
2477             // above (InVals.push_back(FIN)) to be the right-justified
2478             // offset within the slot.  For this store, we need a new
2479             // frame index that points at the beginning of the slot.
2480             int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2481             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2482             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2483                                  MachinePointerInfo(FuncArg),
2484                                  false, false, 0);
2485           }
2486
2487           MemOps.push_back(Store);
2488           ++GPR_idx;
2489         }
2490         // Whether we copied from a register or not, advance the offset
2491         // into the parameter save area by a full doubleword.
2492         ArgOffset += PtrByteSize;
2493         continue;
2494       }
2495
2496       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2497         // Store whatever pieces of the object are in registers
2498         // to memory.  ArgOffset will be the address of the beginning
2499         // of the object.
2500         if (GPR_idx != Num_GPR_Regs) {
2501           unsigned VReg;
2502           VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2503           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2504           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2505           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2506           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2507                                        MachinePointerInfo(FuncArg, j),
2508                                        false, false, 0);
2509           MemOps.push_back(Store);
2510           ++GPR_idx;
2511           ArgOffset += PtrByteSize;
2512         } else {
2513           ArgOffset += ArgSize - j;
2514           break;
2515         }
2516       }
2517       continue;
2518     }
2519
2520     switch (ObjectVT.getSimpleVT().SimpleTy) {
2521     default: llvm_unreachable("Unhandled argument type!");
2522     case MVT::i1:
2523     case MVT::i32:
2524     case MVT::i64:
2525       if (GPR_idx != Num_GPR_Regs) {
2526         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2527         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2528
2529         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2530           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2531           // value to MVT::i64 and then truncate to the correct register size.
2532           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2533
2534         ++GPR_idx;
2535       } else {
2536         needsLoad = true;
2537         ArgSize = PtrByteSize;
2538       }
2539       ArgOffset += 8;
2540       break;
2541
2542     case MVT::f32:
2543     case MVT::f64:
2544       // Every 8 bytes of argument space consumes one of the GPRs available for
2545       // argument passing.
2546       if (GPR_idx != Num_GPR_Regs) {
2547         ++GPR_idx;
2548       }
2549       if (FPR_idx != Num_FPR_Regs) {
2550         unsigned VReg;
2551
2552         if (ObjectVT == MVT::f32)
2553           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2554         else
2555           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2556
2557         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2558         ++FPR_idx;
2559       } else {
2560         needsLoad = true;
2561         ArgSize = PtrByteSize;
2562       }
2563
2564       ArgOffset += 8;
2565       break;
2566     case MVT::v4f32:
2567     case MVT::v4i32:
2568     case MVT::v8i16:
2569     case MVT::v16i8:
2570     case MVT::v2f64:
2571     case MVT::v2i64:
2572       // Note that vector arguments in registers don't reserve stack space,
2573       // except in varargs functions.
2574       if (VR_idx != Num_VR_Regs) {
2575         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2576         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2577         if (isVarArg) {
2578           while ((ArgOffset % 16) != 0) {
2579             ArgOffset += PtrByteSize;
2580             if (GPR_idx != Num_GPR_Regs)
2581               GPR_idx++;
2582           }
2583           ArgOffset += 16;
2584           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2585         }
2586         ++VR_idx;
2587       } else {
2588         // Vectors are aligned.
2589         ArgOffset = ((ArgOffset+15)/16)*16;
2590         CurArgOffset = ArgOffset;
2591         ArgOffset += 16;
2592         needsLoad = true;
2593       }
2594       break;
2595     }
2596
2597     // We need to load the argument to a virtual register if we determined
2598     // above that we ran out of physical registers of the appropriate type.
2599     if (needsLoad) {
2600       int FI = MFI->CreateFixedObject(ObjSize,
2601                                       CurArgOffset + (ArgSize - ObjSize),
2602                                       isImmutable);
2603       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2604       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2605                            false, false, false, 0);
2606     }
2607
2608     InVals.push_back(ArgVal);
2609   }
2610
2611   // Set the size that is at least reserved in caller of this function.  Tail
2612   // call optimized functions' reserved stack space needs to be aligned so that
2613   // taking the difference between two stack areas will result in an aligned
2614   // stack.
2615   setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2616
2617   // If the function takes variable number of arguments, make a frame index for
2618   // the start of the first vararg value... for expansion of llvm.va_start.
2619   if (isVarArg) {
2620     int Depth = ArgOffset;
2621
2622     FuncInfo->setVarArgsFrameIndex(
2623       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2624     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2625
2626     // If this function is vararg, store any remaining integer argument regs
2627     // to their spots on the stack so that they may be loaded by deferencing the
2628     // result of va_next.
2629     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2630       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2631       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2632       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2633                                    MachinePointerInfo(), false, false, 0);
2634       MemOps.push_back(Store);
2635       // Increment the address by four for the next argument to store
2636       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2637       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2638     }
2639   }
2640
2641   if (!MemOps.empty())
2642     Chain = DAG.getNode(ISD::TokenFactor, dl,
2643                         MVT::Other, &MemOps[0], MemOps.size());
2644
2645   return Chain;
2646 }
2647
2648 SDValue
2649 PPCTargetLowering::LowerFormalArguments_Darwin(
2650                                       SDValue Chain,
2651                                       CallingConv::ID CallConv, bool isVarArg,
2652                                       const SmallVectorImpl<ISD::InputArg>
2653                                         &Ins,
2654                                       SDLoc dl, SelectionDAG &DAG,
2655                                       SmallVectorImpl<SDValue> &InVals) const {
2656   // TODO: add description of PPC stack frame format, or at least some docs.
2657   //
2658   MachineFunction &MF = DAG.getMachineFunction();
2659   MachineFrameInfo *MFI = MF.getFrameInfo();
2660   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2661
2662   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2663   bool isPPC64 = PtrVT == MVT::i64;
2664   // Potential tail calls could cause overwriting of argument stack slots.
2665   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2666                        (CallConv == CallingConv::Fast));
2667   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2668
2669   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2670   // Area that is at least reserved in caller of this function.
2671   unsigned MinReservedArea = ArgOffset;
2672
2673   static const uint16_t GPR_32[] = {           // 32-bit registers.
2674     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2675     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2676   };
2677   static const uint16_t GPR_64[] = {           // 64-bit registers.
2678     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2679     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2680   };
2681
2682   static const uint16_t *FPR = GetFPR();
2683
2684   static const uint16_t VR[] = {
2685     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2686     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2687   };
2688
2689   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2690   const unsigned Num_FPR_Regs = 13;
2691   const unsigned Num_VR_Regs  = array_lengthof( VR);
2692
2693   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2694
2695   const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2696
2697   // In 32-bit non-varargs functions, the stack space for vectors is after the
2698   // stack space for non-vectors.  We do not use this space unless we have
2699   // too many vectors to fit in registers, something that only occurs in
2700   // constructed examples:), but we have to walk the arglist to figure
2701   // that out...for the pathological case, compute VecArgOffset as the
2702   // start of the vector parameter area.  Computing VecArgOffset is the
2703   // entire point of the following loop.
2704   unsigned VecArgOffset = ArgOffset;
2705   if (!isVarArg && !isPPC64) {
2706     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2707          ++ArgNo) {
2708       EVT ObjectVT = Ins[ArgNo].VT;
2709       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2710
2711       if (Flags.isByVal()) {
2712         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2713         unsigned ObjSize = Flags.getByValSize();
2714         unsigned ArgSize =
2715                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2716         VecArgOffset += ArgSize;
2717         continue;
2718       }
2719
2720       switch(ObjectVT.getSimpleVT().SimpleTy) {
2721       default: llvm_unreachable("Unhandled argument type!");
2722       case MVT::i1:
2723       case MVT::i32:
2724       case MVT::f32:
2725         VecArgOffset += 4;
2726         break;
2727       case MVT::i64:  // PPC64
2728       case MVT::f64:
2729         // FIXME: We are guaranteed to be !isPPC64 at this point.
2730         // Does MVT::i64 apply?
2731         VecArgOffset += 8;
2732         break;
2733       case MVT::v4f32:
2734       case MVT::v4i32:
2735       case MVT::v8i16:
2736       case MVT::v16i8:
2737         // Nothing to do, we're only looking at Nonvector args here.
2738         break;
2739       }
2740     }
2741   }
2742   // We've found where the vector parameter area in memory is.  Skip the
2743   // first 12 parameters; these don't use that memory.
2744   VecArgOffset = ((VecArgOffset+15)/16)*16;
2745   VecArgOffset += 12*16;
2746
2747   // Add DAG nodes to load the arguments or copy them out of registers.  On
2748   // entry to a function on PPC, the arguments start after the linkage area,
2749   // although the first ones are often in registers.
2750
2751   SmallVector<SDValue, 8> MemOps;
2752   unsigned nAltivecParamsAtEnd = 0;
2753   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2754   unsigned CurArgIdx = 0;
2755   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2756     SDValue ArgVal;
2757     bool needsLoad = false;
2758     EVT ObjectVT = Ins[ArgNo].VT;
2759     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2760     unsigned ArgSize = ObjSize;
2761     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2762     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2763     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2764
2765     unsigned CurArgOffset = ArgOffset;
2766
2767     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2768     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2769         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2770       if (isVarArg || isPPC64) {
2771         MinReservedArea = ((MinReservedArea+15)/16)*16;
2772         MinReservedArea += CalculateStackSlotSize(ObjectVT,
2773                                                   Flags,
2774                                                   PtrByteSize);
2775       } else  nAltivecParamsAtEnd++;
2776     } else
2777       // Calculate min reserved area.
2778       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2779                                                 Flags,
2780                                                 PtrByteSize);
2781
2782     // FIXME the codegen can be much improved in some cases.
2783     // We do not have to keep everything in memory.
2784     if (Flags.isByVal()) {
2785       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2786       ObjSize = Flags.getByValSize();
2787       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2788       // Objects of size 1 and 2 are right justified, everything else is
2789       // left justified.  This means the memory address is adjusted forwards.
2790       if (ObjSize==1 || ObjSize==2) {
2791         CurArgOffset = CurArgOffset + (4 - ObjSize);
2792       }
2793       // The value of the object is its address.
2794       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2795       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2796       InVals.push_back(FIN);
2797       if (ObjSize==1 || ObjSize==2) {
2798         if (GPR_idx != Num_GPR_Regs) {
2799           unsigned VReg;
2800           if (isPPC64)
2801             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2802           else
2803             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2804           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2805           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2806           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2807                                             MachinePointerInfo(FuncArg),
2808                                             ObjType, false, false, 0);
2809           MemOps.push_back(Store);
2810           ++GPR_idx;
2811         }
2812
2813         ArgOffset += PtrByteSize;
2814
2815         continue;
2816       }
2817       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2818         // Store whatever pieces of the object are in registers
2819         // to memory.  ArgOffset will be the address of the beginning
2820         // of the object.
2821         if (GPR_idx != Num_GPR_Regs) {
2822           unsigned VReg;
2823           if (isPPC64)
2824             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2825           else
2826             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2827           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2828           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2829           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2830           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2831                                        MachinePointerInfo(FuncArg, j),
2832                                        false, false, 0);
2833           MemOps.push_back(Store);
2834           ++GPR_idx;
2835           ArgOffset += PtrByteSize;
2836         } else {
2837           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2838           break;
2839         }
2840       }
2841       continue;
2842     }
2843
2844     switch (ObjectVT.getSimpleVT().SimpleTy) {
2845     default: llvm_unreachable("Unhandled argument type!");
2846     case MVT::i1:
2847     case MVT::i32:
2848       if (!isPPC64) {
2849         if (GPR_idx != Num_GPR_Regs) {
2850           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2851           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2852
2853           if (ObjectVT == MVT::i1)
2854             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
2855
2856           ++GPR_idx;
2857         } else {
2858           needsLoad = true;
2859           ArgSize = PtrByteSize;
2860         }
2861         // All int arguments reserve stack space in the Darwin ABI.
2862         ArgOffset += PtrByteSize;
2863         break;
2864       }
2865       // FALLTHROUGH
2866     case MVT::i64:  // PPC64
2867       if (GPR_idx != Num_GPR_Regs) {
2868         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2869         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2870
2871         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2872           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2873           // value to MVT::i64 and then truncate to the correct register size.
2874           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2875
2876         ++GPR_idx;
2877       } else {
2878         needsLoad = true;
2879         ArgSize = PtrByteSize;
2880       }
2881       // All int arguments reserve stack space in the Darwin ABI.
2882       ArgOffset += 8;
2883       break;
2884
2885     case MVT::f32:
2886     case MVT::f64:
2887       // Every 4 bytes of argument space consumes one of the GPRs available for
2888       // argument passing.
2889       if (GPR_idx != Num_GPR_Regs) {
2890         ++GPR_idx;
2891         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2892           ++GPR_idx;
2893       }
2894       if (FPR_idx != Num_FPR_Regs) {
2895         unsigned VReg;
2896
2897         if (ObjectVT == MVT::f32)
2898           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2899         else
2900           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2901
2902         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2903         ++FPR_idx;
2904       } else {
2905         needsLoad = true;
2906       }
2907
2908       // All FP arguments reserve stack space in the Darwin ABI.
2909       ArgOffset += isPPC64 ? 8 : ObjSize;
2910       break;
2911     case MVT::v4f32:
2912     case MVT::v4i32:
2913     case MVT::v8i16:
2914     case MVT::v16i8:
2915       // Note that vector arguments in registers don't reserve stack space,
2916       // except in varargs functions.
2917       if (VR_idx != Num_VR_Regs) {
2918         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2919         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2920         if (isVarArg) {
2921           while ((ArgOffset % 16) != 0) {
2922             ArgOffset += PtrByteSize;
2923             if (GPR_idx != Num_GPR_Regs)
2924               GPR_idx++;
2925           }
2926           ArgOffset += 16;
2927           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2928         }
2929         ++VR_idx;
2930       } else {
2931         if (!isVarArg && !isPPC64) {
2932           // Vectors go after all the nonvectors.
2933           CurArgOffset = VecArgOffset;
2934           VecArgOffset += 16;
2935         } else {
2936           // Vectors are aligned.
2937           ArgOffset = ((ArgOffset+15)/16)*16;
2938           CurArgOffset = ArgOffset;
2939           ArgOffset += 16;
2940         }
2941         needsLoad = true;
2942       }
2943       break;
2944     }
2945
2946     // We need to load the argument to a virtual register if we determined above
2947     // that we ran out of physical registers of the appropriate type.
2948     if (needsLoad) {
2949       int FI = MFI->CreateFixedObject(ObjSize,
2950                                       CurArgOffset + (ArgSize - ObjSize),
2951                                       isImmutable);
2952       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2953       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2954                            false, false, false, 0);
2955     }
2956
2957     InVals.push_back(ArgVal);
2958   }
2959
2960   // Set the size that is at least reserved in caller of this function.  Tail
2961   // call optimized functions' reserved stack space needs to be aligned so that
2962   // taking the difference between two stack areas will result in an aligned
2963   // stack.
2964   setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2965
2966   // If the function takes variable number of arguments, make a frame index for
2967   // the start of the first vararg value... for expansion of llvm.va_start.
2968   if (isVarArg) {
2969     int Depth = ArgOffset;
2970
2971     FuncInfo->setVarArgsFrameIndex(
2972       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2973                              Depth, true));
2974     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2975
2976     // If this function is vararg, store any remaining integer argument regs
2977     // to their spots on the stack so that they may be loaded by deferencing the
2978     // result of va_next.
2979     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2980       unsigned VReg;
2981
2982       if (isPPC64)
2983         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2984       else
2985         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2986
2987       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2988       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2989                                    MachinePointerInfo(), false, false, 0);
2990       MemOps.push_back(Store);
2991       // Increment the address by four for the next argument to store
2992       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2993       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2994     }
2995   }
2996
2997   if (!MemOps.empty())
2998     Chain = DAG.getNode(ISD::TokenFactor, dl,
2999                         MVT::Other, &MemOps[0], MemOps.size());
3000
3001   return Chain;
3002 }
3003
3004 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
3005 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
3006 static unsigned
3007 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
3008                                      bool isPPC64,
3009                                      bool isVarArg,
3010                                      unsigned CC,
3011                                      const SmallVectorImpl<ISD::OutputArg>
3012                                        &Outs,
3013                                      const SmallVectorImpl<SDValue> &OutVals,
3014                                      unsigned &nAltivecParamsAtEnd) {
3015   // Count how many bytes are to be pushed on the stack, including the linkage
3016   // area, and parameter passing area.  We start with 24/48 bytes, which is
3017   // prereserved space for [SP][CR][LR][3 x unused].
3018   unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
3019   unsigned NumOps = Outs.size();
3020   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3021
3022   // Add up all the space actually used.
3023   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
3024   // they all go in registers, but we must reserve stack space for them for
3025   // possible use by the caller.  In varargs or 64-bit calls, parameters are
3026   // assigned stack space in order, with padding so Altivec parameters are
3027   // 16-byte aligned.
3028   nAltivecParamsAtEnd = 0;
3029   for (unsigned i = 0; i != NumOps; ++i) {
3030     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3031     EVT ArgVT = Outs[i].VT;
3032     // Varargs Altivec parameters are padded to a 16 byte boundary.
3033     if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
3034         ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8 ||
3035         ArgVT==MVT::v2f64 || ArgVT==MVT::v2i64) {
3036       if (!isVarArg && !isPPC64) {
3037         // Non-varargs Altivec parameters go after all the non-Altivec
3038         // parameters; handle those later so we know how much padding we need.
3039         nAltivecParamsAtEnd++;
3040         continue;
3041       }
3042       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
3043       NumBytes = ((NumBytes+15)/16)*16;
3044     }
3045     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3046   }
3047
3048    // Allow for Altivec parameters at the end, if needed.
3049   if (nAltivecParamsAtEnd) {
3050     NumBytes = ((NumBytes+15)/16)*16;
3051     NumBytes += 16*nAltivecParamsAtEnd;
3052   }
3053
3054   // The prolog code of the callee may store up to 8 GPR argument registers to
3055   // the stack, allowing va_start to index over them in memory if its varargs.
3056   // Because we cannot tell if this is needed on the caller side, we have to
3057   // conservatively assume that it is needed.  As such, make sure we have at
3058   // least enough stack space for the caller to store the 8 GPRs.
3059   NumBytes = std::max(NumBytes,
3060                       PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
3061
3062   // Tail call needs the stack to be aligned.
3063   if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
3064     unsigned TargetAlign = DAG.getMachineFunction().getTarget().
3065       getFrameLowering()->getStackAlignment();
3066     unsigned AlignMask = TargetAlign-1;
3067     NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3068   }
3069
3070   return NumBytes;
3071 }
3072
3073 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3074 /// adjusted to accommodate the arguments for the tailcall.
3075 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3076                                    unsigned ParamSize) {
3077
3078   if (!isTailCall) return 0;
3079
3080   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3081   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3082   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3083   // Remember only if the new adjustement is bigger.
3084   if (SPDiff < FI->getTailCallSPDelta())
3085     FI->setTailCallSPDelta(SPDiff);
3086
3087   return SPDiff;
3088 }
3089
3090 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3091 /// for tail call optimization. Targets which want to do tail call
3092 /// optimization should implement this function.
3093 bool
3094 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3095                                                      CallingConv::ID CalleeCC,
3096                                                      bool isVarArg,
3097                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3098                                                      SelectionDAG& DAG) const {
3099   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3100     return false;
3101
3102   // Variable argument functions are not supported.
3103   if (isVarArg)
3104     return false;
3105
3106   MachineFunction &MF = DAG.getMachineFunction();
3107   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3108   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3109     // Functions containing by val parameters are not supported.
3110     for (unsigned i = 0; i != Ins.size(); i++) {
3111        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3112        if (Flags.isByVal()) return false;
3113     }
3114
3115     // Non-PIC/GOT tail calls are supported.
3116     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3117       return true;
3118
3119     // At the moment we can only do local tail calls (in same module, hidden
3120     // or protected) if we are generating PIC.
3121     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3122       return G->getGlobal()->hasHiddenVisibility()
3123           || G->getGlobal()->hasProtectedVisibility();
3124   }
3125
3126   return false;
3127 }
3128
3129 /// isCallCompatibleAddress - Return the immediate to use if the specified
3130 /// 32-bit value is representable in the immediate field of a BxA instruction.
3131 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3132   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3133   if (!C) return 0;
3134
3135   int Addr = C->getZExtValue();
3136   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3137       SignExtend32<26>(Addr) != Addr)
3138     return 0;  // Top 6 bits have to be sext of immediate.
3139
3140   return DAG.getConstant((int)C->getZExtValue() >> 2,
3141                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3142 }
3143
3144 namespace {
3145
3146 struct TailCallArgumentInfo {
3147   SDValue Arg;
3148   SDValue FrameIdxOp;
3149   int       FrameIdx;
3150
3151   TailCallArgumentInfo() : FrameIdx(0) {}
3152 };
3153
3154 }
3155
3156 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3157 static void
3158 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3159                                            SDValue Chain,
3160                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3161                    SmallVectorImpl<SDValue> &MemOpChains,
3162                    SDLoc dl) {
3163   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3164     SDValue Arg = TailCallArgs[i].Arg;
3165     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3166     int FI = TailCallArgs[i].FrameIdx;
3167     // Store relative to framepointer.
3168     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3169                                        MachinePointerInfo::getFixedStack(FI),
3170                                        false, false, 0));
3171   }
3172 }
3173
3174 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3175 /// the appropriate stack slot for the tail call optimized function call.
3176 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3177                                                MachineFunction &MF,
3178                                                SDValue Chain,
3179                                                SDValue OldRetAddr,
3180                                                SDValue OldFP,
3181                                                int SPDiff,
3182                                                bool isPPC64,
3183                                                bool isDarwinABI,
3184                                                SDLoc dl) {
3185   if (SPDiff) {
3186     // Calculate the new stack slot for the return address.
3187     int SlotSize = isPPC64 ? 8 : 4;
3188     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3189                                                                    isDarwinABI);
3190     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3191                                                           NewRetAddrLoc, true);
3192     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3193     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3194     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3195                          MachinePointerInfo::getFixedStack(NewRetAddr),
3196                          false, false, 0);
3197
3198     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3199     // slot as the FP is never overwritten.
3200     if (isDarwinABI) {
3201       int NewFPLoc =
3202         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3203       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3204                                                           true);
3205       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3206       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3207                            MachinePointerInfo::getFixedStack(NewFPIdx),
3208                            false, false, 0);
3209     }
3210   }
3211   return Chain;
3212 }
3213
3214 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3215 /// the position of the argument.
3216 static void
3217 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3218                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3219                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3220   int Offset = ArgOffset + SPDiff;
3221   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3222   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3223   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3224   SDValue FIN = DAG.getFrameIndex(FI, VT);
3225   TailCallArgumentInfo Info;
3226   Info.Arg = Arg;
3227   Info.FrameIdxOp = FIN;
3228   Info.FrameIdx = FI;
3229   TailCallArguments.push_back(Info);
3230 }
3231
3232 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3233 /// stack slot. Returns the chain as result and the loaded frame pointers in
3234 /// LROpOut/FPOpout. Used when tail calling.
3235 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3236                                                         int SPDiff,
3237                                                         SDValue Chain,
3238                                                         SDValue &LROpOut,
3239                                                         SDValue &FPOpOut,
3240                                                         bool isDarwinABI,
3241                                                         SDLoc dl) const {
3242   if (SPDiff) {
3243     // Load the LR and FP stack slot for later adjusting.
3244     EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3245     LROpOut = getReturnAddrFrameIndex(DAG);
3246     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3247                           false, false, false, 0);
3248     Chain = SDValue(LROpOut.getNode(), 1);
3249
3250     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3251     // slot as the FP is never overwritten.
3252     if (isDarwinABI) {
3253       FPOpOut = getFramePointerFrameIndex(DAG);
3254       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3255                             false, false, false, 0);
3256       Chain = SDValue(FPOpOut.getNode(), 1);
3257     }
3258   }
3259   return Chain;
3260 }
3261
3262 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3263 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3264 /// specified by the specific parameter attribute. The copy will be passed as
3265 /// a byval function parameter.
3266 /// Sometimes what we are copying is the end of a larger object, the part that
3267 /// does not fit in registers.
3268 static SDValue
3269 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3270                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3271                           SDLoc dl) {
3272   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3273   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3274                        false, false, MachinePointerInfo(0),
3275                        MachinePointerInfo(0));
3276 }
3277
3278 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3279 /// tail calls.
3280 static void
3281 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3282                  SDValue Arg, SDValue PtrOff, int SPDiff,
3283                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3284                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3285                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3286                  SDLoc dl) {
3287   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3288   if (!isTailCall) {
3289     if (isVector) {
3290       SDValue StackPtr;
3291       if (isPPC64)
3292         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3293       else
3294         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3295       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3296                            DAG.getConstant(ArgOffset, PtrVT));
3297     }
3298     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3299                                        MachinePointerInfo(), false, false, 0));
3300   // Calculate and remember argument location.
3301   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3302                                   TailCallArguments);
3303 }
3304
3305 static
3306 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3307                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3308                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3309                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3310   MachineFunction &MF = DAG.getMachineFunction();
3311
3312   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3313   // might overwrite each other in case of tail call optimization.
3314   SmallVector<SDValue, 8> MemOpChains2;
3315   // Do not flag preceding copytoreg stuff together with the following stuff.
3316   InFlag = SDValue();
3317   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3318                                     MemOpChains2, dl);
3319   if (!MemOpChains2.empty())
3320     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3321                         &MemOpChains2[0], MemOpChains2.size());
3322
3323   // Store the return address to the appropriate stack slot.
3324   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3325                                         isPPC64, isDarwinABI, dl);
3326
3327   // Emit callseq_end just before tailcall node.
3328   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3329                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3330   InFlag = Chain.getValue(1);
3331 }
3332
3333 static
3334 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3335                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3336                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3337                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3338                      const PPCSubtarget &PPCSubTarget) {
3339
3340   bool isPPC64 = PPCSubTarget.isPPC64();
3341   bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3342
3343   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3344   NodeTys.push_back(MVT::Other);   // Returns a chain
3345   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3346
3347   unsigned CallOpc = PPCISD::CALL;
3348
3349   bool needIndirectCall = true;
3350   if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3351     // If this is an absolute destination address, use the munged value.
3352     Callee = SDValue(Dest, 0);
3353     needIndirectCall = false;
3354   }
3355
3356   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3357     // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3358     // Use indirect calls for ALL functions calls in JIT mode, since the
3359     // far-call stubs may be outside relocation limits for a BL instruction.
3360     if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3361       unsigned OpFlags = 0;
3362       if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3363           (PPCSubTarget.getTargetTriple().isMacOSX() &&
3364            PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3365           (G->getGlobal()->isDeclaration() ||
3366            G->getGlobal()->isWeakForLinker())) {
3367         // PC-relative references to external symbols should go through $stub,
3368         // unless we're building with the leopard linker or later, which
3369         // automatically synthesizes these stubs.
3370         OpFlags = PPCII::MO_DARWIN_STUB;
3371       }
3372
3373       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3374       // every direct call is) turn it into a TargetGlobalAddress /
3375       // TargetExternalSymbol node so that legalize doesn't hack it.
3376       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3377                                           Callee.getValueType(),
3378                                           0, OpFlags);
3379       needIndirectCall = false;
3380     }
3381   }
3382
3383   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3384     unsigned char OpFlags = 0;
3385
3386     if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3387         (PPCSubTarget.getTargetTriple().isMacOSX() &&
3388          PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3389       // PC-relative references to external symbols should go through $stub,
3390       // unless we're building with the leopard linker or later, which
3391       // automatically synthesizes these stubs.
3392       OpFlags = PPCII::MO_DARWIN_STUB;
3393     }
3394
3395     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3396                                          OpFlags);
3397     needIndirectCall = false;
3398   }
3399
3400   if (needIndirectCall) {
3401     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3402     // to do the call, we can't use PPCISD::CALL.
3403     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3404
3405     if (isSVR4ABI && isPPC64) {
3406       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3407       // entry point, but to the function descriptor (the function entry point
3408       // address is part of the function descriptor though).
3409       // The function descriptor is a three doubleword structure with the
3410       // following fields: function entry point, TOC base address and
3411       // environment pointer.
3412       // Thus for a call through a function pointer, the following actions need
3413       // to be performed:
3414       //   1. Save the TOC of the caller in the TOC save area of its stack
3415       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3416       //   2. Load the address of the function entry point from the function
3417       //      descriptor.
3418       //   3. Load the TOC of the callee from the function descriptor into r2.
3419       //   4. Load the environment pointer from the function descriptor into
3420       //      r11.
3421       //   5. Branch to the function entry point address.
3422       //   6. On return of the callee, the TOC of the caller needs to be
3423       //      restored (this is done in FinishCall()).
3424       //
3425       // All those operations are flagged together to ensure that no other
3426       // operations can be scheduled in between. E.g. without flagging the
3427       // operations together, a TOC access in the caller could be scheduled
3428       // between the load of the callee TOC and the branch to the callee, which
3429       // results in the TOC access going through the TOC of the callee instead
3430       // of going through the TOC of the caller, which leads to incorrect code.
3431
3432       // Load the address of the function entry point from the function
3433       // descriptor.
3434       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3435       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3436                                         InFlag.getNode() ? 3 : 2);
3437       Chain = LoadFuncPtr.getValue(1);
3438       InFlag = LoadFuncPtr.getValue(2);
3439
3440       // Load environment pointer into r11.
3441       // Offset of the environment pointer within the function descriptor.
3442       SDValue PtrOff = DAG.getIntPtrConstant(16);
3443
3444       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3445       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3446                                        InFlag);
3447       Chain = LoadEnvPtr.getValue(1);
3448       InFlag = LoadEnvPtr.getValue(2);
3449
3450       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3451                                         InFlag);
3452       Chain = EnvVal.getValue(0);
3453       InFlag = EnvVal.getValue(1);
3454
3455       // Load TOC of the callee into r2. We are using a target-specific load
3456       // with r2 hard coded, because the result of a target-independent load
3457       // would never go directly into r2, since r2 is a reserved register (which
3458       // prevents the register allocator from allocating it), resulting in an
3459       // additional register being allocated and an unnecessary move instruction
3460       // being generated.
3461       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3462       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3463                                        Callee, InFlag);
3464       Chain = LoadTOCPtr.getValue(0);
3465       InFlag = LoadTOCPtr.getValue(1);
3466
3467       MTCTROps[0] = Chain;
3468       MTCTROps[1] = LoadFuncPtr;
3469       MTCTROps[2] = InFlag;
3470     }
3471
3472     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3473                         2 + (InFlag.getNode() != 0));
3474     InFlag = Chain.getValue(1);
3475
3476     NodeTys.clear();
3477     NodeTys.push_back(MVT::Other);
3478     NodeTys.push_back(MVT::Glue);
3479     Ops.push_back(Chain);
3480     CallOpc = PPCISD::BCTRL;
3481     Callee.setNode(0);
3482     // Add use of X11 (holding environment pointer)
3483     if (isSVR4ABI && isPPC64)
3484       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3485     // Add CTR register as callee so a bctr can be emitted later.
3486     if (isTailCall)
3487       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3488   }
3489
3490   // If this is a direct call, pass the chain and the callee.
3491   if (Callee.getNode()) {
3492     Ops.push_back(Chain);
3493     Ops.push_back(Callee);
3494   }
3495   // If this is a tail call add stack pointer delta.
3496   if (isTailCall)
3497     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3498
3499   // Add argument registers to the end of the list so that they are known live
3500   // into the call.
3501   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3502     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3503                                   RegsToPass[i].second.getValueType()));
3504
3505   return CallOpc;
3506 }
3507
3508 static
3509 bool isLocalCall(const SDValue &Callee)
3510 {
3511   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3512     return !G->getGlobal()->isDeclaration() &&
3513            !G->getGlobal()->isWeakForLinker();
3514   return false;
3515 }
3516
3517 SDValue
3518 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3519                                    CallingConv::ID CallConv, bool isVarArg,
3520                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3521                                    SDLoc dl, SelectionDAG &DAG,
3522                                    SmallVectorImpl<SDValue> &InVals) const {
3523
3524   SmallVector<CCValAssign, 16> RVLocs;
3525   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3526                     getTargetMachine(), RVLocs, *DAG.getContext());
3527   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3528
3529   // Copy all of the result registers out of their specified physreg.
3530   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3531     CCValAssign &VA = RVLocs[i];
3532     assert(VA.isRegLoc() && "Can only return in registers!");
3533
3534     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3535                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3536     Chain = Val.getValue(1);
3537     InFlag = Val.getValue(2);
3538
3539     switch (VA.getLocInfo()) {
3540     default: llvm_unreachable("Unknown loc info!");
3541     case CCValAssign::Full: break;
3542     case CCValAssign::AExt:
3543       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3544       break;
3545     case CCValAssign::ZExt:
3546       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3547                         DAG.getValueType(VA.getValVT()));
3548       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3549       break;
3550     case CCValAssign::SExt:
3551       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3552                         DAG.getValueType(VA.getValVT()));
3553       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3554       break;
3555     }
3556
3557     InVals.push_back(Val);
3558   }
3559
3560   return Chain;
3561 }
3562
3563 SDValue
3564 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3565                               bool isTailCall, bool isVarArg,
3566                               SelectionDAG &DAG,
3567                               SmallVector<std::pair<unsigned, SDValue>, 8>
3568                                 &RegsToPass,
3569                               SDValue InFlag, SDValue Chain,
3570                               SDValue &Callee,
3571                               int SPDiff, unsigned NumBytes,
3572                               const SmallVectorImpl<ISD::InputArg> &Ins,
3573                               SmallVectorImpl<SDValue> &InVals) const {
3574   std::vector<EVT> NodeTys;
3575   SmallVector<SDValue, 8> Ops;
3576   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3577                                  isTailCall, RegsToPass, Ops, NodeTys,
3578                                  PPCSubTarget);
3579
3580   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3581   if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3582     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3583
3584   // When performing tail call optimization the callee pops its arguments off
3585   // the stack. Account for this here so these bytes can be pushed back on in
3586   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3587   int BytesCalleePops =
3588     (CallConv == CallingConv::Fast &&
3589      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3590
3591   // Add a register mask operand representing the call-preserved registers.
3592   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3593   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3594   assert(Mask && "Missing call preserved mask for calling convention");
3595   Ops.push_back(DAG.getRegisterMask(Mask));
3596
3597   if (InFlag.getNode())
3598     Ops.push_back(InFlag);
3599
3600   // Emit tail call.
3601   if (isTailCall) {
3602     assert(((Callee.getOpcode() == ISD::Register &&
3603              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3604             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3605             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3606             isa<ConstantSDNode>(Callee)) &&
3607     "Expecting an global address, external symbol, absolute value or register");
3608
3609     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3610   }
3611
3612   // Add a NOP immediately after the branch instruction when using the 64-bit
3613   // SVR4 ABI. At link time, if caller and callee are in a different module and
3614   // thus have a different TOC, the call will be replaced with a call to a stub
3615   // function which saves the current TOC, loads the TOC of the callee and
3616   // branches to the callee. The NOP will be replaced with a load instruction
3617   // which restores the TOC of the caller from the TOC save slot of the current
3618   // stack frame. If caller and callee belong to the same module (and have the
3619   // same TOC), the NOP will remain unchanged.
3620
3621   bool needsTOCRestore = false;
3622   if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3623     if (CallOpc == PPCISD::BCTRL) {
3624       // This is a call through a function pointer.
3625       // Restore the caller TOC from the save area into R2.
3626       // See PrepareCall() for more information about calls through function
3627       // pointers in the 64-bit SVR4 ABI.
3628       // We are using a target-specific load with r2 hard coded, because the
3629       // result of a target-independent load would never go directly into r2,
3630       // since r2 is a reserved register (which prevents the register allocator
3631       // from allocating it), resulting in an additional register being
3632       // allocated and an unnecessary move instruction being generated.
3633       needsTOCRestore = true;
3634     } else if ((CallOpc == PPCISD::CALL) &&
3635                (!isLocalCall(Callee) ||
3636                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3637       // Otherwise insert NOP for non-local calls.
3638       CallOpc = PPCISD::CALL_NOP;
3639     }
3640   }
3641
3642   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3643   InFlag = Chain.getValue(1);
3644
3645   if (needsTOCRestore) {
3646     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3647     Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3648     InFlag = Chain.getValue(1);
3649   }
3650
3651   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3652                              DAG.getIntPtrConstant(BytesCalleePops, true),
3653                              InFlag, dl);
3654   if (!Ins.empty())
3655     InFlag = Chain.getValue(1);
3656
3657   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3658                          Ins, dl, DAG, InVals);
3659 }
3660
3661 SDValue
3662 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3663                              SmallVectorImpl<SDValue> &InVals) const {
3664   SelectionDAG &DAG                     = CLI.DAG;
3665   SDLoc &dl                             = CLI.DL;
3666   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3667   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3668   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3669   SDValue Chain                         = CLI.Chain;
3670   SDValue Callee                        = CLI.Callee;
3671   bool &isTailCall                      = CLI.IsTailCall;
3672   CallingConv::ID CallConv              = CLI.CallConv;
3673   bool isVarArg                         = CLI.IsVarArg;
3674
3675   if (isTailCall)
3676     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3677                                                    Ins, DAG);
3678
3679   if (PPCSubTarget.isSVR4ABI()) {
3680     if (PPCSubTarget.isPPC64())
3681       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3682                               isTailCall, Outs, OutVals, Ins,
3683                               dl, DAG, InVals);
3684     else
3685       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3686                               isTailCall, Outs, OutVals, Ins,
3687                               dl, DAG, InVals);
3688   }
3689
3690   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3691                           isTailCall, Outs, OutVals, Ins,
3692                           dl, DAG, InVals);
3693 }
3694
3695 SDValue
3696 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3697                                     CallingConv::ID CallConv, bool isVarArg,
3698                                     bool isTailCall,
3699                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3700                                     const SmallVectorImpl<SDValue> &OutVals,
3701                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3702                                     SDLoc dl, SelectionDAG &DAG,
3703                                     SmallVectorImpl<SDValue> &InVals) const {
3704   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3705   // of the 32-bit SVR4 ABI stack frame layout.
3706
3707   assert((CallConv == CallingConv::C ||
3708           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3709
3710   unsigned PtrByteSize = 4;
3711
3712   MachineFunction &MF = DAG.getMachineFunction();
3713
3714   // Mark this function as potentially containing a function that contains a
3715   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3716   // and restoring the callers stack pointer in this functions epilog. This is
3717   // done because by tail calling the called function might overwrite the value
3718   // in this function's (MF) stack pointer stack slot 0(SP).
3719   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3720       CallConv == CallingConv::Fast)
3721     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3722
3723   // Count how many bytes are to be pushed on the stack, including the linkage
3724   // area, parameter list area and the part of the local variable space which
3725   // contains copies of aggregates which are passed by value.
3726
3727   // Assign locations to all of the outgoing arguments.
3728   SmallVector<CCValAssign, 16> ArgLocs;
3729   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3730                  getTargetMachine(), ArgLocs, *DAG.getContext());
3731
3732   // Reserve space for the linkage area on the stack.
3733   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3734
3735   if (isVarArg) {
3736     // Handle fixed and variable vector arguments differently.
3737     // Fixed vector arguments go into registers as long as registers are
3738     // available. Variable vector arguments always go into memory.
3739     unsigned NumArgs = Outs.size();
3740
3741     for (unsigned i = 0; i != NumArgs; ++i) {
3742       MVT ArgVT = Outs[i].VT;
3743       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3744       bool Result;
3745
3746       if (Outs[i].IsFixed) {
3747         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3748                                CCInfo);
3749       } else {
3750         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3751                                       ArgFlags, CCInfo);
3752       }
3753
3754       if (Result) {
3755 #ifndef NDEBUG
3756         errs() << "Call operand #" << i << " has unhandled type "
3757              << EVT(ArgVT).getEVTString() << "\n";
3758 #endif
3759         llvm_unreachable(0);
3760       }
3761     }
3762   } else {
3763     // All arguments are treated the same.
3764     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3765   }
3766
3767   // Assign locations to all of the outgoing aggregate by value arguments.
3768   SmallVector<CCValAssign, 16> ByValArgLocs;
3769   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3770                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
3771
3772   // Reserve stack space for the allocations in CCInfo.
3773   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3774
3775   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3776
3777   // Size of the linkage area, parameter list area and the part of the local
3778   // space variable where copies of aggregates which are passed by value are
3779   // stored.
3780   unsigned NumBytes = CCByValInfo.getNextStackOffset();
3781
3782   // Calculate by how many bytes the stack has to be adjusted in case of tail
3783   // call optimization.
3784   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3785
3786   // Adjust the stack pointer for the new arguments...
3787   // These operations are automatically eliminated by the prolog/epilog pass
3788   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3789                                dl);
3790   SDValue CallSeqStart = Chain;
3791
3792   // Load the return address and frame pointer so it can be moved somewhere else
3793   // later.
3794   SDValue LROp, FPOp;
3795   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3796                                        dl);
3797
3798   // Set up a copy of the stack pointer for use loading and storing any
3799   // arguments that may not fit in the registers available for argument
3800   // passing.
3801   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3802
3803   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3804   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3805   SmallVector<SDValue, 8> MemOpChains;
3806
3807   bool seenFloatArg = false;
3808   // Walk the register/memloc assignments, inserting copies/loads.
3809   for (unsigned i = 0, j = 0, e = ArgLocs.size();
3810        i != e;
3811        ++i) {
3812     CCValAssign &VA = ArgLocs[i];
3813     SDValue Arg = OutVals[i];
3814     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3815
3816     if (Flags.isByVal()) {
3817       // Argument is an aggregate which is passed by value, thus we need to
3818       // create a copy of it in the local variable space of the current stack
3819       // frame (which is the stack frame of the caller) and pass the address of
3820       // this copy to the callee.
3821       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3822       CCValAssign &ByValVA = ByValArgLocs[j++];
3823       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3824
3825       // Memory reserved in the local variable space of the callers stack frame.
3826       unsigned LocMemOffset = ByValVA.getLocMemOffset();
3827
3828       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3829       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3830
3831       // Create a copy of the argument in the local area of the current
3832       // stack frame.
3833       SDValue MemcpyCall =
3834         CreateCopyOfByValArgument(Arg, PtrOff,
3835                                   CallSeqStart.getNode()->getOperand(0),
3836                                   Flags, DAG, dl);
3837
3838       // This must go outside the CALLSEQ_START..END.
3839       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3840                            CallSeqStart.getNode()->getOperand(1),
3841                            SDLoc(MemcpyCall));
3842       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3843                              NewCallSeqStart.getNode());
3844       Chain = CallSeqStart = NewCallSeqStart;
3845
3846       // Pass the address of the aggregate copy on the stack either in a
3847       // physical register or in the parameter list area of the current stack
3848       // frame to the callee.
3849       Arg = PtrOff;
3850     }
3851
3852     if (VA.isRegLoc()) {
3853       if (Arg.getValueType() == MVT::i1)
3854         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3855
3856       seenFloatArg |= VA.getLocVT().isFloatingPoint();
3857       // Put argument in a physical register.
3858       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3859     } else {
3860       // Put argument in the parameter list area of the current stack frame.
3861       assert(VA.isMemLoc());
3862       unsigned LocMemOffset = VA.getLocMemOffset();
3863
3864       if (!isTailCall) {
3865         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3866         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3867
3868         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3869                                            MachinePointerInfo(),
3870                                            false, false, 0));
3871       } else {
3872         // Calculate and remember argument location.
3873         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3874                                  TailCallArguments);
3875       }
3876     }
3877   }
3878
3879   if (!MemOpChains.empty())
3880     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3881                         &MemOpChains[0], MemOpChains.size());
3882
3883   // Build a sequence of copy-to-reg nodes chained together with token chain
3884   // and flag operands which copy the outgoing args into the appropriate regs.
3885   SDValue InFlag;
3886   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3887     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3888                              RegsToPass[i].second, InFlag);
3889     InFlag = Chain.getValue(1);
3890   }
3891
3892   // Set CR bit 6 to true if this is a vararg call with floating args passed in
3893   // registers.
3894   if (isVarArg) {
3895     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3896     SDValue Ops[] = { Chain, InFlag };
3897
3898     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3899                         dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3900
3901     InFlag = Chain.getValue(1);
3902   }
3903
3904   if (isTailCall)
3905     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3906                     false, TailCallArguments);
3907
3908   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3909                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3910                     Ins, InVals);
3911 }
3912
3913 // Copy an argument into memory, being careful to do this outside the
3914 // call sequence for the call to which the argument belongs.
3915 SDValue
3916 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3917                                               SDValue CallSeqStart,
3918                                               ISD::ArgFlagsTy Flags,
3919                                               SelectionDAG &DAG,
3920                                               SDLoc dl) const {
3921   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3922                         CallSeqStart.getNode()->getOperand(0),
3923                         Flags, DAG, dl);
3924   // The MEMCPY must go outside the CALLSEQ_START..END.
3925   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3926                              CallSeqStart.getNode()->getOperand(1),
3927                              SDLoc(MemcpyCall));
3928   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3929                          NewCallSeqStart.getNode());
3930   return NewCallSeqStart;
3931 }
3932
3933 SDValue
3934 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3935                                     CallingConv::ID CallConv, bool isVarArg,
3936                                     bool isTailCall,
3937                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3938                                     const SmallVectorImpl<SDValue> &OutVals,
3939                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3940                                     SDLoc dl, SelectionDAG &DAG,
3941                                     SmallVectorImpl<SDValue> &InVals) const {
3942
3943   unsigned NumOps = Outs.size();
3944
3945   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3946   unsigned PtrByteSize = 8;
3947
3948   MachineFunction &MF = DAG.getMachineFunction();
3949
3950   // Mark this function as potentially containing a function that contains a
3951   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3952   // and restoring the callers stack pointer in this functions epilog. This is
3953   // done because by tail calling the called function might overwrite the value
3954   // in this function's (MF) stack pointer stack slot 0(SP).
3955   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3956       CallConv == CallingConv::Fast)
3957     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3958
3959   unsigned nAltivecParamsAtEnd = 0;
3960
3961   // Count how many bytes are to be pushed on the stack, including the linkage
3962   // area, and parameter passing area.  We start with at least 48 bytes, which
3963   // is reserved space for [SP][CR][LR][3 x unused].
3964   // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3965   // of this call.
3966   unsigned NumBytes =
3967     CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3968                                          Outs, OutVals, nAltivecParamsAtEnd);
3969
3970   // Calculate by how many bytes the stack has to be adjusted in case of tail
3971   // call optimization.
3972   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3973
3974   // To protect arguments on the stack from being clobbered in a tail call,
3975   // force all the loads to happen before doing any other lowering.
3976   if (isTailCall)
3977     Chain = DAG.getStackArgumentTokenFactor(Chain);
3978
3979   // Adjust the stack pointer for the new arguments...
3980   // These operations are automatically eliminated by the prolog/epilog pass
3981   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3982                                dl);
3983   SDValue CallSeqStart = Chain;
3984
3985   // Load the return address and frame pointer so it can be move somewhere else
3986   // later.
3987   SDValue LROp, FPOp;
3988   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3989                                        dl);
3990
3991   // Set up a copy of the stack pointer for use loading and storing any
3992   // arguments that may not fit in the registers available for argument
3993   // passing.
3994   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3995
3996   // Figure out which arguments are going to go in registers, and which in
3997   // memory.  Also, if this is a vararg function, floating point operations
3998   // must be stored to our stack, and loaded into integer regs as well, if
3999   // any integer regs are available for argument passing.
4000   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
4001   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4002
4003   static const uint16_t GPR[] = {
4004     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4005     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4006   };
4007   static const uint16_t *FPR = GetFPR();
4008
4009   static const uint16_t VR[] = {
4010     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4011     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4012   };
4013   const unsigned NumGPRs = array_lengthof(GPR);
4014   const unsigned NumFPRs = 13;
4015   const unsigned NumVRs  = array_lengthof(VR);
4016
4017   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4018   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4019
4020   SmallVector<SDValue, 8> MemOpChains;
4021   for (unsigned i = 0; i != NumOps; ++i) {
4022     SDValue Arg = OutVals[i];
4023     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4024
4025     // PtrOff will be used to store the current argument to the stack if a
4026     // register cannot be found for it.
4027     SDValue PtrOff;
4028
4029     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4030
4031     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4032
4033     // Promote integers to 64-bit values.
4034     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4035       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4036       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4037       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4038     }
4039
4040     // FIXME memcpy is used way more than necessary.  Correctness first.
4041     // Note: "by value" is code for passing a structure by value, not
4042     // basic types.
4043     if (Flags.isByVal()) {
4044       // Note: Size includes alignment padding, so
4045       //   struct x { short a; char b; }
4046       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4047       // These are the proper values we need for right-justifying the
4048       // aggregate in a parameter register.
4049       unsigned Size = Flags.getByValSize();
4050
4051       // An empty aggregate parameter takes up no storage and no
4052       // registers.
4053       if (Size == 0)
4054         continue;
4055
4056       unsigned BVAlign = Flags.getByValAlign();
4057       if (BVAlign > 8) {
4058         if (BVAlign % PtrByteSize != 0)
4059           llvm_unreachable(
4060             "ByVal alignment is not a multiple of the pointer size");
4061
4062         ArgOffset = ((ArgOffset+BVAlign-1)/BVAlign)*BVAlign;
4063       }
4064
4065       // All aggregates smaller than 8 bytes must be passed right-justified.
4066       if (Size==1 || Size==2 || Size==4) {
4067         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4068         if (GPR_idx != NumGPRs) {
4069           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4070                                         MachinePointerInfo(), VT,
4071                                         false, false, 0);
4072           MemOpChains.push_back(Load.getValue(1));
4073           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4074
4075           ArgOffset += PtrByteSize;
4076           continue;
4077         }
4078       }
4079
4080       if (GPR_idx == NumGPRs && Size < 8) {
4081         SDValue Const = DAG.getConstant(PtrByteSize - Size,
4082                                         PtrOff.getValueType());
4083         SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4084         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4085                                                           CallSeqStart,
4086                                                           Flags, DAG, dl);
4087         ArgOffset += PtrByteSize;
4088         continue;
4089       }
4090       // Copy entire object into memory.  There are cases where gcc-generated
4091       // code assumes it is there, even if it could be put entirely into
4092       // registers.  (This is not what the doc says.)
4093
4094       // FIXME: The above statement is likely due to a misunderstanding of the
4095       // documents.  All arguments must be copied into the parameter area BY
4096       // THE CALLEE in the event that the callee takes the address of any
4097       // formal argument.  That has not yet been implemented.  However, it is
4098       // reasonable to use the stack area as a staging area for the register
4099       // load.
4100
4101       // Skip this for small aggregates, as we will use the same slot for a
4102       // right-justified copy, below.
4103       if (Size >= 8)
4104         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4105                                                           CallSeqStart,
4106                                                           Flags, DAG, dl);
4107
4108       // When a register is available, pass a small aggregate right-justified.
4109       if (Size < 8 && GPR_idx != NumGPRs) {
4110         // The easiest way to get this right-justified in a register
4111         // is to copy the structure into the rightmost portion of a
4112         // local variable slot, then load the whole slot into the
4113         // register.
4114         // FIXME: The memcpy seems to produce pretty awful code for
4115         // small aggregates, particularly for packed ones.
4116         // FIXME: It would be preferable to use the slot in the
4117         // parameter save area instead of a new local variable.
4118         SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4119         SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4120         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4121                                                           CallSeqStart,
4122                                                           Flags, DAG, dl);
4123
4124         // Load the slot into the register.
4125         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4126                                    MachinePointerInfo(),
4127                                    false, false, false, 0);
4128         MemOpChains.push_back(Load.getValue(1));
4129         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4130
4131         // Done with this argument.
4132         ArgOffset += PtrByteSize;
4133         continue;
4134       }
4135
4136       // For aggregates larger than PtrByteSize, copy the pieces of the
4137       // object that fit into registers from the parameter save area.
4138       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4139         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4140         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4141         if (GPR_idx != NumGPRs) {
4142           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4143                                      MachinePointerInfo(),
4144                                      false, false, false, 0);
4145           MemOpChains.push_back(Load.getValue(1));
4146           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4147           ArgOffset += PtrByteSize;
4148         } else {
4149           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4150           break;
4151         }
4152       }
4153       continue;
4154     }
4155
4156     switch (Arg.getSimpleValueType().SimpleTy) {
4157     default: llvm_unreachable("Unexpected ValueType for argument!");
4158     case MVT::i1:
4159     case MVT::i32:
4160     case MVT::i64:
4161       if (GPR_idx != NumGPRs) {
4162         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4163       } else {
4164         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4165                          true, isTailCall, false, MemOpChains,
4166                          TailCallArguments, dl);
4167       }
4168       ArgOffset += PtrByteSize;
4169       break;
4170     case MVT::f32:
4171     case MVT::f64:
4172       if (FPR_idx != NumFPRs) {
4173         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4174
4175         if (isVarArg) {
4176           // A single float or an aggregate containing only a single float
4177           // must be passed right-justified in the stack doubleword, and
4178           // in the GPR, if one is available.
4179           SDValue StoreOff;
4180           if (Arg.getSimpleValueType().SimpleTy == MVT::f32) {
4181             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4182             StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4183           } else
4184             StoreOff = PtrOff;
4185
4186           SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4187                                        MachinePointerInfo(), false, false, 0);
4188           MemOpChains.push_back(Store);
4189
4190           // Float varargs are always shadowed in available integer registers
4191           if (GPR_idx != NumGPRs) {
4192             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4193                                        MachinePointerInfo(), false, false,
4194                                        false, 0);
4195             MemOpChains.push_back(Load.getValue(1));
4196             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4197           }
4198         } else if (GPR_idx != NumGPRs)
4199           // If we have any FPRs remaining, we may also have GPRs remaining.
4200           ++GPR_idx;
4201       } else {
4202         // Single-precision floating-point values are mapped to the
4203         // second (rightmost) word of the stack doubleword.
4204         if (Arg.getValueType() == MVT::f32) {
4205           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4206           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4207         }
4208
4209         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4210                          true, isTailCall, false, MemOpChains,
4211                          TailCallArguments, dl);
4212       }
4213       ArgOffset += 8;
4214       break;
4215     case MVT::v4f32:
4216     case MVT::v4i32:
4217     case MVT::v8i16:
4218     case MVT::v16i8:
4219     case MVT::v2f64:
4220     case MVT::v2i64:
4221       if (isVarArg) {
4222         // These go aligned on the stack, or in the corresponding R registers
4223         // when within range.  The Darwin PPC ABI doc claims they also go in
4224         // V registers; in fact gcc does this only for arguments that are
4225         // prototyped, not for those that match the ...  We do it for all
4226         // arguments, seems to work.
4227         while (ArgOffset % 16 !=0) {
4228           ArgOffset += PtrByteSize;
4229           if (GPR_idx != NumGPRs)
4230             GPR_idx++;
4231         }
4232         // We could elide this store in the case where the object fits
4233         // entirely in R registers.  Maybe later.
4234         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4235                             DAG.getConstant(ArgOffset, PtrVT));
4236         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4237                                      MachinePointerInfo(), false, false, 0);
4238         MemOpChains.push_back(Store);
4239         if (VR_idx != NumVRs) {
4240           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4241                                      MachinePointerInfo(),
4242                                      false, false, false, 0);
4243           MemOpChains.push_back(Load.getValue(1));
4244           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4245         }
4246         ArgOffset += 16;
4247         for (unsigned i=0; i<16; i+=PtrByteSize) {
4248           if (GPR_idx == NumGPRs)
4249             break;
4250           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4251                                   DAG.getConstant(i, PtrVT));
4252           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4253                                      false, false, false, 0);
4254           MemOpChains.push_back(Load.getValue(1));
4255           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4256         }
4257         break;
4258       }
4259
4260       // Non-varargs Altivec params generally go in registers, but have
4261       // stack space allocated at the end.
4262       if (VR_idx != NumVRs) {
4263         // Doesn't have GPR space allocated.
4264         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4265       } else {
4266         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4267                          true, isTailCall, true, MemOpChains,
4268                          TailCallArguments, dl);
4269         ArgOffset += 16;
4270       }
4271       break;
4272     }
4273   }
4274
4275   if (!MemOpChains.empty())
4276     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4277                         &MemOpChains[0], MemOpChains.size());
4278
4279   // Check if this is an indirect call (MTCTR/BCTRL).
4280   // See PrepareCall() for more information about calls through function
4281   // pointers in the 64-bit SVR4 ABI.
4282   if (!isTailCall &&
4283       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4284       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4285       !isBLACompatibleAddress(Callee, DAG)) {
4286     // Load r2 into a virtual register and store it to the TOC save area.
4287     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4288     // TOC save area offset.
4289     SDValue PtrOff = DAG.getIntPtrConstant(40);
4290     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4291     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4292                          false, false, 0);
4293     // R12 must contain the address of an indirect callee.  This does not
4294     // mean the MTCTR instruction must use R12; it's easier to model this
4295     // as an extra parameter, so do that.
4296     RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4297   }
4298
4299   // Build a sequence of copy-to-reg nodes chained together with token chain
4300   // and flag operands which copy the outgoing args into the appropriate regs.
4301   SDValue InFlag;
4302   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4303     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4304                              RegsToPass[i].second, InFlag);
4305     InFlag = Chain.getValue(1);
4306   }
4307
4308   if (isTailCall)
4309     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4310                     FPOp, true, TailCallArguments);
4311
4312   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4313                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4314                     Ins, InVals);
4315 }
4316
4317 SDValue
4318 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4319                                     CallingConv::ID CallConv, bool isVarArg,
4320                                     bool isTailCall,
4321                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4322                                     const SmallVectorImpl<SDValue> &OutVals,
4323                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4324                                     SDLoc dl, SelectionDAG &DAG,
4325                                     SmallVectorImpl<SDValue> &InVals) const {
4326
4327   unsigned NumOps = Outs.size();
4328
4329   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4330   bool isPPC64 = PtrVT == MVT::i64;
4331   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4332
4333   MachineFunction &MF = DAG.getMachineFunction();
4334
4335   // Mark this function as potentially containing a function that contains a
4336   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4337   // and restoring the callers stack pointer in this functions epilog. This is
4338   // done because by tail calling the called function might overwrite the value
4339   // in this function's (MF) stack pointer stack slot 0(SP).
4340   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4341       CallConv == CallingConv::Fast)
4342     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4343
4344   unsigned nAltivecParamsAtEnd = 0;
4345
4346   // Count how many bytes are to be pushed on the stack, including the linkage
4347   // area, and parameter passing area.  We start with 24/48 bytes, which is
4348   // prereserved space for [SP][CR][LR][3 x unused].
4349   unsigned NumBytes =
4350     CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4351                                          Outs, OutVals,
4352                                          nAltivecParamsAtEnd);
4353
4354   // Calculate by how many bytes the stack has to be adjusted in case of tail
4355   // call optimization.
4356   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4357
4358   // To protect arguments on the stack from being clobbered in a tail call,
4359   // force all the loads to happen before doing any other lowering.
4360   if (isTailCall)
4361     Chain = DAG.getStackArgumentTokenFactor(Chain);
4362
4363   // Adjust the stack pointer for the new arguments...
4364   // These operations are automatically eliminated by the prolog/epilog pass
4365   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4366                                dl);
4367   SDValue CallSeqStart = Chain;
4368
4369   // Load the return address and frame pointer so it can be move somewhere else
4370   // later.
4371   SDValue LROp, FPOp;
4372   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4373                                        dl);
4374
4375   // Set up a copy of the stack pointer for use loading and storing any
4376   // arguments that may not fit in the registers available for argument
4377   // passing.
4378   SDValue StackPtr;
4379   if (isPPC64)
4380     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4381   else
4382     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4383
4384   // Figure out which arguments are going to go in registers, and which in
4385   // memory.  Also, if this is a vararg function, floating point operations
4386   // must be stored to our stack, and loaded into integer regs as well, if
4387   // any integer regs are available for argument passing.
4388   unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4389   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4390
4391   static const uint16_t GPR_32[] = {           // 32-bit registers.
4392     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4393     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4394   };
4395   static const uint16_t GPR_64[] = {           // 64-bit registers.
4396     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4397     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4398   };
4399   static const uint16_t *FPR = GetFPR();
4400
4401   static const uint16_t VR[] = {
4402     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4403     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4404   };
4405   const unsigned NumGPRs = array_lengthof(GPR_32);
4406   const unsigned NumFPRs = 13;
4407   const unsigned NumVRs  = array_lengthof(VR);
4408
4409   const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4410
4411   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4412   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4413
4414   SmallVector<SDValue, 8> MemOpChains;
4415   for (unsigned i = 0; i != NumOps; ++i) {
4416     SDValue Arg = OutVals[i];
4417     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4418
4419     // PtrOff will be used to store the current argument to the stack if a
4420     // register cannot be found for it.
4421     SDValue PtrOff;
4422
4423     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4424
4425     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4426
4427     // On PPC64, promote integers to 64-bit values.
4428     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4429       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4430       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4431       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4432     }
4433
4434     // FIXME memcpy is used way more than necessary.  Correctness first.
4435     // Note: "by value" is code for passing a structure by value, not
4436     // basic types.
4437     if (Flags.isByVal()) {
4438       unsigned Size = Flags.getByValSize();
4439       // Very small objects are passed right-justified.  Everything else is
4440       // passed left-justified.
4441       if (Size==1 || Size==2) {
4442         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4443         if (GPR_idx != NumGPRs) {
4444           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4445                                         MachinePointerInfo(), VT,
4446                                         false, false, 0);
4447           MemOpChains.push_back(Load.getValue(1));
4448           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4449
4450           ArgOffset += PtrByteSize;
4451         } else {
4452           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4453                                           PtrOff.getValueType());
4454           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4455           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4456                                                             CallSeqStart,
4457                                                             Flags, DAG, dl);
4458           ArgOffset += PtrByteSize;
4459         }
4460         continue;
4461       }
4462       // Copy entire object into memory.  There are cases where gcc-generated
4463       // code assumes it is there, even if it could be put entirely into
4464       // registers.  (This is not what the doc says.)
4465       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4466                                                         CallSeqStart,
4467                                                         Flags, DAG, dl);
4468
4469       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4470       // copy the pieces of the object that fit into registers from the
4471       // parameter save area.
4472       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4473         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4474         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4475         if (GPR_idx != NumGPRs) {
4476           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4477                                      MachinePointerInfo(),
4478                                      false, false, false, 0);
4479           MemOpChains.push_back(Load.getValue(1));
4480           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4481           ArgOffset += PtrByteSize;
4482         } else {
4483           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4484           break;
4485         }
4486       }
4487       continue;
4488     }
4489
4490     switch (Arg.getSimpleValueType().SimpleTy) {
4491     default: llvm_unreachable("Unexpected ValueType for argument!");
4492     case MVT::i1:
4493     case MVT::i32:
4494     case MVT::i64:
4495       if (GPR_idx != NumGPRs) {
4496         if (Arg.getValueType() == MVT::i1)
4497           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4498
4499         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4500       } else {
4501         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4502                          isPPC64, isTailCall, false, MemOpChains,
4503                          TailCallArguments, dl);
4504       }
4505       ArgOffset += PtrByteSize;
4506       break;
4507     case MVT::f32:
4508     case MVT::f64:
4509       if (FPR_idx != NumFPRs) {
4510         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4511
4512         if (isVarArg) {
4513           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4514                                        MachinePointerInfo(), false, false, 0);
4515           MemOpChains.push_back(Store);
4516
4517           // Float varargs are always shadowed in available integer registers
4518           if (GPR_idx != NumGPRs) {
4519             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4520                                        MachinePointerInfo(), false, false,
4521                                        false, 0);
4522             MemOpChains.push_back(Load.getValue(1));
4523             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4524           }
4525           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4526             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4527             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4528             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4529                                        MachinePointerInfo(),
4530                                        false, false, false, 0);
4531             MemOpChains.push_back(Load.getValue(1));
4532             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4533           }
4534         } else {
4535           // If we have any FPRs remaining, we may also have GPRs remaining.
4536           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4537           // GPRs.
4538           if (GPR_idx != NumGPRs)
4539             ++GPR_idx;
4540           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4541               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4542             ++GPR_idx;
4543         }
4544       } else
4545         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4546                          isPPC64, isTailCall, false, MemOpChains,
4547                          TailCallArguments, dl);
4548       if (isPPC64)
4549         ArgOffset += 8;
4550       else
4551         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4552       break;
4553     case MVT::v4f32:
4554     case MVT::v4i32:
4555     case MVT::v8i16:
4556     case MVT::v16i8:
4557       if (isVarArg) {
4558         // These go aligned on the stack, or in the corresponding R registers
4559         // when within range.  The Darwin PPC ABI doc claims they also go in
4560         // V registers; in fact gcc does this only for arguments that are
4561         // prototyped, not for those that match the ...  We do it for all
4562         // arguments, seems to work.
4563         while (ArgOffset % 16 !=0) {
4564           ArgOffset += PtrByteSize;
4565           if (GPR_idx != NumGPRs)
4566             GPR_idx++;
4567         }
4568         // We could elide this store in the case where the object fits
4569         // entirely in R registers.  Maybe later.
4570         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4571                             DAG.getConstant(ArgOffset, PtrVT));
4572         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4573                                      MachinePointerInfo(), false, false, 0);
4574         MemOpChains.push_back(Store);
4575         if (VR_idx != NumVRs) {
4576           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4577                                      MachinePointerInfo(),
4578                                      false, false, false, 0);
4579           MemOpChains.push_back(Load.getValue(1));
4580           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4581         }
4582         ArgOffset += 16;
4583         for (unsigned i=0; i<16; i+=PtrByteSize) {
4584           if (GPR_idx == NumGPRs)
4585             break;
4586           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4587                                   DAG.getConstant(i, PtrVT));
4588           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4589                                      false, false, false, 0);
4590           MemOpChains.push_back(Load.getValue(1));
4591           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4592         }
4593         break;
4594       }
4595
4596       // Non-varargs Altivec params generally go in registers, but have
4597       // stack space allocated at the end.
4598       if (VR_idx != NumVRs) {
4599         // Doesn't have GPR space allocated.
4600         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4601       } else if (nAltivecParamsAtEnd==0) {
4602         // We are emitting Altivec params in order.
4603         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4604                          isPPC64, isTailCall, true, MemOpChains,
4605                          TailCallArguments, dl);
4606         ArgOffset += 16;
4607       }
4608       break;
4609     }
4610   }
4611   // If all Altivec parameters fit in registers, as they usually do,
4612   // they get stack space following the non-Altivec parameters.  We
4613   // don't track this here because nobody below needs it.
4614   // If there are more Altivec parameters than fit in registers emit
4615   // the stores here.
4616   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4617     unsigned j = 0;
4618     // Offset is aligned; skip 1st 12 params which go in V registers.
4619     ArgOffset = ((ArgOffset+15)/16)*16;
4620     ArgOffset += 12*16;
4621     for (unsigned i = 0; i != NumOps; ++i) {
4622       SDValue Arg = OutVals[i];
4623       EVT ArgType = Outs[i].VT;
4624       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4625           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4626         if (++j > NumVRs) {
4627           SDValue PtrOff;
4628           // We are emitting Altivec params in order.
4629           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4630                            isPPC64, isTailCall, true, MemOpChains,
4631                            TailCallArguments, dl);
4632           ArgOffset += 16;
4633         }
4634       }
4635     }
4636   }
4637
4638   if (!MemOpChains.empty())
4639     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4640                         &MemOpChains[0], MemOpChains.size());
4641
4642   // On Darwin, R12 must contain the address of an indirect callee.  This does
4643   // not mean the MTCTR instruction must use R12; it's easier to model this as
4644   // an extra parameter, so do that.
4645   if (!isTailCall &&
4646       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4647       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4648       !isBLACompatibleAddress(Callee, DAG))
4649     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4650                                                    PPC::R12), Callee));
4651
4652   // Build a sequence of copy-to-reg nodes chained together with token chain
4653   // and flag operands which copy the outgoing args into the appropriate regs.
4654   SDValue InFlag;
4655   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4656     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4657                              RegsToPass[i].second, InFlag);
4658     InFlag = Chain.getValue(1);
4659   }
4660
4661   if (isTailCall)
4662     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4663                     FPOp, true, TailCallArguments);
4664
4665   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4666                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4667                     Ins, InVals);
4668 }
4669
4670 bool
4671 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4672                                   MachineFunction &MF, bool isVarArg,
4673                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
4674                                   LLVMContext &Context) const {
4675   SmallVector<CCValAssign, 16> RVLocs;
4676   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4677                  RVLocs, Context);
4678   return CCInfo.CheckReturn(Outs, RetCC_PPC);
4679 }
4680
4681 SDValue
4682 PPCTargetLowering::LowerReturn(SDValue Chain,
4683                                CallingConv::ID CallConv, bool isVarArg,
4684                                const SmallVectorImpl<ISD::OutputArg> &Outs,
4685                                const SmallVectorImpl<SDValue> &OutVals,
4686                                SDLoc dl, SelectionDAG &DAG) const {
4687
4688   SmallVector<CCValAssign, 16> RVLocs;
4689   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4690                  getTargetMachine(), RVLocs, *DAG.getContext());
4691   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4692
4693   SDValue Flag;
4694   SmallVector<SDValue, 4> RetOps(1, Chain);
4695
4696   // Copy the result values into the output registers.
4697   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4698     CCValAssign &VA = RVLocs[i];
4699     assert(VA.isRegLoc() && "Can only return in registers!");
4700
4701     SDValue Arg = OutVals[i];
4702
4703     switch (VA.getLocInfo()) {
4704     default: llvm_unreachable("Unknown loc info!");
4705     case CCValAssign::Full: break;
4706     case CCValAssign::AExt:
4707       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4708       break;
4709     case CCValAssign::ZExt:
4710       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4711       break;
4712     case CCValAssign::SExt:
4713       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4714       break;
4715     }
4716
4717     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4718     Flag = Chain.getValue(1);
4719     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4720   }
4721
4722   RetOps[0] = Chain;  // Update chain.
4723
4724   // Add the flag if we have it.
4725   if (Flag.getNode())
4726     RetOps.push_back(Flag);
4727
4728   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4729                      &RetOps[0], RetOps.size());
4730 }
4731
4732 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4733                                    const PPCSubtarget &Subtarget) const {
4734   // When we pop the dynamic allocation we need to restore the SP link.
4735   SDLoc dl(Op);
4736
4737   // Get the corect type for pointers.
4738   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4739
4740   // Construct the stack pointer operand.
4741   bool isPPC64 = Subtarget.isPPC64();
4742   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4743   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4744
4745   // Get the operands for the STACKRESTORE.
4746   SDValue Chain = Op.getOperand(0);
4747   SDValue SaveSP = Op.getOperand(1);
4748
4749   // Load the old link SP.
4750   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4751                                    MachinePointerInfo(),
4752                                    false, false, false, 0);
4753
4754   // Restore the stack pointer.
4755   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4756
4757   // Store the old link SP.
4758   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4759                       false, false, 0);
4760 }
4761
4762
4763
4764 SDValue
4765 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4766   MachineFunction &MF = DAG.getMachineFunction();
4767   bool isPPC64 = PPCSubTarget.isPPC64();
4768   bool isDarwinABI = PPCSubTarget.isDarwinABI();
4769   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4770
4771   // Get current frame pointer save index.  The users of this index will be
4772   // primarily DYNALLOC instructions.
4773   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4774   int RASI = FI->getReturnAddrSaveIndex();
4775
4776   // If the frame pointer save index hasn't been defined yet.
4777   if (!RASI) {
4778     // Find out what the fix offset of the frame pointer save area.
4779     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4780     // Allocate the frame index for frame pointer save area.
4781     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4782     // Save the result.
4783     FI->setReturnAddrSaveIndex(RASI);
4784   }
4785   return DAG.getFrameIndex(RASI, PtrVT);
4786 }
4787
4788 SDValue
4789 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4790   MachineFunction &MF = DAG.getMachineFunction();
4791   bool isPPC64 = PPCSubTarget.isPPC64();
4792   bool isDarwinABI = PPCSubTarget.isDarwinABI();
4793   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4794
4795   // Get current frame pointer save index.  The users of this index will be
4796   // primarily DYNALLOC instructions.
4797   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4798   int FPSI = FI->getFramePointerSaveIndex();
4799
4800   // If the frame pointer save index hasn't been defined yet.
4801   if (!FPSI) {
4802     // Find out what the fix offset of the frame pointer save area.
4803     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4804                                                            isDarwinABI);
4805
4806     // Allocate the frame index for frame pointer save area.
4807     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4808     // Save the result.
4809     FI->setFramePointerSaveIndex(FPSI);
4810   }
4811   return DAG.getFrameIndex(FPSI, PtrVT);
4812 }
4813
4814 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4815                                          SelectionDAG &DAG,
4816                                          const PPCSubtarget &Subtarget) const {
4817   // Get the inputs.
4818   SDValue Chain = Op.getOperand(0);
4819   SDValue Size  = Op.getOperand(1);
4820   SDLoc dl(Op);
4821
4822   // Get the corect type for pointers.
4823   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4824   // Negate the size.
4825   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4826                                   DAG.getConstant(0, PtrVT), Size);
4827   // Construct a node for the frame pointer save index.
4828   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4829   // Build a DYNALLOC node.
4830   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4831   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4832   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4833 }
4834
4835 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4836                                                SelectionDAG &DAG) const {
4837   SDLoc DL(Op);
4838   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4839                      DAG.getVTList(MVT::i32, MVT::Other),
4840                      Op.getOperand(0), Op.getOperand(1));
4841 }
4842
4843 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4844                                                 SelectionDAG &DAG) const {
4845   SDLoc DL(Op);
4846   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4847                      Op.getOperand(0), Op.getOperand(1));
4848 }
4849
4850 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
4851   assert(Op.getValueType() == MVT::i1 &&
4852          "Custom lowering only for i1 loads");
4853
4854   // First, load 8 bits into 32 bits, then truncate to 1 bit.
4855
4856   SDLoc dl(Op);
4857   LoadSDNode *LD = cast<LoadSDNode>(Op);
4858
4859   SDValue Chain = LD->getChain();
4860   SDValue BasePtr = LD->getBasePtr();
4861   MachineMemOperand *MMO = LD->getMemOperand();
4862
4863   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
4864                                  BasePtr, MVT::i8, MMO);
4865   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
4866
4867   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
4868   return DAG.getMergeValues(Ops, 2, dl);
4869 }
4870
4871 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
4872   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
4873          "Custom lowering only for i1 stores");
4874
4875   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
4876
4877   SDLoc dl(Op);
4878   StoreSDNode *ST = cast<StoreSDNode>(Op);
4879
4880   SDValue Chain = ST->getChain();
4881   SDValue BasePtr = ST->getBasePtr();
4882   SDValue Value = ST->getValue();
4883   MachineMemOperand *MMO = ST->getMemOperand();
4884
4885   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
4886   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
4887 }
4888
4889 // FIXME: Remove this once the ANDI glue bug is fixed:
4890 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
4891   assert(Op.getValueType() == MVT::i1 &&
4892          "Custom lowering only for i1 results");
4893
4894   SDLoc DL(Op);
4895   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
4896                      Op.getOperand(0));
4897 }
4898
4899 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4900 /// possible.
4901 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4902   // Not FP? Not a fsel.
4903   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4904       !Op.getOperand(2).getValueType().isFloatingPoint())
4905     return Op;
4906
4907   // We might be able to do better than this under some circumstances, but in
4908   // general, fsel-based lowering of select is a finite-math-only optimization.
4909   // For more information, see section F.3 of the 2.06 ISA specification.
4910   if (!DAG.getTarget().Options.NoInfsFPMath ||
4911       !DAG.getTarget().Options.NoNaNsFPMath)
4912     return Op;
4913
4914   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4915
4916   EVT ResVT = Op.getValueType();
4917   EVT CmpVT = Op.getOperand(0).getValueType();
4918   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4919   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
4920   SDLoc dl(Op);
4921
4922   // If the RHS of the comparison is a 0.0, we don't need to do the
4923   // subtraction at all.
4924   SDValue Sel1;
4925   if (isFloatingPointZero(RHS))
4926     switch (CC) {
4927     default: break;       // SETUO etc aren't handled by fsel.
4928     case ISD::SETNE:
4929       std::swap(TV, FV);
4930     case ISD::SETEQ:
4931       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
4932         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4933       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4934       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
4935         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4936       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4937                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4938     case ISD::SETULT:
4939     case ISD::SETLT:
4940       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
4941     case ISD::SETOGE:
4942     case ISD::SETGE:
4943       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
4944         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4945       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4946     case ISD::SETUGT:
4947     case ISD::SETGT:
4948       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
4949     case ISD::SETOLE:
4950     case ISD::SETLE:
4951       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
4952         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4953       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4954                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4955     }
4956
4957   SDValue Cmp;
4958   switch (CC) {
4959   default: break;       // SETUO etc aren't handled by fsel.
4960   case ISD::SETNE:
4961     std::swap(TV, FV);
4962   case ISD::SETEQ:
4963     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4964     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4965       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4966     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4967     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
4968       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4969     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4970                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4971   case ISD::SETULT:
4972   case ISD::SETLT:
4973     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4974     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4975       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4976     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4977   case ISD::SETOGE:
4978   case ISD::SETGE:
4979     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4980     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4981       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4982     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4983   case ISD::SETUGT:
4984   case ISD::SETGT:
4985     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4986     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4987       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4988     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4989   case ISD::SETOLE:
4990   case ISD::SETLE:
4991     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4992     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
4993       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4994     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4995   }
4996   return Op;
4997 }
4998
4999 // FIXME: Split this code up when LegalizeDAGTypes lands.
5000 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5001                                            SDLoc dl) const {
5002   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5003   SDValue Src = Op.getOperand(0);
5004   if (Src.getValueType() == MVT::f32)
5005     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5006
5007   SDValue Tmp;
5008   switch (Op.getSimpleValueType().SimpleTy) {
5009   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5010   case MVT::i32:
5011     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5012                         (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5013                                                    PPCISD::FCTIDZ),
5014                       dl, MVT::f64, Src);
5015     break;
5016   case MVT::i64:
5017     assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
5018            "i64 FP_TO_UINT is supported only with FPCVT");
5019     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5020                                                         PPCISD::FCTIDUZ,
5021                       dl, MVT::f64, Src);
5022     break;
5023   }
5024
5025   // Convert the FP value to an int value through memory.
5026   bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
5027     (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
5028   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5029   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5030   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5031
5032   // Emit a store to the stack slot.
5033   SDValue Chain;
5034   if (i32Stack) {
5035     MachineFunction &MF = DAG.getMachineFunction();
5036     MachineMemOperand *MMO =
5037       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5038     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5039     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5040               DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
5041               MVT::i32, MMO);
5042   } else
5043     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5044                          MPI, false, false, 0);
5045
5046   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5047   // add in a bias.
5048   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5049     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5050                         DAG.getConstant(4, FIPtr.getValueType()));
5051     MPI = MachinePointerInfo();
5052   }
5053
5054   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5055                      false, false, false, 0);
5056 }
5057
5058 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5059                                            SelectionDAG &DAG) const {
5060   SDLoc dl(Op);
5061   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5062   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5063     return SDValue();
5064
5065   if (Op.getOperand(0).getValueType() == MVT::i1)
5066     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5067                        DAG.getConstantFP(1.0, Op.getValueType()),
5068                        DAG.getConstantFP(0.0, Op.getValueType()));
5069
5070   assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
5071          "UINT_TO_FP is supported only with FPCVT");
5072
5073   // If we have FCFIDS, then use it when converting to single-precision.
5074   // Otherwise, convert to double-precision and then round.
5075   unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5076                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5077                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5078                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5079                     PPCISD::FCFIDU : PPCISD::FCFID);
5080   MVT      FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5081                    MVT::f32 : MVT::f64;
5082
5083   if (Op.getOperand(0).getValueType() == MVT::i64) {
5084     SDValue SINT = Op.getOperand(0);
5085     // When converting to single-precision, we actually need to convert
5086     // to double-precision first and then round to single-precision.
5087     // To avoid double-rounding effects during that operation, we have
5088     // to prepare the input operand.  Bits that might be truncated when
5089     // converting to double-precision are replaced by a bit that won't
5090     // be lost at this stage, but is below the single-precision rounding
5091     // position.
5092     //
5093     // However, if -enable-unsafe-fp-math is in effect, accept double
5094     // rounding to avoid the extra overhead.
5095     if (Op.getValueType() == MVT::f32 &&
5096         !PPCSubTarget.hasFPCVT() &&
5097         !DAG.getTarget().Options.UnsafeFPMath) {
5098
5099       // Twiddle input to make sure the low 11 bits are zero.  (If this
5100       // is the case, we are guaranteed the value will fit into the 53 bit
5101       // mantissa of an IEEE double-precision value without rounding.)
5102       // If any of those low 11 bits were not zero originally, make sure
5103       // bit 12 (value 2048) is set instead, so that the final rounding
5104       // to single-precision gets the correct result.
5105       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5106                                   SINT, DAG.getConstant(2047, MVT::i64));
5107       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5108                           Round, DAG.getConstant(2047, MVT::i64));
5109       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5110       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5111                           Round, DAG.getConstant(-2048, MVT::i64));
5112
5113       // However, we cannot use that value unconditionally: if the magnitude
5114       // of the input value is small, the bit-twiddling we did above might
5115       // end up visibly changing the output.  Fortunately, in that case, we
5116       // don't need to twiddle bits since the original input will convert
5117       // exactly to double-precision floating-point already.  Therefore,
5118       // construct a conditional to use the original value if the top 11
5119       // bits are all sign-bit copies, and use the rounded value computed
5120       // above otherwise.
5121       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5122                                  SINT, DAG.getConstant(53, MVT::i32));
5123       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5124                          Cond, DAG.getConstant(1, MVT::i64));
5125       Cond = DAG.getSetCC(dl, MVT::i32,
5126                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5127
5128       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5129     }
5130
5131     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5132     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5133
5134     if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5135       FP = DAG.getNode(ISD::FP_ROUND, dl,
5136                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5137     return FP;
5138   }
5139
5140   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5141          "Unhandled INT_TO_FP type in custom expander!");
5142   // Since we only generate this in 64-bit mode, we can take advantage of
5143   // 64-bit registers.  In particular, sign extend the input value into the
5144   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5145   // then lfd it and fcfid it.
5146   MachineFunction &MF = DAG.getMachineFunction();
5147   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5148   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5149
5150   SDValue Ld;
5151   if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
5152     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5153     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5154
5155     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5156                                  MachinePointerInfo::getFixedStack(FrameIdx),
5157                                  false, false, 0);
5158
5159     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5160            "Expected an i32 store");
5161     MachineMemOperand *MMO =
5162       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5163                               MachineMemOperand::MOLoad, 4, 4);
5164     SDValue Ops[] = { Store, FIdx };
5165     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5166                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5167                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5168                                  Ops, 2, MVT::i32, MMO);
5169   } else {
5170     assert(PPCSubTarget.isPPC64() &&
5171            "i32->FP without LFIWAX supported only on PPC64");
5172
5173     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5174     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5175
5176     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5177                                 Op.getOperand(0));
5178
5179     // STD the extended value into the stack slot.
5180     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5181                                  MachinePointerInfo::getFixedStack(FrameIdx),
5182                                  false, false, 0);
5183
5184     // Load the value as a double.
5185     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5186                      MachinePointerInfo::getFixedStack(FrameIdx),
5187                      false, false, false, 0);
5188   }
5189
5190   // FCFID it and return it.
5191   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5192   if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
5193     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5194   return FP;
5195 }
5196
5197 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5198                                             SelectionDAG &DAG) const {
5199   SDLoc dl(Op);
5200   /*
5201    The rounding mode is in bits 30:31 of FPSR, and has the following
5202    settings:
5203      00 Round to nearest
5204      01 Round to 0
5205      10 Round to +inf
5206      11 Round to -inf
5207
5208   FLT_ROUNDS, on the other hand, expects the following:
5209     -1 Undefined
5210      0 Round to 0
5211      1 Round to nearest
5212      2 Round to +inf
5213      3 Round to -inf
5214
5215   To perform the conversion, we do:
5216     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5217   */
5218
5219   MachineFunction &MF = DAG.getMachineFunction();
5220   EVT VT = Op.getValueType();
5221   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5222   SDValue MFFSreg, InFlag;
5223
5224   // Save FP Control Word to register
5225   EVT NodeTys[] = {
5226     MVT::f64,    // return register
5227     MVT::Glue    // unused in this context
5228   };
5229   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5230
5231   // Save FP register to stack slot
5232   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5233   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5234   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5235                                StackSlot, MachinePointerInfo(), false, false,0);
5236
5237   // Load FP Control Word from low 32 bits of stack slot.
5238   SDValue Four = DAG.getConstant(4, PtrVT);
5239   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5240   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5241                             false, false, false, 0);
5242
5243   // Transform as necessary
5244   SDValue CWD1 =
5245     DAG.getNode(ISD::AND, dl, MVT::i32,
5246                 CWD, DAG.getConstant(3, MVT::i32));
5247   SDValue CWD2 =
5248     DAG.getNode(ISD::SRL, dl, MVT::i32,
5249                 DAG.getNode(ISD::AND, dl, MVT::i32,
5250                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5251                                         CWD, DAG.getConstant(3, MVT::i32)),
5252                             DAG.getConstant(3, MVT::i32)),
5253                 DAG.getConstant(1, MVT::i32));
5254
5255   SDValue RetVal =
5256     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5257
5258   return DAG.getNode((VT.getSizeInBits() < 16 ?
5259                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5260 }
5261
5262 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5263   EVT VT = Op.getValueType();
5264   unsigned BitWidth = VT.getSizeInBits();
5265   SDLoc dl(Op);
5266   assert(Op.getNumOperands() == 3 &&
5267          VT == Op.getOperand(1).getValueType() &&
5268          "Unexpected SHL!");
5269
5270   // Expand into a bunch of logical ops.  Note that these ops
5271   // depend on the PPC behavior for oversized shift amounts.
5272   SDValue Lo = Op.getOperand(0);
5273   SDValue Hi = Op.getOperand(1);
5274   SDValue Amt = Op.getOperand(2);
5275   EVT AmtVT = Amt.getValueType();
5276
5277   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5278                              DAG.getConstant(BitWidth, AmtVT), Amt);
5279   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5280   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5281   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5282   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5283                              DAG.getConstant(-BitWidth, AmtVT));
5284   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5285   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5286   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5287   SDValue OutOps[] = { OutLo, OutHi };
5288   return DAG.getMergeValues(OutOps, 2, dl);
5289 }
5290
5291 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5292   EVT VT = Op.getValueType();
5293   SDLoc dl(Op);
5294   unsigned BitWidth = VT.getSizeInBits();
5295   assert(Op.getNumOperands() == 3 &&
5296          VT == Op.getOperand(1).getValueType() &&
5297          "Unexpected SRL!");
5298
5299   // Expand into a bunch of logical ops.  Note that these ops
5300   // depend on the PPC behavior for oversized shift amounts.
5301   SDValue Lo = Op.getOperand(0);
5302   SDValue Hi = Op.getOperand(1);
5303   SDValue Amt = Op.getOperand(2);
5304   EVT AmtVT = Amt.getValueType();
5305
5306   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5307                              DAG.getConstant(BitWidth, AmtVT), Amt);
5308   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5309   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5310   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5311   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5312                              DAG.getConstant(-BitWidth, AmtVT));
5313   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5314   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5315   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5316   SDValue OutOps[] = { OutLo, OutHi };
5317   return DAG.getMergeValues(OutOps, 2, dl);
5318 }
5319
5320 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5321   SDLoc dl(Op);
5322   EVT VT = Op.getValueType();
5323   unsigned BitWidth = VT.getSizeInBits();
5324   assert(Op.getNumOperands() == 3 &&
5325          VT == Op.getOperand(1).getValueType() &&
5326          "Unexpected SRA!");
5327
5328   // Expand into a bunch of logical ops, followed by a select_cc.
5329   SDValue Lo = Op.getOperand(0);
5330   SDValue Hi = Op.getOperand(1);
5331   SDValue Amt = Op.getOperand(2);
5332   EVT AmtVT = Amt.getValueType();
5333
5334   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5335                              DAG.getConstant(BitWidth, AmtVT), Amt);
5336   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5337   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5338   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5339   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5340                              DAG.getConstant(-BitWidth, AmtVT));
5341   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5342   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5343   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5344                                   Tmp4, Tmp6, ISD::SETLE);
5345   SDValue OutOps[] = { OutLo, OutHi };
5346   return DAG.getMergeValues(OutOps, 2, dl);
5347 }
5348
5349 //===----------------------------------------------------------------------===//
5350 // Vector related lowering.
5351 //
5352
5353 /// BuildSplatI - Build a canonical splati of Val with an element size of
5354 /// SplatSize.  Cast the result to VT.
5355 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5356                              SelectionDAG &DAG, SDLoc dl) {
5357   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5358
5359   static const EVT VTys[] = { // canonical VT to use for each size.
5360     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5361   };
5362
5363   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5364
5365   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5366   if (Val == -1)
5367     SplatSize = 1;
5368
5369   EVT CanonicalVT = VTys[SplatSize-1];
5370
5371   // Build a canonical splat for this value.
5372   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5373   SmallVector<SDValue, 8> Ops;
5374   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5375   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5376                               &Ops[0], Ops.size());
5377   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5378 }
5379
5380 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5381 /// specified intrinsic ID.
5382 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5383                                 SelectionDAG &DAG, SDLoc dl,
5384                                 EVT DestVT = MVT::Other) {
5385   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5386   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5387                      DAG.getConstant(IID, MVT::i32), Op);
5388 }
5389
5390 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5391 /// specified intrinsic ID.
5392 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5393                                 SelectionDAG &DAG, SDLoc dl,
5394                                 EVT DestVT = MVT::Other) {
5395   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5396   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5397                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5398 }
5399
5400 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5401 /// specified intrinsic ID.
5402 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5403                                 SDValue Op2, SelectionDAG &DAG,
5404                                 SDLoc dl, EVT DestVT = MVT::Other) {
5405   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5406   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5407                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5408 }
5409
5410
5411 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5412 /// amount.  The result has the specified value type.
5413 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5414                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5415   // Force LHS/RHS to be the right type.
5416   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5417   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5418
5419   int Ops[16];
5420   for (unsigned i = 0; i != 16; ++i)
5421     Ops[i] = i + Amt;
5422   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5423   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5424 }
5425
5426 // If this is a case we can't handle, return null and let the default
5427 // expansion code take care of it.  If we CAN select this case, and if it
5428 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5429 // this case more efficiently than a constant pool load, lower it to the
5430 // sequence of ops that should be used.
5431 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5432                                              SelectionDAG &DAG) const {
5433   SDLoc dl(Op);
5434   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5435   assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5436
5437   // Check if this is a splat of a constant value.
5438   APInt APSplatBits, APSplatUndef;
5439   unsigned SplatBitSize;
5440   bool HasAnyUndefs;
5441   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5442                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5443     return SDValue();
5444
5445   unsigned SplatBits = APSplatBits.getZExtValue();
5446   unsigned SplatUndef = APSplatUndef.getZExtValue();
5447   unsigned SplatSize = SplatBitSize / 8;
5448
5449   // First, handle single instruction cases.
5450
5451   // All zeros?
5452   if (SplatBits == 0) {
5453     // Canonicalize all zero vectors to be v4i32.
5454     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5455       SDValue Z = DAG.getConstant(0, MVT::i32);
5456       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5457       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5458     }
5459     return Op;
5460   }
5461
5462   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5463   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5464                     (32-SplatBitSize));
5465   if (SextVal >= -16 && SextVal <= 15)
5466     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5467
5468
5469   // Two instruction sequences.
5470
5471   // If this value is in the range [-32,30] and is even, use:
5472   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5473   // If this value is in the range [17,31] and is odd, use:
5474   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5475   // If this value is in the range [-31,-17] and is odd, use:
5476   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5477   // Note the last two are three-instruction sequences.
5478   if (SextVal >= -32 && SextVal <= 31) {
5479     // To avoid having these optimizations undone by constant folding,
5480     // we convert to a pseudo that will be expanded later into one of
5481     // the above forms.
5482     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5483     EVT VT = Op.getValueType();
5484     int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5485     SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5486     return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5487   }
5488
5489   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5490   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5491   // for fneg/fabs.
5492   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5493     // Make -1 and vspltisw -1:
5494     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5495
5496     // Make the VSLW intrinsic, computing 0x8000_0000.
5497     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5498                                    OnesV, DAG, dl);
5499
5500     // xor by OnesV to invert it.
5501     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5502     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5503   }
5504
5505   // Check to see if this is a wide variety of vsplti*, binop self cases.
5506   static const signed char SplatCsts[] = {
5507     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5508     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5509   };
5510
5511   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5512     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5513     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5514     int i = SplatCsts[idx];
5515
5516     // Figure out what shift amount will be used by altivec if shifted by i in
5517     // this splat size.
5518     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5519
5520     // vsplti + shl self.
5521     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5522       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5523       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5524         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5525         Intrinsic::ppc_altivec_vslw
5526       };
5527       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5528       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5529     }
5530
5531     // vsplti + srl self.
5532     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5533       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5534       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5535         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5536         Intrinsic::ppc_altivec_vsrw
5537       };
5538       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5539       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5540     }
5541
5542     // vsplti + sra self.
5543     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5544       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5545       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5546         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5547         Intrinsic::ppc_altivec_vsraw
5548       };
5549       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5550       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5551     }
5552
5553     // vsplti + rol self.
5554     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5555                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5556       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5557       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5558         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5559         Intrinsic::ppc_altivec_vrlw
5560       };
5561       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5562       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5563     }
5564
5565     // t = vsplti c, result = vsldoi t, t, 1
5566     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5567       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5568       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5569     }
5570     // t = vsplti c, result = vsldoi t, t, 2
5571     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5572       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5573       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5574     }
5575     // t = vsplti c, result = vsldoi t, t, 3
5576     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5577       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5578       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5579     }
5580   }
5581
5582   return SDValue();
5583 }
5584
5585 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5586 /// the specified operations to build the shuffle.
5587 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5588                                       SDValue RHS, SelectionDAG &DAG,
5589                                       SDLoc dl) {
5590   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5591   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5592   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5593
5594   enum {
5595     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5596     OP_VMRGHW,
5597     OP_VMRGLW,
5598     OP_VSPLTISW0,
5599     OP_VSPLTISW1,
5600     OP_VSPLTISW2,
5601     OP_VSPLTISW3,
5602     OP_VSLDOI4,
5603     OP_VSLDOI8,
5604     OP_VSLDOI12
5605   };
5606
5607   if (OpNum == OP_COPY) {
5608     if (LHSID == (1*9+2)*9+3) return LHS;
5609     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5610     return RHS;
5611   }
5612
5613   SDValue OpLHS, OpRHS;
5614   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5615   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5616
5617   int ShufIdxs[16];
5618   switch (OpNum) {
5619   default: llvm_unreachable("Unknown i32 permute!");
5620   case OP_VMRGHW:
5621     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
5622     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5623     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
5624     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5625     break;
5626   case OP_VMRGLW:
5627     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5628     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5629     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5630     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5631     break;
5632   case OP_VSPLTISW0:
5633     for (unsigned i = 0; i != 16; ++i)
5634       ShufIdxs[i] = (i&3)+0;
5635     break;
5636   case OP_VSPLTISW1:
5637     for (unsigned i = 0; i != 16; ++i)
5638       ShufIdxs[i] = (i&3)+4;
5639     break;
5640   case OP_VSPLTISW2:
5641     for (unsigned i = 0; i != 16; ++i)
5642       ShufIdxs[i] = (i&3)+8;
5643     break;
5644   case OP_VSPLTISW3:
5645     for (unsigned i = 0; i != 16; ++i)
5646       ShufIdxs[i] = (i&3)+12;
5647     break;
5648   case OP_VSLDOI4:
5649     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5650   case OP_VSLDOI8:
5651     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5652   case OP_VSLDOI12:
5653     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5654   }
5655   EVT VT = OpLHS.getValueType();
5656   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5657   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5658   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5659   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5660 }
5661
5662 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
5663 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
5664 /// return the code it can be lowered into.  Worst case, it can always be
5665 /// lowered into a vperm.
5666 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5667                                                SelectionDAG &DAG) const {
5668   SDLoc dl(Op);
5669   SDValue V1 = Op.getOperand(0);
5670   SDValue V2 = Op.getOperand(1);
5671   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5672   EVT VT = Op.getValueType();
5673
5674   // Cases that are handled by instructions that take permute immediates
5675   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5676   // selected by the instruction selector.
5677   if (V2.getOpcode() == ISD::UNDEF) {
5678     if (PPC::isSplatShuffleMask(SVOp, 1) ||
5679         PPC::isSplatShuffleMask(SVOp, 2) ||
5680         PPC::isSplatShuffleMask(SVOp, 4) ||
5681         PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5682         PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5683         PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5684         PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5685         PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5686         PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5687         PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5688         PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5689         PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5690       return Op;
5691     }
5692   }
5693
5694   // Altivec has a variety of "shuffle immediates" that take two vector inputs
5695   // and produce a fixed permutation.  If any of these match, do not lower to
5696   // VPERM.
5697   if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5698       PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5699       PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5700       PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5701       PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5702       PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5703       PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5704       PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5705       PPC::isVMRGHShuffleMask(SVOp, 4, false))
5706     return Op;
5707
5708   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
5709   // perfect shuffle table to emit an optimal matching sequence.
5710   ArrayRef<int> PermMask = SVOp->getMask();
5711
5712   unsigned PFIndexes[4];
5713   bool isFourElementShuffle = true;
5714   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5715     unsigned EltNo = 8;   // Start out undef.
5716     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
5717       if (PermMask[i*4+j] < 0)
5718         continue;   // Undef, ignore it.
5719
5720       unsigned ByteSource = PermMask[i*4+j];
5721       if ((ByteSource & 3) != j) {
5722         isFourElementShuffle = false;
5723         break;
5724       }
5725
5726       if (EltNo == 8) {
5727         EltNo = ByteSource/4;
5728       } else if (EltNo != ByteSource/4) {
5729         isFourElementShuffle = false;
5730         break;
5731       }
5732     }
5733     PFIndexes[i] = EltNo;
5734   }
5735
5736   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5737   // perfect shuffle vector to determine if it is cost effective to do this as
5738   // discrete instructions, or whether we should use a vperm.
5739   if (isFourElementShuffle) {
5740     // Compute the index in the perfect shuffle table.
5741     unsigned PFTableIndex =
5742       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5743
5744     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5745     unsigned Cost  = (PFEntry >> 30);
5746
5747     // Determining when to avoid vperm is tricky.  Many things affect the cost
5748     // of vperm, particularly how many times the perm mask needs to be computed.
5749     // For example, if the perm mask can be hoisted out of a loop or is already
5750     // used (perhaps because there are multiple permutes with the same shuffle
5751     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
5752     // the loop requires an extra register.
5753     //
5754     // As a compromise, we only emit discrete instructions if the shuffle can be
5755     // generated in 3 or fewer operations.  When we have loop information
5756     // available, if this block is within a loop, we should avoid using vperm
5757     // for 3-operation perms and use a constant pool load instead.
5758     if (Cost < 3)
5759       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5760   }
5761
5762   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5763   // vector that will get spilled to the constant pool.
5764   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5765
5766   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5767   // that it is in input element units, not in bytes.  Convert now.
5768   EVT EltVT = V1.getValueType().getVectorElementType();
5769   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5770
5771   SmallVector<SDValue, 16> ResultMask;
5772   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5773     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5774
5775     for (unsigned j = 0; j != BytesPerElement; ++j)
5776       ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5777                                            MVT::i32));
5778   }
5779
5780   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5781                                     &ResultMask[0], ResultMask.size());
5782   return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5783 }
5784
5785 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5786 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
5787 /// information about the intrinsic.
5788 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5789                                   bool &isDot) {
5790   unsigned IntrinsicID =
5791     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5792   CompareOpc = -1;
5793   isDot = false;
5794   switch (IntrinsicID) {
5795   default: return false;
5796     // Comparison predicates.
5797   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
5798   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5799   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
5800   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
5801   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5802   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5803   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5804   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5805   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5806   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5807   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5808   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5809   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5810
5811     // Normal Comparisons.
5812   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
5813   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
5814   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
5815   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
5816   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
5817   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
5818   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
5819   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
5820   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
5821   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
5822   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
5823   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
5824   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
5825   }
5826   return true;
5827 }
5828
5829 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5830 /// lower, do it, otherwise return null.
5831 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5832                                                    SelectionDAG &DAG) const {
5833   // If this is a lowered altivec predicate compare, CompareOpc is set to the
5834   // opcode number of the comparison.
5835   SDLoc dl(Op);
5836   int CompareOpc;
5837   bool isDot;
5838   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5839     return SDValue();    // Don't custom lower most intrinsics.
5840
5841   // If this is a non-dot comparison, make the VCMP node and we are done.
5842   if (!isDot) {
5843     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5844                               Op.getOperand(1), Op.getOperand(2),
5845                               DAG.getConstant(CompareOpc, MVT::i32));
5846     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5847   }
5848
5849   // Create the PPCISD altivec 'dot' comparison node.
5850   SDValue Ops[] = {
5851     Op.getOperand(2),  // LHS
5852     Op.getOperand(3),  // RHS
5853     DAG.getConstant(CompareOpc, MVT::i32)
5854   };
5855   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5856   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5857
5858   // Now that we have the comparison, emit a copy from the CR to a GPR.
5859   // This is flagged to the above dot comparison.
5860   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5861                                 DAG.getRegister(PPC::CR6, MVT::i32),
5862                                 CompNode.getValue(1));
5863
5864   // Unpack the result based on how the target uses it.
5865   unsigned BitNo;   // Bit # of CR6.
5866   bool InvertBit;   // Invert result?
5867   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5868   default:  // Can't happen, don't crash on invalid number though.
5869   case 0:   // Return the value of the EQ bit of CR6.
5870     BitNo = 0; InvertBit = false;
5871     break;
5872   case 1:   // Return the inverted value of the EQ bit of CR6.
5873     BitNo = 0; InvertBit = true;
5874     break;
5875   case 2:   // Return the value of the LT bit of CR6.
5876     BitNo = 2; InvertBit = false;
5877     break;
5878   case 3:   // Return the inverted value of the LT bit of CR6.
5879     BitNo = 2; InvertBit = true;
5880     break;
5881   }
5882
5883   // Shift the bit into the low position.
5884   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5885                       DAG.getConstant(8-(3-BitNo), MVT::i32));
5886   // Isolate the bit.
5887   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5888                       DAG.getConstant(1, MVT::i32));
5889
5890   // If we are supposed to, toggle the bit.
5891   if (InvertBit)
5892     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5893                         DAG.getConstant(1, MVT::i32));
5894   return Flags;
5895 }
5896
5897 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5898                                                    SelectionDAG &DAG) const {
5899   SDLoc dl(Op);
5900   // Create a stack slot that is 16-byte aligned.
5901   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5902   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5903   EVT PtrVT = getPointerTy();
5904   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5905
5906   // Store the input value into Value#0 of the stack slot.
5907   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5908                                Op.getOperand(0), FIdx, MachinePointerInfo(),
5909                                false, false, 0);
5910   // Load it out.
5911   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5912                      false, false, false, 0);
5913 }
5914
5915 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5916   SDLoc dl(Op);
5917   if (Op.getValueType() == MVT::v4i32) {
5918     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5919
5920     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
5921     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5922
5923     SDValue RHSSwap =   // = vrlw RHS, 16
5924       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5925
5926     // Shrinkify inputs to v8i16.
5927     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5928     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5929     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5930
5931     // Low parts multiplied together, generating 32-bit results (we ignore the
5932     // top parts).
5933     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5934                                         LHS, RHS, DAG, dl, MVT::v4i32);
5935
5936     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5937                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5938     // Shift the high parts up 16 bits.
5939     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5940                               Neg16, DAG, dl);
5941     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5942   } else if (Op.getValueType() == MVT::v8i16) {
5943     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5944
5945     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5946
5947     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5948                             LHS, RHS, Zero, DAG, dl);
5949   } else if (Op.getValueType() == MVT::v16i8) {
5950     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5951
5952     // Multiply the even 8-bit parts, producing 16-bit sums.
5953     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5954                                            LHS, RHS, DAG, dl, MVT::v8i16);
5955     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5956
5957     // Multiply the odd 8-bit parts, producing 16-bit sums.
5958     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5959                                           LHS, RHS, DAG, dl, MVT::v8i16);
5960     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5961
5962     // Merge the results together.
5963     int Ops[16];
5964     for (unsigned i = 0; i != 8; ++i) {
5965       Ops[i*2  ] = 2*i+1;
5966       Ops[i*2+1] = 2*i+1+16;
5967     }
5968     return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5969   } else {
5970     llvm_unreachable("Unknown mul to lower!");
5971   }
5972 }
5973
5974 /// LowerOperation - Provide custom lowering hooks for some operations.
5975 ///
5976 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5977   switch (Op.getOpcode()) {
5978   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5979   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5980   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
5981   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5982   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5983   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5984   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5985   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
5986   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
5987   case ISD::VASTART:
5988     return LowerVASTART(Op, DAG, PPCSubTarget);
5989
5990   case ISD::VAARG:
5991     return LowerVAARG(Op, DAG, PPCSubTarget);
5992
5993   case ISD::VACOPY:
5994     return LowerVACOPY(Op, DAG, PPCSubTarget);
5995
5996   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5997   case ISD::DYNAMIC_STACKALLOC:
5998     return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5999
6000   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6001   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6002
6003   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6004   case ISD::STORE:              return LowerSTORE(Op, DAG);
6005   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6006   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6007   case ISD::FP_TO_UINT:
6008   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6009                                                        SDLoc(Op));
6010   case ISD::UINT_TO_FP:
6011   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6012   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6013
6014   // Lower 64-bit shifts.
6015   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6016   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6017   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6018
6019   // Vector-related lowering.
6020   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6021   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6022   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6023   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6024   case ISD::MUL:                return LowerMUL(Op, DAG);
6025
6026   // For counter-based loop handling.
6027   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6028
6029   // Frame & Return address.
6030   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6031   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6032   }
6033 }
6034
6035 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6036                                            SmallVectorImpl<SDValue>&Results,
6037                                            SelectionDAG &DAG) const {
6038   const TargetMachine &TM = getTargetMachine();
6039   SDLoc dl(N);
6040   switch (N->getOpcode()) {
6041   default:
6042     llvm_unreachable("Do not know how to custom type legalize this operation!");
6043   case ISD::INTRINSIC_W_CHAIN: {
6044     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6045         Intrinsic::ppc_is_decremented_ctr_nonzero)
6046       break;
6047
6048     assert(N->getValueType(0) == MVT::i1 &&
6049            "Unexpected result type for CTR decrement intrinsic");
6050     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6051     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6052     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6053                                  N->getOperand(1)); 
6054
6055     Results.push_back(NewInt);
6056     Results.push_back(NewInt.getValue(1));
6057     break;
6058   }
6059   case ISD::VAARG: {
6060     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6061         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6062       return;
6063
6064     EVT VT = N->getValueType(0);
6065
6066     if (VT == MVT::i64) {
6067       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
6068
6069       Results.push_back(NewNode);
6070       Results.push_back(NewNode.getValue(1));
6071     }
6072     return;
6073   }
6074   case ISD::FP_ROUND_INREG: {
6075     assert(N->getValueType(0) == MVT::ppcf128);
6076     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6077     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6078                              MVT::f64, N->getOperand(0),
6079                              DAG.getIntPtrConstant(0));
6080     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6081                              MVT::f64, N->getOperand(0),
6082                              DAG.getIntPtrConstant(1));
6083
6084     // Add the two halves of the long double in round-to-zero mode.
6085     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6086
6087     // We know the low half is about to be thrown away, so just use something
6088     // convenient.
6089     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6090                                 FPreg, FPreg));
6091     return;
6092   }
6093   case ISD::FP_TO_SINT:
6094     // LowerFP_TO_INT() can only handle f32 and f64.
6095     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6096       return;
6097     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6098     return;
6099   }
6100 }
6101
6102
6103 //===----------------------------------------------------------------------===//
6104 //  Other Lowering Code
6105 //===----------------------------------------------------------------------===//
6106
6107 MachineBasicBlock *
6108 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6109                                     bool is64bit, unsigned BinOpcode) const {
6110   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6111   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6112
6113   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6114   MachineFunction *F = BB->getParent();
6115   MachineFunction::iterator It = BB;
6116   ++It;
6117
6118   unsigned dest = MI->getOperand(0).getReg();
6119   unsigned ptrA = MI->getOperand(1).getReg();
6120   unsigned ptrB = MI->getOperand(2).getReg();
6121   unsigned incr = MI->getOperand(3).getReg();
6122   DebugLoc dl = MI->getDebugLoc();
6123
6124   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6125   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6126   F->insert(It, loopMBB);
6127   F->insert(It, exitMBB);
6128   exitMBB->splice(exitMBB->begin(), BB,
6129                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6130   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6131
6132   MachineRegisterInfo &RegInfo = F->getRegInfo();
6133   unsigned TmpReg = (!BinOpcode) ? incr :
6134     RegInfo.createVirtualRegister(
6135        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6136                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
6137
6138   //  thisMBB:
6139   //   ...
6140   //   fallthrough --> loopMBB
6141   BB->addSuccessor(loopMBB);
6142
6143   //  loopMBB:
6144   //   l[wd]arx dest, ptr
6145   //   add r0, dest, incr
6146   //   st[wd]cx. r0, ptr
6147   //   bne- loopMBB
6148   //   fallthrough --> exitMBB
6149   BB = loopMBB;
6150   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6151     .addReg(ptrA).addReg(ptrB);
6152   if (BinOpcode)
6153     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6154   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6155     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6156   BuildMI(BB, dl, TII->get(PPC::BCC))
6157     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6158   BB->addSuccessor(loopMBB);
6159   BB->addSuccessor(exitMBB);
6160
6161   //  exitMBB:
6162   //   ...
6163   BB = exitMBB;
6164   return BB;
6165 }
6166
6167 MachineBasicBlock *
6168 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6169                                             MachineBasicBlock *BB,
6170                                             bool is8bit,    // operation
6171                                             unsigned BinOpcode) const {
6172   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6173   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6174   // In 64 bit mode we have to use 64 bits for addresses, even though the
6175   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6176   // registers without caring whether they're 32 or 64, but here we're
6177   // doing actual arithmetic on the addresses.
6178   bool is64bit = PPCSubTarget.isPPC64();
6179   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6180
6181   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6182   MachineFunction *F = BB->getParent();
6183   MachineFunction::iterator It = BB;
6184   ++It;
6185
6186   unsigned dest = MI->getOperand(0).getReg();
6187   unsigned ptrA = MI->getOperand(1).getReg();
6188   unsigned ptrB = MI->getOperand(2).getReg();
6189   unsigned incr = MI->getOperand(3).getReg();
6190   DebugLoc dl = MI->getDebugLoc();
6191
6192   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6193   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6194   F->insert(It, loopMBB);
6195   F->insert(It, exitMBB);
6196   exitMBB->splice(exitMBB->begin(), BB,
6197                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6198   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6199
6200   MachineRegisterInfo &RegInfo = F->getRegInfo();
6201   const TargetRegisterClass *RC =
6202     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6203               (const TargetRegisterClass *) &PPC::GPRCRegClass;
6204   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6205   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6206   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6207   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6208   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6209   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6210   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6211   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6212   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6213   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6214   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6215   unsigned Ptr1Reg;
6216   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6217
6218   //  thisMBB:
6219   //   ...
6220   //   fallthrough --> loopMBB
6221   BB->addSuccessor(loopMBB);
6222
6223   // The 4-byte load must be aligned, while a char or short may be
6224   // anywhere in the word.  Hence all this nasty bookkeeping code.
6225   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6226   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6227   //   xori shift, shift1, 24 [16]
6228   //   rlwinm ptr, ptr1, 0, 0, 29
6229   //   slw incr2, incr, shift
6230   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6231   //   slw mask, mask2, shift
6232   //  loopMBB:
6233   //   lwarx tmpDest, ptr
6234   //   add tmp, tmpDest, incr2
6235   //   andc tmp2, tmpDest, mask
6236   //   and tmp3, tmp, mask
6237   //   or tmp4, tmp3, tmp2
6238   //   stwcx. tmp4, ptr
6239   //   bne- loopMBB
6240   //   fallthrough --> exitMBB
6241   //   srw dest, tmpDest, shift
6242   if (ptrA != ZeroReg) {
6243     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6244     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6245       .addReg(ptrA).addReg(ptrB);
6246   } else {
6247     Ptr1Reg = ptrB;
6248   }
6249   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6250       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6251   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6252       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6253   if (is64bit)
6254     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6255       .addReg(Ptr1Reg).addImm(0).addImm(61);
6256   else
6257     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6258       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6259   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6260       .addReg(incr).addReg(ShiftReg);
6261   if (is8bit)
6262     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6263   else {
6264     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6265     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6266   }
6267   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6268       .addReg(Mask2Reg).addReg(ShiftReg);
6269
6270   BB = loopMBB;
6271   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6272     .addReg(ZeroReg).addReg(PtrReg);
6273   if (BinOpcode)
6274     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6275       .addReg(Incr2Reg).addReg(TmpDestReg);
6276   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6277     .addReg(TmpDestReg).addReg(MaskReg);
6278   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6279     .addReg(TmpReg).addReg(MaskReg);
6280   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6281     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6282   BuildMI(BB, dl, TII->get(PPC::STWCX))
6283     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6284   BuildMI(BB, dl, TII->get(PPC::BCC))
6285     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6286   BB->addSuccessor(loopMBB);
6287   BB->addSuccessor(exitMBB);
6288
6289   //  exitMBB:
6290   //   ...
6291   BB = exitMBB;
6292   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6293     .addReg(ShiftReg);
6294   return BB;
6295 }
6296
6297 llvm::MachineBasicBlock*
6298 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6299                                     MachineBasicBlock *MBB) const {
6300   DebugLoc DL = MI->getDebugLoc();
6301   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6302
6303   MachineFunction *MF = MBB->getParent();
6304   MachineRegisterInfo &MRI = MF->getRegInfo();
6305
6306   const BasicBlock *BB = MBB->getBasicBlock();
6307   MachineFunction::iterator I = MBB;
6308   ++I;
6309
6310   // Memory Reference
6311   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6312   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6313
6314   unsigned DstReg = MI->getOperand(0).getReg();
6315   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6316   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6317   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6318   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6319
6320   MVT PVT = getPointerTy();
6321   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6322          "Invalid Pointer Size!");
6323   // For v = setjmp(buf), we generate
6324   //
6325   // thisMBB:
6326   //  SjLjSetup mainMBB
6327   //  bl mainMBB
6328   //  v_restore = 1
6329   //  b sinkMBB
6330   //
6331   // mainMBB:
6332   //  buf[LabelOffset] = LR
6333   //  v_main = 0
6334   //
6335   // sinkMBB:
6336   //  v = phi(main, restore)
6337   //
6338
6339   MachineBasicBlock *thisMBB = MBB;
6340   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6341   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6342   MF->insert(I, mainMBB);
6343   MF->insert(I, sinkMBB);
6344
6345   MachineInstrBuilder MIB;
6346
6347   // Transfer the remainder of BB and its successor edges to sinkMBB.
6348   sinkMBB->splice(sinkMBB->begin(), MBB,
6349                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6350   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6351
6352   // Note that the structure of the jmp_buf used here is not compatible
6353   // with that used by libc, and is not designed to be. Specifically, it
6354   // stores only those 'reserved' registers that LLVM does not otherwise
6355   // understand how to spill. Also, by convention, by the time this
6356   // intrinsic is called, Clang has already stored the frame address in the
6357   // first slot of the buffer and stack address in the third. Following the
6358   // X86 target code, we'll store the jump address in the second slot. We also
6359   // need to save the TOC pointer (R2) to handle jumps between shared
6360   // libraries, and that will be stored in the fourth slot. The thread
6361   // identifier (R13) is not affected.
6362
6363   // thisMBB:
6364   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6365   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6366   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6367
6368   // Prepare IP either in reg.
6369   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6370   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6371   unsigned BufReg = MI->getOperand(1).getReg();
6372
6373   if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6374     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6375             .addReg(PPC::X2)
6376             .addImm(TOCOffset)
6377             .addReg(BufReg);
6378     MIB.setMemRefs(MMOBegin, MMOEnd);
6379   }
6380
6381   // Naked functions never have a base pointer, and so we use r1. For all
6382   // other functions, this decision must be delayed until during PEI.
6383   unsigned BaseReg;
6384   if (MF->getFunction()->getAttributes().hasAttribute(
6385           AttributeSet::FunctionIndex, Attribute::Naked))
6386     BaseReg = PPCSubTarget.isPPC64() ? PPC::X1 : PPC::R1;
6387   else
6388     BaseReg = PPCSubTarget.isPPC64() ? PPC::BP8 : PPC::BP;
6389
6390   MIB = BuildMI(*thisMBB, MI, DL,
6391                 TII->get(PPCSubTarget.isPPC64() ? PPC::STD : PPC::STW))
6392           .addReg(BaseReg)
6393           .addImm(BPOffset)
6394           .addReg(BufReg);
6395   MIB.setMemRefs(MMOBegin, MMOEnd);
6396
6397   // Setup
6398   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6399   const PPCRegisterInfo *TRI =
6400     static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6401   MIB.addRegMask(TRI->getNoPreservedMask());
6402
6403   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6404
6405   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6406           .addMBB(mainMBB);
6407   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6408
6409   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6410   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6411
6412   // mainMBB:
6413   //  mainDstReg = 0
6414   MIB = BuildMI(mainMBB, DL,
6415     TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6416
6417   // Store IP
6418   if (PPCSubTarget.isPPC64()) {
6419     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6420             .addReg(LabelReg)
6421             .addImm(LabelOffset)
6422             .addReg(BufReg);
6423   } else {
6424     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6425             .addReg(LabelReg)
6426             .addImm(LabelOffset)
6427             .addReg(BufReg);
6428   }
6429
6430   MIB.setMemRefs(MMOBegin, MMOEnd);
6431
6432   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6433   mainMBB->addSuccessor(sinkMBB);
6434
6435   // sinkMBB:
6436   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6437           TII->get(PPC::PHI), DstReg)
6438     .addReg(mainDstReg).addMBB(mainMBB)
6439     .addReg(restoreDstReg).addMBB(thisMBB);
6440
6441   MI->eraseFromParent();
6442   return sinkMBB;
6443 }
6444
6445 MachineBasicBlock *
6446 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6447                                      MachineBasicBlock *MBB) const {
6448   DebugLoc DL = MI->getDebugLoc();
6449   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6450
6451   MachineFunction *MF = MBB->getParent();
6452   MachineRegisterInfo &MRI = MF->getRegInfo();
6453
6454   // Memory Reference
6455   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6456   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6457
6458   MVT PVT = getPointerTy();
6459   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6460          "Invalid Pointer Size!");
6461
6462   const TargetRegisterClass *RC =
6463     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6464   unsigned Tmp = MRI.createVirtualRegister(RC);
6465   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6466   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6467   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6468   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 : PPC::R30;
6469
6470   MachineInstrBuilder MIB;
6471
6472   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6473   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6474   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6475   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6476
6477   unsigned BufReg = MI->getOperand(0).getReg();
6478
6479   // Reload FP (the jumped-to function may not have had a
6480   // frame pointer, and if so, then its r31 will be restored
6481   // as necessary).
6482   if (PVT == MVT::i64) {
6483     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6484             .addImm(0)
6485             .addReg(BufReg);
6486   } else {
6487     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6488             .addImm(0)
6489             .addReg(BufReg);
6490   }
6491   MIB.setMemRefs(MMOBegin, MMOEnd);
6492
6493   // Reload IP
6494   if (PVT == MVT::i64) {
6495     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6496             .addImm(LabelOffset)
6497             .addReg(BufReg);
6498   } else {
6499     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6500             .addImm(LabelOffset)
6501             .addReg(BufReg);
6502   }
6503   MIB.setMemRefs(MMOBegin, MMOEnd);
6504
6505   // Reload SP
6506   if (PVT == MVT::i64) {
6507     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6508             .addImm(SPOffset)
6509             .addReg(BufReg);
6510   } else {
6511     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6512             .addImm(SPOffset)
6513             .addReg(BufReg);
6514   }
6515   MIB.setMemRefs(MMOBegin, MMOEnd);
6516
6517   // Reload BP
6518   if (PVT == MVT::i64) {
6519     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6520             .addImm(BPOffset)
6521             .addReg(BufReg);
6522   } else {
6523     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6524             .addImm(BPOffset)
6525             .addReg(BufReg);
6526   }
6527   MIB.setMemRefs(MMOBegin, MMOEnd);
6528
6529   // Reload TOC
6530   if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6531     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6532             .addImm(TOCOffset)
6533             .addReg(BufReg);
6534
6535     MIB.setMemRefs(MMOBegin, MMOEnd);
6536   }
6537
6538   // Jump
6539   BuildMI(*MBB, MI, DL,
6540           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6541   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6542
6543   MI->eraseFromParent();
6544   return MBB;
6545 }
6546
6547 MachineBasicBlock *
6548 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6549                                                MachineBasicBlock *BB) const {
6550   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6551       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6552     return emitEHSjLjSetJmp(MI, BB);
6553   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6554              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6555     return emitEHSjLjLongJmp(MI, BB);
6556   }
6557
6558   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6559
6560   // To "insert" these instructions we actually have to insert their
6561   // control-flow patterns.
6562   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6563   MachineFunction::iterator It = BB;
6564   ++It;
6565
6566   MachineFunction *F = BB->getParent();
6567
6568   if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6569                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
6570                                  MI->getOpcode() == PPC::SELECT_I4 ||
6571                                  MI->getOpcode() == PPC::SELECT_I8)) {
6572     SmallVector<MachineOperand, 2> Cond;
6573     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6574         MI->getOpcode() == PPC::SELECT_CC_I8)
6575       Cond.push_back(MI->getOperand(4));
6576     else
6577       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6578     Cond.push_back(MI->getOperand(1));
6579
6580     DebugLoc dl = MI->getDebugLoc();
6581     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6582     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6583                       Cond, MI->getOperand(2).getReg(),
6584                       MI->getOperand(3).getReg());
6585   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6586              MI->getOpcode() == PPC::SELECT_CC_I8 ||
6587              MI->getOpcode() == PPC::SELECT_CC_F4 ||
6588              MI->getOpcode() == PPC::SELECT_CC_F8 ||
6589              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6590              MI->getOpcode() == PPC::SELECT_I4 ||
6591              MI->getOpcode() == PPC::SELECT_I8 ||
6592              MI->getOpcode() == PPC::SELECT_F4 ||
6593              MI->getOpcode() == PPC::SELECT_F8 ||
6594              MI->getOpcode() == PPC::SELECT_VRRC) {
6595     // The incoming instruction knows the destination vreg to set, the
6596     // condition code register to branch on, the true/false values to
6597     // select between, and a branch opcode to use.
6598
6599     //  thisMBB:
6600     //  ...
6601     //   TrueVal = ...
6602     //   cmpTY ccX, r1, r2
6603     //   bCC copy1MBB
6604     //   fallthrough --> copy0MBB
6605     MachineBasicBlock *thisMBB = BB;
6606     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6607     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6608     DebugLoc dl = MI->getDebugLoc();
6609     F->insert(It, copy0MBB);
6610     F->insert(It, sinkMBB);
6611
6612     // Transfer the remainder of BB and its successor edges to sinkMBB.
6613     sinkMBB->splice(sinkMBB->begin(), BB,
6614                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
6615     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6616
6617     // Next, add the true and fallthrough blocks as its successors.
6618     BB->addSuccessor(copy0MBB);
6619     BB->addSuccessor(sinkMBB);
6620
6621     if (MI->getOpcode() == PPC::SELECT_I4 ||
6622         MI->getOpcode() == PPC::SELECT_I8 ||
6623         MI->getOpcode() == PPC::SELECT_F4 ||
6624         MI->getOpcode() == PPC::SELECT_F8 ||
6625         MI->getOpcode() == PPC::SELECT_VRRC) {
6626       BuildMI(BB, dl, TII->get(PPC::BC))
6627         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6628     } else {
6629       unsigned SelectPred = MI->getOperand(4).getImm();
6630       BuildMI(BB, dl, TII->get(PPC::BCC))
6631         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6632     }
6633
6634     //  copy0MBB:
6635     //   %FalseValue = ...
6636     //   # fallthrough to sinkMBB
6637     BB = copy0MBB;
6638
6639     // Update machine-CFG edges
6640     BB->addSuccessor(sinkMBB);
6641
6642     //  sinkMBB:
6643     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6644     //  ...
6645     BB = sinkMBB;
6646     BuildMI(*BB, BB->begin(), dl,
6647             TII->get(PPC::PHI), MI->getOperand(0).getReg())
6648       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6649       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6650   }
6651   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6652     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6653   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6654     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6655   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6656     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6657   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6658     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6659
6660   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6661     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6662   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6663     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6664   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6665     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6666   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6667     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6668
6669   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6670     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6671   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6672     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6673   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6674     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6675   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6676     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6677
6678   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6679     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6680   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6681     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6682   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6683     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6684   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6685     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6686
6687   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6688     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6689   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6690     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6691   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6692     BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6693   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6694     BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6695
6696   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6697     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6698   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6699     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6700   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6701     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6702   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6703     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6704
6705   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6706     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6707   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6708     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6709   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6710     BB = EmitAtomicBinary(MI, BB, false, 0);
6711   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6712     BB = EmitAtomicBinary(MI, BB, true, 0);
6713
6714   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6715            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6716     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6717
6718     unsigned dest   = MI->getOperand(0).getReg();
6719     unsigned ptrA   = MI->getOperand(1).getReg();
6720     unsigned ptrB   = MI->getOperand(2).getReg();
6721     unsigned oldval = MI->getOperand(3).getReg();
6722     unsigned newval = MI->getOperand(4).getReg();
6723     DebugLoc dl     = MI->getDebugLoc();
6724
6725     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6726     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6727     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6728     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6729     F->insert(It, loop1MBB);
6730     F->insert(It, loop2MBB);
6731     F->insert(It, midMBB);
6732     F->insert(It, exitMBB);
6733     exitMBB->splice(exitMBB->begin(), BB,
6734                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
6735     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6736
6737     //  thisMBB:
6738     //   ...
6739     //   fallthrough --> loopMBB
6740     BB->addSuccessor(loop1MBB);
6741
6742     // loop1MBB:
6743     //   l[wd]arx dest, ptr
6744     //   cmp[wd] dest, oldval
6745     //   bne- midMBB
6746     // loop2MBB:
6747     //   st[wd]cx. newval, ptr
6748     //   bne- loopMBB
6749     //   b exitBB
6750     // midMBB:
6751     //   st[wd]cx. dest, ptr
6752     // exitBB:
6753     BB = loop1MBB;
6754     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6755       .addReg(ptrA).addReg(ptrB);
6756     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6757       .addReg(oldval).addReg(dest);
6758     BuildMI(BB, dl, TII->get(PPC::BCC))
6759       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6760     BB->addSuccessor(loop2MBB);
6761     BB->addSuccessor(midMBB);
6762
6763     BB = loop2MBB;
6764     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6765       .addReg(newval).addReg(ptrA).addReg(ptrB);
6766     BuildMI(BB, dl, TII->get(PPC::BCC))
6767       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6768     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6769     BB->addSuccessor(loop1MBB);
6770     BB->addSuccessor(exitMBB);
6771
6772     BB = midMBB;
6773     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6774       .addReg(dest).addReg(ptrA).addReg(ptrB);
6775     BB->addSuccessor(exitMBB);
6776
6777     //  exitMBB:
6778     //   ...
6779     BB = exitMBB;
6780   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6781              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6782     // We must use 64-bit registers for addresses when targeting 64-bit,
6783     // since we're actually doing arithmetic on them.  Other registers
6784     // can be 32-bit.
6785     bool is64bit = PPCSubTarget.isPPC64();
6786     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6787
6788     unsigned dest   = MI->getOperand(0).getReg();
6789     unsigned ptrA   = MI->getOperand(1).getReg();
6790     unsigned ptrB   = MI->getOperand(2).getReg();
6791     unsigned oldval = MI->getOperand(3).getReg();
6792     unsigned newval = MI->getOperand(4).getReg();
6793     DebugLoc dl     = MI->getDebugLoc();
6794
6795     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6796     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6797     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6798     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6799     F->insert(It, loop1MBB);
6800     F->insert(It, loop2MBB);
6801     F->insert(It, midMBB);
6802     F->insert(It, exitMBB);
6803     exitMBB->splice(exitMBB->begin(), BB,
6804                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
6805     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6806
6807     MachineRegisterInfo &RegInfo = F->getRegInfo();
6808     const TargetRegisterClass *RC =
6809       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6810                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6811     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6812     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6813     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6814     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6815     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6816     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6817     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6818     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6819     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6820     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6821     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6822     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6823     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6824     unsigned Ptr1Reg;
6825     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6826     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6827     //  thisMBB:
6828     //   ...
6829     //   fallthrough --> loopMBB
6830     BB->addSuccessor(loop1MBB);
6831
6832     // The 4-byte load must be aligned, while a char or short may be
6833     // anywhere in the word.  Hence all this nasty bookkeeping code.
6834     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6835     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6836     //   xori shift, shift1, 24 [16]
6837     //   rlwinm ptr, ptr1, 0, 0, 29
6838     //   slw newval2, newval, shift
6839     //   slw oldval2, oldval,shift
6840     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6841     //   slw mask, mask2, shift
6842     //   and newval3, newval2, mask
6843     //   and oldval3, oldval2, mask
6844     // loop1MBB:
6845     //   lwarx tmpDest, ptr
6846     //   and tmp, tmpDest, mask
6847     //   cmpw tmp, oldval3
6848     //   bne- midMBB
6849     // loop2MBB:
6850     //   andc tmp2, tmpDest, mask
6851     //   or tmp4, tmp2, newval3
6852     //   stwcx. tmp4, ptr
6853     //   bne- loop1MBB
6854     //   b exitBB
6855     // midMBB:
6856     //   stwcx. tmpDest, ptr
6857     // exitBB:
6858     //   srw dest, tmpDest, shift
6859     if (ptrA != ZeroReg) {
6860       Ptr1Reg = RegInfo.createVirtualRegister(RC);
6861       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6862         .addReg(ptrA).addReg(ptrB);
6863     } else {
6864       Ptr1Reg = ptrB;
6865     }
6866     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6867         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6868     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6869         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6870     if (is64bit)
6871       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6872         .addReg(Ptr1Reg).addImm(0).addImm(61);
6873     else
6874       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6875         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6876     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6877         .addReg(newval).addReg(ShiftReg);
6878     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6879         .addReg(oldval).addReg(ShiftReg);
6880     if (is8bit)
6881       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6882     else {
6883       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6884       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6885         .addReg(Mask3Reg).addImm(65535);
6886     }
6887     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6888         .addReg(Mask2Reg).addReg(ShiftReg);
6889     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6890         .addReg(NewVal2Reg).addReg(MaskReg);
6891     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6892         .addReg(OldVal2Reg).addReg(MaskReg);
6893
6894     BB = loop1MBB;
6895     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6896         .addReg(ZeroReg).addReg(PtrReg);
6897     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6898         .addReg(TmpDestReg).addReg(MaskReg);
6899     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6900         .addReg(TmpReg).addReg(OldVal3Reg);
6901     BuildMI(BB, dl, TII->get(PPC::BCC))
6902         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6903     BB->addSuccessor(loop2MBB);
6904     BB->addSuccessor(midMBB);
6905
6906     BB = loop2MBB;
6907     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6908         .addReg(TmpDestReg).addReg(MaskReg);
6909     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6910         .addReg(Tmp2Reg).addReg(NewVal3Reg);
6911     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6912         .addReg(ZeroReg).addReg(PtrReg);
6913     BuildMI(BB, dl, TII->get(PPC::BCC))
6914       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6915     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6916     BB->addSuccessor(loop1MBB);
6917     BB->addSuccessor(exitMBB);
6918
6919     BB = midMBB;
6920     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6921       .addReg(ZeroReg).addReg(PtrReg);
6922     BB->addSuccessor(exitMBB);
6923
6924     //  exitMBB:
6925     //   ...
6926     BB = exitMBB;
6927     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6928       .addReg(ShiftReg);
6929   } else if (MI->getOpcode() == PPC::FADDrtz) {
6930     // This pseudo performs an FADD with rounding mode temporarily forced
6931     // to round-to-zero.  We emit this via custom inserter since the FPSCR
6932     // is not modeled at the SelectionDAG level.
6933     unsigned Dest = MI->getOperand(0).getReg();
6934     unsigned Src1 = MI->getOperand(1).getReg();
6935     unsigned Src2 = MI->getOperand(2).getReg();
6936     DebugLoc dl   = MI->getDebugLoc();
6937
6938     MachineRegisterInfo &RegInfo = F->getRegInfo();
6939     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6940
6941     // Save FPSCR value.
6942     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6943
6944     // Set rounding mode to round-to-zero.
6945     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6946     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6947
6948     // Perform addition.
6949     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6950
6951     // Restore FPSCR value.
6952     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6953   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6954              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
6955              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6956              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
6957     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
6958                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
6959                       PPC::ANDIo8 : PPC::ANDIo;
6960     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
6961                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
6962
6963     MachineRegisterInfo &RegInfo = F->getRegInfo();
6964     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
6965                                                   &PPC::GPRCRegClass :
6966                                                   &PPC::G8RCRegClass);
6967
6968     DebugLoc dl   = MI->getDebugLoc();
6969     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
6970       .addReg(MI->getOperand(1).getReg()).addImm(1);
6971     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
6972             MI->getOperand(0).getReg())
6973       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
6974   } else {
6975     llvm_unreachable("Unexpected instr type to insert");
6976   }
6977
6978   MI->eraseFromParent();   // The pseudo instruction is gone now.
6979   return BB;
6980 }
6981
6982 //===----------------------------------------------------------------------===//
6983 // Target Optimization Hooks
6984 //===----------------------------------------------------------------------===//
6985
6986 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6987                                                DAGCombinerInfo &DCI) const {
6988   if (DCI.isAfterLegalizeVectorOps())
6989     return SDValue();
6990
6991   EVT VT = Op.getValueType();
6992
6993   if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6994       (VT == MVT::f64 && PPCSubTarget.hasFRE())  ||
6995       (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
6996       (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
6997
6998     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6999     // For the reciprocal, we need to find the zero of the function:
7000     //   F(X) = A X - 1 [which has a zero at X = 1/A]
7001     //     =>
7002     //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7003     //     does not require additional intermediate precision]
7004
7005     // Convergence is quadratic, so we essentially double the number of digits
7006     // correct after every iteration. The minimum architected relative
7007     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7008     // 23 digits and double has 52 digits.
7009     int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7010     if (VT.getScalarType() == MVT::f64)
7011       ++Iterations;
7012
7013     SelectionDAG &DAG = DCI.DAG;
7014     SDLoc dl(Op);
7015
7016     SDValue FPOne =
7017       DAG.getConstantFP(1.0, VT.getScalarType());
7018     if (VT.isVector()) {
7019       assert(VT.getVectorNumElements() == 4 &&
7020              "Unknown vector type");
7021       FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7022                           FPOne, FPOne, FPOne, FPOne);
7023     }
7024
7025     SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7026     DCI.AddToWorklist(Est.getNode());
7027
7028     // Newton iterations: Est = Est + Est (1 - Arg * Est)
7029     for (int i = 0; i < Iterations; ++i) {
7030       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7031       DCI.AddToWorklist(NewEst.getNode());
7032
7033       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7034       DCI.AddToWorklist(NewEst.getNode());
7035
7036       NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7037       DCI.AddToWorklist(NewEst.getNode());
7038
7039       Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7040       DCI.AddToWorklist(Est.getNode());
7041     }
7042
7043     return Est;
7044   }
7045
7046   return SDValue();
7047 }
7048
7049 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7050                                              DAGCombinerInfo &DCI) const {
7051   if (DCI.isAfterLegalizeVectorOps())
7052     return SDValue();
7053
7054   EVT VT = Op.getValueType();
7055
7056   if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
7057       (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE())  ||
7058       (VT == MVT::v4f32 && PPCSubTarget.hasAltivec()) ||
7059       (VT == MVT::v2f64 && PPCSubTarget.hasVSX())) {
7060
7061     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7062     // For the reciprocal sqrt, we need to find the zero of the function:
7063     //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7064     //     =>
7065     //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7066     // As a result, we precompute A/2 prior to the iteration loop.
7067
7068     // Convergence is quadratic, so we essentially double the number of digits
7069     // correct after every iteration. The minimum architected relative
7070     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7071     // 23 digits and double has 52 digits.
7072     int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
7073     if (VT.getScalarType() == MVT::f64)
7074       ++Iterations;
7075
7076     SelectionDAG &DAG = DCI.DAG;
7077     SDLoc dl(Op);
7078
7079     SDValue FPThreeHalves =
7080       DAG.getConstantFP(1.5, VT.getScalarType());
7081     if (VT.isVector()) {
7082       assert(VT.getVectorNumElements() == 4 &&
7083              "Unknown vector type");
7084       FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7085                                   FPThreeHalves, FPThreeHalves,
7086                                   FPThreeHalves, FPThreeHalves);
7087     }
7088
7089     SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7090     DCI.AddToWorklist(Est.getNode());
7091
7092     // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7093     // this entire sequence requires only one FP constant.
7094     SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7095     DCI.AddToWorklist(HalfArg.getNode());
7096
7097     HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7098     DCI.AddToWorklist(HalfArg.getNode());
7099
7100     // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7101     for (int i = 0; i < Iterations; ++i) {
7102       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7103       DCI.AddToWorklist(NewEst.getNode());
7104
7105       NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7106       DCI.AddToWorklist(NewEst.getNode());
7107
7108       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7109       DCI.AddToWorklist(NewEst.getNode());
7110
7111       Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7112       DCI.AddToWorklist(Est.getNode());
7113     }
7114
7115     return Est;
7116   }
7117
7118   return SDValue();
7119 }
7120
7121 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7122 // not enforce equality of the chain operands.
7123 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7124                             unsigned Bytes, int Dist,
7125                             SelectionDAG &DAG) {
7126   EVT VT = LS->getMemoryVT();
7127   if (VT.getSizeInBits() / 8 != Bytes)
7128     return false;
7129
7130   SDValue Loc = LS->getBasePtr();
7131   SDValue BaseLoc = Base->getBasePtr();
7132   if (Loc.getOpcode() == ISD::FrameIndex) {
7133     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7134       return false;
7135     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7136     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7137     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7138     int FS  = MFI->getObjectSize(FI);
7139     int BFS = MFI->getObjectSize(BFI);
7140     if (FS != BFS || FS != (int)Bytes) return false;
7141     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7142   }
7143
7144   // Handle X+C
7145   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7146       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7147     return true;
7148
7149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7150   const GlobalValue *GV1 = NULL;
7151   const GlobalValue *GV2 = NULL;
7152   int64_t Offset1 = 0;
7153   int64_t Offset2 = 0;
7154   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7155   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7156   if (isGA1 && isGA2 && GV1 == GV2)
7157     return Offset1 == (Offset2 + Dist*Bytes);
7158   return false;
7159 }
7160
7161 // Return true is there is a nearyby consecutive load to the one provided
7162 // (regardless of alignment). We search up and down the chain, looking though
7163 // token factors and other loads (but nothing else). As a result, a true
7164 // results indicates that it is safe to create a new consecutive load adjacent
7165 // to the load provided.
7166 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7167   SDValue Chain = LD->getChain();
7168   EVT VT = LD->getMemoryVT();
7169
7170   SmallSet<SDNode *, 16> LoadRoots;
7171   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7172   SmallSet<SDNode *, 16> Visited;
7173
7174   // First, search up the chain, branching to follow all token-factor operands.
7175   // If we find a consecutive load, then we're done, otherwise, record all
7176   // nodes just above the top-level loads and token factors.
7177   while (!Queue.empty()) {
7178     SDNode *ChainNext = Queue.pop_back_val();
7179     if (!Visited.insert(ChainNext))
7180       continue;
7181
7182     if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7183       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7184         return true;
7185
7186       if (!Visited.count(ChainLD->getChain().getNode()))
7187         Queue.push_back(ChainLD->getChain().getNode());
7188     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7189       for (SDNode::op_iterator O = ChainNext->op_begin(),
7190            OE = ChainNext->op_end(); O != OE; ++O)
7191         if (!Visited.count(O->getNode()))
7192           Queue.push_back(O->getNode());
7193     } else
7194       LoadRoots.insert(ChainNext);
7195   }
7196
7197   // Second, search down the chain, starting from the top-level nodes recorded
7198   // in the first phase. These top-level nodes are the nodes just above all
7199   // loads and token factors. Starting with their uses, recursively look though
7200   // all loads (just the chain uses) and token factors to find a consecutive
7201   // load.
7202   Visited.clear();
7203   Queue.clear();
7204
7205   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7206        IE = LoadRoots.end(); I != IE; ++I) {
7207     Queue.push_back(*I);
7208        
7209     while (!Queue.empty()) {
7210       SDNode *LoadRoot = Queue.pop_back_val();
7211       if (!Visited.insert(LoadRoot))
7212         continue;
7213
7214       if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7215         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7216           return true;
7217
7218       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7219            UE = LoadRoot->use_end(); UI != UE; ++UI)
7220         if (((isa<LoadSDNode>(*UI) &&
7221             cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7222             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7223           Queue.push_back(*UI);
7224     }
7225   }
7226
7227   return false;
7228 }
7229
7230 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7231                                                   DAGCombinerInfo &DCI) const {
7232   SelectionDAG &DAG = DCI.DAG;
7233   SDLoc dl(N);
7234
7235   assert(PPCSubTarget.useCRBits() &&
7236          "Expecting to be tracking CR bits");
7237   // If we're tracking CR bits, we need to be careful that we don't have:
7238   //   trunc(binary-ops(zext(x), zext(y)))
7239   // or
7240   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7241   // such that we're unnecessarily moving things into GPRs when it would be
7242   // better to keep them in CR bits.
7243
7244   // Note that trunc here can be an actual i1 trunc, or can be the effective
7245   // truncation that comes from a setcc or select_cc.
7246   if (N->getOpcode() == ISD::TRUNCATE &&
7247       N->getValueType(0) != MVT::i1)
7248     return SDValue();
7249
7250   if (N->getOperand(0).getValueType() != MVT::i32 &&
7251       N->getOperand(0).getValueType() != MVT::i64)
7252     return SDValue();
7253
7254   if (N->getOpcode() == ISD::SETCC ||
7255       N->getOpcode() == ISD::SELECT_CC) {
7256     // If we're looking at a comparison, then we need to make sure that the
7257     // high bits (all except for the first) don't matter the result.
7258     ISD::CondCode CC =
7259       cast<CondCodeSDNode>(N->getOperand(
7260         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7261     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7262
7263     if (ISD::isSignedIntSetCC(CC)) {
7264       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7265           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7266         return SDValue();
7267     } else if (ISD::isUnsignedIntSetCC(CC)) {
7268       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7269                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7270           !DAG.MaskedValueIsZero(N->getOperand(1),
7271                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7272         return SDValue();
7273     } else {
7274       // This is neither a signed nor an unsigned comparison, just make sure
7275       // that the high bits are equal.
7276       APInt Op1Zero, Op1One;
7277       APInt Op2Zero, Op2One;
7278       DAG.ComputeMaskedBits(N->getOperand(0), Op1Zero, Op1One);
7279       DAG.ComputeMaskedBits(N->getOperand(1), Op2Zero, Op2One);
7280
7281       // We don't really care about what is known about the first bit (if
7282       // anything), so clear it in all masks prior to comparing them.
7283       Op1Zero.clearBit(0); Op1One.clearBit(0);
7284       Op2Zero.clearBit(0); Op2One.clearBit(0);
7285
7286       if (Op1Zero != Op2Zero || Op1One != Op2One)
7287         return SDValue();
7288     }
7289   }
7290
7291   // We now know that the higher-order bits are irrelevant, we just need to
7292   // make sure that all of the intermediate operations are bit operations, and
7293   // all inputs are extensions.
7294   if (N->getOperand(0).getOpcode() != ISD::AND &&
7295       N->getOperand(0).getOpcode() != ISD::OR  &&
7296       N->getOperand(0).getOpcode() != ISD::XOR &&
7297       N->getOperand(0).getOpcode() != ISD::SELECT &&
7298       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7299       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7300       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7301       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7302       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7303     return SDValue();
7304
7305   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7306       N->getOperand(1).getOpcode() != ISD::AND &&
7307       N->getOperand(1).getOpcode() != ISD::OR  &&
7308       N->getOperand(1).getOpcode() != ISD::XOR &&
7309       N->getOperand(1).getOpcode() != ISD::SELECT &&
7310       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7311       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7312       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7313       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7314       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7315     return SDValue();
7316
7317   SmallVector<SDValue, 4> Inputs;
7318   SmallVector<SDValue, 8> BinOps, PromOps;
7319   SmallPtrSet<SDNode *, 16> Visited;
7320
7321   for (unsigned i = 0; i < 2; ++i) {
7322     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7323           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7324           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7325           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7326         isa<ConstantSDNode>(N->getOperand(i)))
7327       Inputs.push_back(N->getOperand(i));
7328     else
7329       BinOps.push_back(N->getOperand(i));
7330
7331     if (N->getOpcode() == ISD::TRUNCATE)
7332       break;
7333   }
7334
7335   // Visit all inputs, collect all binary operations (and, or, xor and
7336   // select) that are all fed by extensions. 
7337   while (!BinOps.empty()) {
7338     SDValue BinOp = BinOps.back();
7339     BinOps.pop_back();
7340
7341     if (!Visited.insert(BinOp.getNode()))
7342       continue;
7343
7344     PromOps.push_back(BinOp);
7345
7346     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7347       // The condition of the select is not promoted.
7348       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7349         continue;
7350       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7351         continue;
7352
7353       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7354             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7355             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7356            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7357           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7358         Inputs.push_back(BinOp.getOperand(i)); 
7359       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7360                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7361                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7362                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7363                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7364                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7365                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7366                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7367                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7368         BinOps.push_back(BinOp.getOperand(i));
7369       } else {
7370         // We have an input that is not an extension or another binary
7371         // operation; we'll abort this transformation.
7372         return SDValue();
7373       }
7374     }
7375   }
7376
7377   // Make sure that this is a self-contained cluster of operations (which
7378   // is not quite the same thing as saying that everything has only one
7379   // use).
7380   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7381     if (isa<ConstantSDNode>(Inputs[i]))
7382       continue;
7383
7384     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7385                               UE = Inputs[i].getNode()->use_end();
7386          UI != UE; ++UI) {
7387       SDNode *User = *UI;
7388       if (User != N && !Visited.count(User))
7389         return SDValue();
7390
7391       // Make sure that we're not going to promote the non-output-value
7392       // operand(s) or SELECT or SELECT_CC.
7393       // FIXME: Although we could sometimes handle this, and it does occur in
7394       // practice that one of the condition inputs to the select is also one of
7395       // the outputs, we currently can't deal with this.
7396       if (User->getOpcode() == ISD::SELECT) {
7397         if (User->getOperand(0) == Inputs[i])
7398           return SDValue();
7399       } else if (User->getOpcode() == ISD::SELECT_CC) {
7400         if (User->getOperand(0) == Inputs[i] ||
7401             User->getOperand(1) == Inputs[i])
7402           return SDValue();
7403       }
7404     }
7405   }
7406
7407   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7408     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7409                               UE = PromOps[i].getNode()->use_end();
7410          UI != UE; ++UI) {
7411       SDNode *User = *UI;
7412       if (User != N && !Visited.count(User))
7413         return SDValue();
7414
7415       // Make sure that we're not going to promote the non-output-value
7416       // operand(s) or SELECT or SELECT_CC.
7417       // FIXME: Although we could sometimes handle this, and it does occur in
7418       // practice that one of the condition inputs to the select is also one of
7419       // the outputs, we currently can't deal with this.
7420       if (User->getOpcode() == ISD::SELECT) {
7421         if (User->getOperand(0) == PromOps[i])
7422           return SDValue();
7423       } else if (User->getOpcode() == ISD::SELECT_CC) {
7424         if (User->getOperand(0) == PromOps[i] ||
7425             User->getOperand(1) == PromOps[i])
7426           return SDValue();
7427       }
7428     }
7429   }
7430
7431   // Replace all inputs with the extension operand.
7432   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7433     // Constants may have users outside the cluster of to-be-promoted nodes,
7434     // and so we need to replace those as we do the promotions.
7435     if (isa<ConstantSDNode>(Inputs[i]))
7436       continue;
7437     else
7438       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
7439   }
7440
7441   // Replace all operations (these are all the same, but have a different
7442   // (i1) return type). DAG.getNode will validate that the types of
7443   // a binary operator match, so go through the list in reverse so that
7444   // we've likely promoted both operands first. Any intermediate truncations or
7445   // extensions disappear.
7446   while (!PromOps.empty()) {
7447     SDValue PromOp = PromOps.back();
7448     PromOps.pop_back();
7449
7450     if (PromOp.getOpcode() == ISD::TRUNCATE ||
7451         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7452         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7453         PromOp.getOpcode() == ISD::ANY_EXTEND) {
7454       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7455           PromOp.getOperand(0).getValueType() != MVT::i1) {
7456         // The operand is not yet ready (see comment below).
7457         PromOps.insert(PromOps.begin(), PromOp);
7458         continue;
7459       }
7460
7461       SDValue RepValue = PromOp.getOperand(0);
7462       if (isa<ConstantSDNode>(RepValue))
7463         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7464
7465       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7466       continue;
7467     }
7468
7469     unsigned C;
7470     switch (PromOp.getOpcode()) {
7471     default:             C = 0; break;
7472     case ISD::SELECT:    C = 1; break;
7473     case ISD::SELECT_CC: C = 2; break;
7474     }
7475
7476     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7477          PromOp.getOperand(C).getValueType() != MVT::i1) ||
7478         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7479          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7480       // The to-be-promoted operands of this node have not yet been
7481       // promoted (this should be rare because we're going through the
7482       // list backward, but if one of the operands has several users in
7483       // this cluster of to-be-promoted nodes, it is possible).
7484       PromOps.insert(PromOps.begin(), PromOp);
7485       continue;
7486     }
7487
7488     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7489                                 PromOp.getNode()->op_end());
7490
7491     // If there are any constant inputs, make sure they're replaced now.
7492     for (unsigned i = 0; i < 2; ++i)
7493       if (isa<ConstantSDNode>(Ops[C+i]))
7494         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7495
7496     DAG.ReplaceAllUsesOfValueWith(PromOp,
7497       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1,
7498                   Ops.data(), Ops.size()));
7499   }
7500
7501   // Now we're left with the initial truncation itself.
7502   if (N->getOpcode() == ISD::TRUNCATE)
7503     return N->getOperand(0);
7504
7505   // Otherwise, this is a comparison. The operands to be compared have just
7506   // changed type (to i1), but everything else is the same.
7507   return SDValue(N, 0);
7508 }
7509
7510 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7511                                                   DAGCombinerInfo &DCI) const {
7512   SelectionDAG &DAG = DCI.DAG;
7513   SDLoc dl(N);
7514
7515   // If we're tracking CR bits, we need to be careful that we don't have:
7516   //   zext(binary-ops(trunc(x), trunc(y)))
7517   // or
7518   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7519   // such that we're unnecessarily moving things into CR bits that can more
7520   // efficiently stay in GPRs. Note that if we're not certain that the high
7521   // bits are set as required by the final extension, we still may need to do
7522   // some masking to get the proper behavior.
7523
7524   // This same functionality is important on PPC64 when dealing with
7525   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7526   // the return values of functions. Because it is so similar, it is handled
7527   // here as well.
7528
7529   if (N->getValueType(0) != MVT::i32 &&
7530       N->getValueType(0) != MVT::i64)
7531     return SDValue();
7532
7533   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7534         PPCSubTarget.useCRBits()) ||
7535        (N->getOperand(0).getValueType() == MVT::i32 &&
7536         PPCSubTarget.isPPC64())))
7537     return SDValue();
7538
7539   if (N->getOperand(0).getOpcode() != ISD::AND &&
7540       N->getOperand(0).getOpcode() != ISD::OR  &&
7541       N->getOperand(0).getOpcode() != ISD::XOR &&
7542       N->getOperand(0).getOpcode() != ISD::SELECT &&
7543       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7544     return SDValue();
7545
7546   SmallVector<SDValue, 4> Inputs;
7547   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7548   SmallPtrSet<SDNode *, 16> Visited;
7549
7550   // Visit all inputs, collect all binary operations (and, or, xor and
7551   // select) that are all fed by truncations. 
7552   while (!BinOps.empty()) {
7553     SDValue BinOp = BinOps.back();
7554     BinOps.pop_back();
7555
7556     if (!Visited.insert(BinOp.getNode()))
7557       continue;
7558
7559     PromOps.push_back(BinOp);
7560
7561     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7562       // The condition of the select is not promoted.
7563       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7564         continue;
7565       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7566         continue;
7567
7568       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7569           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7570         Inputs.push_back(BinOp.getOperand(i)); 
7571       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7572                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7573                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7574                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7575                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7576         BinOps.push_back(BinOp.getOperand(i));
7577       } else {
7578         // We have an input that is not a truncation or another binary
7579         // operation; we'll abort this transformation.
7580         return SDValue();
7581       }
7582     }
7583   }
7584
7585   // Make sure that this is a self-contained cluster of operations (which
7586   // is not quite the same thing as saying that everything has only one
7587   // use).
7588   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7589     if (isa<ConstantSDNode>(Inputs[i]))
7590       continue;
7591
7592     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7593                               UE = Inputs[i].getNode()->use_end();
7594          UI != UE; ++UI) {
7595       SDNode *User = *UI;
7596       if (User != N && !Visited.count(User))
7597         return SDValue();
7598
7599       // Make sure that we're not going to promote the non-output-value
7600       // operand(s) or SELECT or SELECT_CC.
7601       // FIXME: Although we could sometimes handle this, and it does occur in
7602       // practice that one of the condition inputs to the select is also one of
7603       // the outputs, we currently can't deal with this.
7604       if (User->getOpcode() == ISD::SELECT) {
7605         if (User->getOperand(0) == Inputs[i])
7606           return SDValue();
7607       } else if (User->getOpcode() == ISD::SELECT_CC) {
7608         if (User->getOperand(0) == Inputs[i] ||
7609             User->getOperand(1) == Inputs[i])
7610           return SDValue();
7611       }
7612     }
7613   }
7614
7615   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7616     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7617                               UE = PromOps[i].getNode()->use_end();
7618          UI != UE; ++UI) {
7619       SDNode *User = *UI;
7620       if (User != N && !Visited.count(User))
7621         return SDValue();
7622
7623       // Make sure that we're not going to promote the non-output-value
7624       // operand(s) or SELECT or SELECT_CC.
7625       // FIXME: Although we could sometimes handle this, and it does occur in
7626       // practice that one of the condition inputs to the select is also one of
7627       // the outputs, we currently can't deal with this.
7628       if (User->getOpcode() == ISD::SELECT) {
7629         if (User->getOperand(0) == PromOps[i])
7630           return SDValue();
7631       } else if (User->getOpcode() == ISD::SELECT_CC) {
7632         if (User->getOperand(0) == PromOps[i] ||
7633             User->getOperand(1) == PromOps[i])
7634           return SDValue();
7635       }
7636     }
7637   }
7638
7639   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7640   bool ReallyNeedsExt = false;
7641   if (N->getOpcode() != ISD::ANY_EXTEND) {
7642     // If all of the inputs are not already sign/zero extended, then
7643     // we'll still need to do that at the end.
7644     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7645       if (isa<ConstantSDNode>(Inputs[i]))
7646         continue;
7647
7648       unsigned OpBits =
7649         Inputs[i].getOperand(0).getValueSizeInBits();
7650       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7651
7652       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7653            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7654                                   APInt::getHighBitsSet(OpBits,
7655                                                         OpBits-PromBits))) ||
7656           (N->getOpcode() == ISD::SIGN_EXTEND &&
7657            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7658              (OpBits-(PromBits-1)))) {
7659         ReallyNeedsExt = true;
7660         break;
7661       }
7662     }
7663   }
7664
7665   // Replace all inputs, either with the truncation operand, or a
7666   // truncation or extension to the final output type.
7667   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7668     // Constant inputs need to be replaced with the to-be-promoted nodes that
7669     // use them because they might have users outside of the cluster of
7670     // promoted nodes.
7671     if (isa<ConstantSDNode>(Inputs[i]))
7672       continue;
7673
7674     SDValue InSrc = Inputs[i].getOperand(0);
7675     if (Inputs[i].getValueType() == N->getValueType(0))
7676       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7677     else if (N->getOpcode() == ISD::SIGN_EXTEND)
7678       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7679         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7680     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7681       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7682         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7683     else
7684       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7685         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7686   }
7687
7688   // Replace all operations (these are all the same, but have a different
7689   // (promoted) return type). DAG.getNode will validate that the types of
7690   // a binary operator match, so go through the list in reverse so that
7691   // we've likely promoted both operands first.
7692   while (!PromOps.empty()) {
7693     SDValue PromOp = PromOps.back();
7694     PromOps.pop_back();
7695
7696     unsigned C;
7697     switch (PromOp.getOpcode()) {
7698     default:             C = 0; break;
7699     case ISD::SELECT:    C = 1; break;
7700     case ISD::SELECT_CC: C = 2; break;
7701     }
7702
7703     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7704          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7705         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7706          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7707       // The to-be-promoted operands of this node have not yet been
7708       // promoted (this should be rare because we're going through the
7709       // list backward, but if one of the operands has several users in
7710       // this cluster of to-be-promoted nodes, it is possible).
7711       PromOps.insert(PromOps.begin(), PromOp);
7712       continue;
7713     }
7714
7715     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7716                                 PromOp.getNode()->op_end());
7717
7718     // If this node has constant inputs, then they'll need to be promoted here.
7719     for (unsigned i = 0; i < 2; ++i) {
7720       if (!isa<ConstantSDNode>(Ops[C+i]))
7721         continue;
7722       if (Ops[C+i].getValueType() == N->getValueType(0))
7723         continue;
7724
7725       if (N->getOpcode() == ISD::SIGN_EXTEND)
7726         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7727       else if (N->getOpcode() == ISD::ZERO_EXTEND)
7728         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7729       else
7730         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
7731     }
7732
7733     DAG.ReplaceAllUsesOfValueWith(PromOp,
7734       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0),
7735                   Ops.data(), Ops.size()));
7736   }
7737
7738   // Now we're left with the initial extension itself.
7739   if (!ReallyNeedsExt)
7740     return N->getOperand(0);
7741
7742   // To zero extend, just mask off everything except for the first bit (in the
7743   // i1 case).
7744   if (N->getOpcode() == ISD::ZERO_EXTEND)
7745     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
7746                        DAG.getConstant(APInt::getLowBitsSet(
7747                                          N->getValueSizeInBits(0), PromBits),
7748                                        N->getValueType(0)));
7749
7750   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
7751          "Invalid extension type");
7752   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
7753   SDValue ShiftCst =
7754     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
7755   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
7756                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
7757                                  N->getOperand(0), ShiftCst), ShiftCst);
7758 }
7759
7760 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
7761                                              DAGCombinerInfo &DCI) const {
7762   const TargetMachine &TM = getTargetMachine();
7763   SelectionDAG &DAG = DCI.DAG;
7764   SDLoc dl(N);
7765   switch (N->getOpcode()) {
7766   default: break;
7767   case PPCISD::SHL:
7768     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7769       if (C->isNullValue())   // 0 << V -> 0.
7770         return N->getOperand(0);
7771     }
7772     break;
7773   case PPCISD::SRL:
7774     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7775       if (C->isNullValue())   // 0 >>u V -> 0.
7776         return N->getOperand(0);
7777     }
7778     break;
7779   case PPCISD::SRA:
7780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7781       if (C->isNullValue() ||   //  0 >>s V -> 0.
7782           C->isAllOnesValue())    // -1 >>s V -> -1.
7783         return N->getOperand(0);
7784     }
7785     break;
7786   case ISD::SIGN_EXTEND:
7787   case ISD::ZERO_EXTEND:
7788   case ISD::ANY_EXTEND: 
7789     return DAGCombineExtBoolTrunc(N, DCI);
7790   case ISD::TRUNCATE:
7791   case ISD::SETCC:
7792   case ISD::SELECT_CC:
7793     return DAGCombineTruncBoolExt(N, DCI);
7794   case ISD::FDIV: {
7795     assert(TM.Options.UnsafeFPMath &&
7796            "Reciprocal estimates require UnsafeFPMath");
7797
7798     if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
7799       SDValue RV =
7800         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
7801       if (RV.getNode() != 0) {
7802         DCI.AddToWorklist(RV.getNode());
7803         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7804                            N->getOperand(0), RV);
7805       }
7806     } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
7807                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7808       SDValue RV =
7809         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7810                                  DCI);
7811       if (RV.getNode() != 0) {
7812         DCI.AddToWorklist(RV.getNode());
7813         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
7814                          N->getValueType(0), RV);
7815         DCI.AddToWorklist(RV.getNode());
7816         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7817                            N->getOperand(0), RV);
7818       }
7819     } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
7820                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
7821       SDValue RV =
7822         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
7823                                  DCI);
7824       if (RV.getNode() != 0) {
7825         DCI.AddToWorklist(RV.getNode());
7826         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
7827                          N->getValueType(0), RV,
7828                          N->getOperand(1).getOperand(1));
7829         DCI.AddToWorklist(RV.getNode());
7830         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7831                            N->getOperand(0), RV);
7832       }
7833     }
7834
7835     SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
7836     if (RV.getNode() != 0) {
7837       DCI.AddToWorklist(RV.getNode());
7838       return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
7839                          N->getOperand(0), RV);
7840     }
7841
7842     }
7843     break;
7844   case ISD::FSQRT: {
7845     assert(TM.Options.UnsafeFPMath &&
7846            "Reciprocal estimates require UnsafeFPMath");
7847
7848     // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
7849     // reciprocal sqrt.
7850     SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
7851     if (RV.getNode() != 0) {
7852       DCI.AddToWorklist(RV.getNode());
7853       RV = DAGCombineFastRecip(RV, DCI);
7854       if (RV.getNode() != 0) {
7855         // Unfortunately, RV is now NaN if the input was exactly 0. Select out
7856         // this case and force the answer to 0.
7857
7858         EVT VT = RV.getValueType();
7859
7860         SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
7861         if (VT.isVector()) {
7862           assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
7863           Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
7864         }
7865
7866         SDValue ZeroCmp =
7867           DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
7868                        N->getOperand(0), Zero, ISD::SETEQ);
7869         DCI.AddToWorklist(ZeroCmp.getNode());
7870         DCI.AddToWorklist(RV.getNode());
7871
7872         RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
7873                          ZeroCmp, Zero, RV);
7874         return RV;
7875       }
7876     }
7877
7878     }
7879     break;
7880   case ISD::SINT_TO_FP:
7881     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
7882       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
7883         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
7884         // We allow the src/dst to be either f32/f64, but the intermediate
7885         // type must be i64.
7886         if (N->getOperand(0).getValueType() == MVT::i64 &&
7887             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
7888           SDValue Val = N->getOperand(0).getOperand(0);
7889           if (Val.getValueType() == MVT::f32) {
7890             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7891             DCI.AddToWorklist(Val.getNode());
7892           }
7893
7894           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7895           DCI.AddToWorklist(Val.getNode());
7896           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7897           DCI.AddToWorklist(Val.getNode());
7898           if (N->getValueType(0) == MVT::f32) {
7899             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7900                               DAG.getIntPtrConstant(0));
7901             DCI.AddToWorklist(Val.getNode());
7902           }
7903           return Val;
7904         } else if (N->getOperand(0).getValueType() == MVT::i32) {
7905           // If the intermediate type is i32, we can avoid the load/store here
7906           // too.
7907         }
7908       }
7909     }
7910     break;
7911   case ISD::STORE:
7912     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7913     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7914         !cast<StoreSDNode>(N)->isTruncatingStore() &&
7915         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7916         N->getOperand(1).getValueType() == MVT::i32 &&
7917         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7918       SDValue Val = N->getOperand(1).getOperand(0);
7919       if (Val.getValueType() == MVT::f32) {
7920         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7921         DCI.AddToWorklist(Val.getNode());
7922       }
7923       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7924       DCI.AddToWorklist(Val.getNode());
7925
7926       SDValue Ops[] = {
7927         N->getOperand(0), Val, N->getOperand(2),
7928         DAG.getValueType(N->getOperand(1).getValueType())
7929       };
7930
7931       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7932               DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7933               cast<StoreSDNode>(N)->getMemoryVT(),
7934               cast<StoreSDNode>(N)->getMemOperand());
7935       DCI.AddToWorklist(Val.getNode());
7936       return Val;
7937     }
7938
7939     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7940     if (cast<StoreSDNode>(N)->isUnindexed() &&
7941         N->getOperand(1).getOpcode() == ISD::BSWAP &&
7942         N->getOperand(1).getNode()->hasOneUse() &&
7943         (N->getOperand(1).getValueType() == MVT::i32 ||
7944          N->getOperand(1).getValueType() == MVT::i16 ||
7945          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7946           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7947           N->getOperand(1).getValueType() == MVT::i64))) {
7948       SDValue BSwapOp = N->getOperand(1).getOperand(0);
7949       // Do an any-extend to 32-bits if this is a half-word input.
7950       if (BSwapOp.getValueType() == MVT::i16)
7951         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7952
7953       SDValue Ops[] = {
7954         N->getOperand(0), BSwapOp, N->getOperand(2),
7955         DAG.getValueType(N->getOperand(1).getValueType())
7956       };
7957       return
7958         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7959                                 Ops, array_lengthof(Ops),
7960                                 cast<StoreSDNode>(N)->getMemoryVT(),
7961                                 cast<StoreSDNode>(N)->getMemOperand());
7962     }
7963     break;
7964   case ISD::LOAD: {
7965     LoadSDNode *LD = cast<LoadSDNode>(N);
7966     EVT VT = LD->getValueType(0);
7967     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7968     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7969     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7970         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7971         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
7972          VT == MVT::v4i32 || VT == MVT::v4f32) &&
7973         LD->getAlignment() < ABIAlignment) {
7974       // This is a type-legal unaligned Altivec load.
7975       SDValue Chain = LD->getChain();
7976       SDValue Ptr = LD->getBasePtr();
7977
7978       // This implements the loading of unaligned vectors as described in
7979       // the venerable Apple Velocity Engine overview. Specifically:
7980       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7981       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7982       //
7983       // The general idea is to expand a sequence of one or more unaligned
7984       // loads into a alignment-based permutation-control instruction (lvsl),
7985       // a series of regular vector loads (which always truncate their
7986       // input address to an aligned address), and a series of permutations.
7987       // The results of these permutations are the requested loaded values.
7988       // The trick is that the last "extra" load is not taken from the address
7989       // you might suspect (sizeof(vector) bytes after the last requested
7990       // load), but rather sizeof(vector) - 1 bytes after the last
7991       // requested vector. The point of this is to avoid a page fault if the
7992       // base address happened to be aligned. This works because if the base
7993       // address is aligned, then adding less than a full vector length will
7994       // cause the last vector in the sequence to be (re)loaded. Otherwise,
7995       // the next vector will be fetched as you might suspect was necessary.
7996
7997       // We might be able to reuse the permutation generation from
7998       // a different base address offset from this one by an aligned amount.
7999       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8000       // optimization later.
8001       SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
8002                                           DAG, dl, MVT::v16i8);
8003
8004       // Refine the alignment of the original load (a "new" load created here
8005       // which was identical to the first except for the alignment would be
8006       // merged with the existing node regardless).
8007       MachineFunction &MF = DAG.getMachineFunction();
8008       MachineMemOperand *MMO =
8009         MF.getMachineMemOperand(LD->getPointerInfo(),
8010                                 LD->getMemOperand()->getFlags(),
8011                                 LD->getMemoryVT().getStoreSize(),
8012                                 ABIAlignment);
8013       LD->refineAlignment(MMO);
8014       SDValue BaseLoad = SDValue(LD, 0);
8015
8016       // Note that the value of IncOffset (which is provided to the next
8017       // load's pointer info offset value, and thus used to calculate the
8018       // alignment), and the value of IncValue (which is actually used to
8019       // increment the pointer value) are different! This is because we
8020       // require the next load to appear to be aligned, even though it
8021       // is actually offset from the base pointer by a lesser amount.
8022       int IncOffset = VT.getSizeInBits() / 8;
8023       int IncValue = IncOffset;
8024
8025       // Walk (both up and down) the chain looking for another load at the real
8026       // (aligned) offset (the alignment of the other load does not matter in
8027       // this case). If found, then do not use the offset reduction trick, as
8028       // that will prevent the loads from being later combined (as they would
8029       // otherwise be duplicates).
8030       if (!findConsecutiveLoad(LD, DAG))
8031         --IncValue;
8032
8033       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8034       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8035
8036       SDValue ExtraLoad =
8037         DAG.getLoad(VT, dl, Chain, Ptr,
8038                     LD->getPointerInfo().getWithOffset(IncOffset),
8039                     LD->isVolatile(), LD->isNonTemporal(),
8040                     LD->isInvariant(), ABIAlignment);
8041
8042       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8043         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8044
8045       if (BaseLoad.getValueType() != MVT::v4i32)
8046         BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8047
8048       if (ExtraLoad.getValueType() != MVT::v4i32)
8049         ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8050
8051       SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8052                                       BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8053
8054       if (VT != MVT::v4i32)
8055         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8056
8057       // Now we need to be really careful about how we update the users of the
8058       // original load. We cannot just call DCI.CombineTo (or
8059       // DAG.ReplaceAllUsesWith for that matter), because the load still has
8060       // uses created here (the permutation for example) that need to stay.
8061       SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8062       while (UI != UE) {
8063         SDUse &Use = UI.getUse();
8064         SDNode *User = *UI;
8065         // Note: BaseLoad is checked here because it might not be N, but a
8066         // bitcast of N.
8067         if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8068             User == TF.getNode() || Use.getResNo() > 1) {
8069           ++UI;
8070           continue;
8071         }
8072
8073         SDValue To = Use.getResNo() ? TF : Perm;
8074         ++UI;
8075
8076         SmallVector<SDValue, 8> Ops;
8077         for (SDNode::op_iterator O = User->op_begin(),
8078              OE = User->op_end(); O != OE; ++O) {
8079           if (*O == Use)
8080             Ops.push_back(To);
8081           else
8082             Ops.push_back(*O);
8083         }
8084
8085         DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
8086       }
8087
8088       return SDValue(N, 0);
8089     }
8090     }
8091     break;
8092   case ISD::INTRINSIC_WO_CHAIN:
8093     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
8094           Intrinsic::ppc_altivec_lvsl &&
8095         N->getOperand(1)->getOpcode() == ISD::ADD) {
8096       SDValue Add = N->getOperand(1);
8097
8098       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8099             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8100               Add.getValueType().getScalarType().getSizeInBits()))) {
8101         SDNode *BasePtr = Add->getOperand(0).getNode();
8102         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8103              UE = BasePtr->use_end(); UI != UE; ++UI) {
8104           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8105               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8106                 Intrinsic::ppc_altivec_lvsl) {
8107             // We've found another LVSL, and this address if an aligned
8108             // multiple of that one. The results will be the same, so use the
8109             // one we've just found instead.
8110
8111             return SDValue(*UI, 0);
8112           }
8113         }
8114       }
8115     }
8116
8117     break;
8118   case ISD::BSWAP:
8119     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8120     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8121         N->getOperand(0).hasOneUse() &&
8122         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8123          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8124           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8125           N->getValueType(0) == MVT::i64))) {
8126       SDValue Load = N->getOperand(0);
8127       LoadSDNode *LD = cast<LoadSDNode>(Load);
8128       // Create the byte-swapping load.
8129       SDValue Ops[] = {
8130         LD->getChain(),    // Chain
8131         LD->getBasePtr(),  // Ptr
8132         DAG.getValueType(N->getValueType(0)) // VT
8133       };
8134       SDValue BSLoad =
8135         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8136                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8137                                               MVT::i64 : MVT::i32, MVT::Other),
8138                                 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
8139
8140       // If this is an i16 load, insert the truncate.
8141       SDValue ResVal = BSLoad;
8142       if (N->getValueType(0) == MVT::i16)
8143         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8144
8145       // First, combine the bswap away.  This makes the value produced by the
8146       // load dead.
8147       DCI.CombineTo(N, ResVal);
8148
8149       // Next, combine the load away, we give it a bogus result value but a real
8150       // chain result.  The result value is dead because the bswap is dead.
8151       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8152
8153       // Return N so it doesn't get rechecked!
8154       return SDValue(N, 0);
8155     }
8156
8157     break;
8158   case PPCISD::VCMP: {
8159     // If a VCMPo node already exists with exactly the same operands as this
8160     // node, use its result instead of this node (VCMPo computes both a CR6 and
8161     // a normal output).
8162     //
8163     if (!N->getOperand(0).hasOneUse() &&
8164         !N->getOperand(1).hasOneUse() &&
8165         !N->getOperand(2).hasOneUse()) {
8166
8167       // Scan all of the users of the LHS, looking for VCMPo's that match.
8168       SDNode *VCMPoNode = 0;
8169
8170       SDNode *LHSN = N->getOperand(0).getNode();
8171       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8172            UI != E; ++UI)
8173         if (UI->getOpcode() == PPCISD::VCMPo &&
8174             UI->getOperand(1) == N->getOperand(1) &&
8175             UI->getOperand(2) == N->getOperand(2) &&
8176             UI->getOperand(0) == N->getOperand(0)) {
8177           VCMPoNode = *UI;
8178           break;
8179         }
8180
8181       // If there is no VCMPo node, or if the flag value has a single use, don't
8182       // transform this.
8183       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8184         break;
8185
8186       // Look at the (necessarily single) use of the flag value.  If it has a
8187       // chain, this transformation is more complex.  Note that multiple things
8188       // could use the value result, which we should ignore.
8189       SDNode *FlagUser = 0;
8190       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8191            FlagUser == 0; ++UI) {
8192         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8193         SDNode *User = *UI;
8194         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8195           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8196             FlagUser = User;
8197             break;
8198           }
8199         }
8200       }
8201
8202       // If the user is a MFOCRF instruction, we know this is safe.
8203       // Otherwise we give up for right now.
8204       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8205         return SDValue(VCMPoNode, 0);
8206     }
8207     break;
8208   }
8209   case ISD::BRCOND: {
8210     SDValue Cond = N->getOperand(1);
8211     SDValue Target = N->getOperand(2);
8212  
8213     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8214         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8215           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8216
8217       // We now need to make the intrinsic dead (it cannot be instruction
8218       // selected).
8219       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8220       assert(Cond.getNode()->hasOneUse() &&
8221              "Counter decrement has more than one use");
8222
8223       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8224                          N->getOperand(0), Target);
8225     }
8226   }
8227   break;
8228   case ISD::BR_CC: {
8229     // If this is a branch on an altivec predicate comparison, lower this so
8230     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8231     // lowering is done pre-legalize, because the legalizer lowers the predicate
8232     // compare down to code that is difficult to reassemble.
8233     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8234     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8235
8236     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8237     // value. If so, pass-through the AND to get to the intrinsic.
8238     if (LHS.getOpcode() == ISD::AND &&
8239         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8240         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8241           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8242         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8243         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8244           isZero())
8245       LHS = LHS.getOperand(0);
8246
8247     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8248         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8249           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8250         isa<ConstantSDNode>(RHS)) {
8251       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8252              "Counter decrement comparison is not EQ or NE");
8253
8254       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8255       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8256                     (CC == ISD::SETNE && !Val);
8257
8258       // We now need to make the intrinsic dead (it cannot be instruction
8259       // selected).
8260       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8261       assert(LHS.getNode()->hasOneUse() &&
8262              "Counter decrement has more than one use");
8263
8264       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8265                          N->getOperand(0), N->getOperand(4));
8266     }
8267
8268     int CompareOpc;
8269     bool isDot;
8270
8271     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8272         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8273         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8274       assert(isDot && "Can't compare against a vector result!");
8275
8276       // If this is a comparison against something other than 0/1, then we know
8277       // that the condition is never/always true.
8278       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8279       if (Val != 0 && Val != 1) {
8280         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8281           return N->getOperand(0);
8282         // Always !=, turn it into an unconditional branch.
8283         return DAG.getNode(ISD::BR, dl, MVT::Other,
8284                            N->getOperand(0), N->getOperand(4));
8285       }
8286
8287       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8288
8289       // Create the PPCISD altivec 'dot' comparison node.
8290       SDValue Ops[] = {
8291         LHS.getOperand(2),  // LHS of compare
8292         LHS.getOperand(3),  // RHS of compare
8293         DAG.getConstant(CompareOpc, MVT::i32)
8294       };
8295       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8296       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
8297
8298       // Unpack the result based on how the target uses it.
8299       PPC::Predicate CompOpc;
8300       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8301       default:  // Can't happen, don't crash on invalid number though.
8302       case 0:   // Branch on the value of the EQ bit of CR6.
8303         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8304         break;
8305       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8306         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8307         break;
8308       case 2:   // Branch on the value of the LT bit of CR6.
8309         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8310         break;
8311       case 3:   // Branch on the inverted value of the LT bit of CR6.
8312         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8313         break;
8314       }
8315
8316       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8317                          DAG.getConstant(CompOpc, MVT::i32),
8318                          DAG.getRegister(PPC::CR6, MVT::i32),
8319                          N->getOperand(4), CompNode.getValue(1));
8320     }
8321     break;
8322   }
8323   }
8324
8325   return SDValue();
8326 }
8327
8328 //===----------------------------------------------------------------------===//
8329 // Inline Assembly Support
8330 //===----------------------------------------------------------------------===//
8331
8332 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8333                                                        APInt &KnownZero,
8334                                                        APInt &KnownOne,
8335                                                        const SelectionDAG &DAG,
8336                                                        unsigned Depth) const {
8337   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8338   switch (Op.getOpcode()) {
8339   default: break;
8340   case PPCISD::LBRX: {
8341     // lhbrx is known to have the top bits cleared out.
8342     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8343       KnownZero = 0xFFFF0000;
8344     break;
8345   }
8346   case ISD::INTRINSIC_WO_CHAIN: {
8347     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8348     default: break;
8349     case Intrinsic::ppc_altivec_vcmpbfp_p:
8350     case Intrinsic::ppc_altivec_vcmpeqfp_p:
8351     case Intrinsic::ppc_altivec_vcmpequb_p:
8352     case Intrinsic::ppc_altivec_vcmpequh_p:
8353     case Intrinsic::ppc_altivec_vcmpequw_p:
8354     case Intrinsic::ppc_altivec_vcmpgefp_p:
8355     case Intrinsic::ppc_altivec_vcmpgtfp_p:
8356     case Intrinsic::ppc_altivec_vcmpgtsb_p:
8357     case Intrinsic::ppc_altivec_vcmpgtsh_p:
8358     case Intrinsic::ppc_altivec_vcmpgtsw_p:
8359     case Intrinsic::ppc_altivec_vcmpgtub_p:
8360     case Intrinsic::ppc_altivec_vcmpgtuh_p:
8361     case Intrinsic::ppc_altivec_vcmpgtuw_p:
8362       KnownZero = ~1U;  // All bits but the low one are known to be zero.
8363       break;
8364     }
8365   }
8366   }
8367 }
8368
8369
8370 /// getConstraintType - Given a constraint, return the type of
8371 /// constraint it is for this target.
8372 PPCTargetLowering::ConstraintType
8373 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8374   if (Constraint.size() == 1) {
8375     switch (Constraint[0]) {
8376     default: break;
8377     case 'b':
8378     case 'r':
8379     case 'f':
8380     case 'v':
8381     case 'y':
8382       return C_RegisterClass;
8383     case 'Z':
8384       // FIXME: While Z does indicate a memory constraint, it specifically
8385       // indicates an r+r address (used in conjunction with the 'y' modifier
8386       // in the replacement string). Currently, we're forcing the base
8387       // register to be r0 in the asm printer (which is interpreted as zero)
8388       // and forming the complete address in the second register. This is
8389       // suboptimal.
8390       return C_Memory;
8391     }
8392   } else if (Constraint == "wc") { // individual CR bits.
8393     return C_RegisterClass;
8394   } else if (Constraint == "wa" || Constraint == "wd" ||
8395              Constraint == "wf" || Constraint == "ws") {
8396     return C_RegisterClass; // VSX registers.
8397   }
8398   return TargetLowering::getConstraintType(Constraint);
8399 }
8400
8401 /// Examine constraint type and operand type and determine a weight value.
8402 /// This object must already have been set up with the operand type
8403 /// and the current alternative constraint selected.
8404 TargetLowering::ConstraintWeight
8405 PPCTargetLowering::getSingleConstraintMatchWeight(
8406     AsmOperandInfo &info, const char *constraint) const {
8407   ConstraintWeight weight = CW_Invalid;
8408   Value *CallOperandVal = info.CallOperandVal;
8409     // If we don't have a value, we can't do a match,
8410     // but allow it at the lowest weight.
8411   if (CallOperandVal == NULL)
8412     return CW_Default;
8413   Type *type = CallOperandVal->getType();
8414
8415   // Look at the constraint type.
8416   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8417     return CW_Register; // an individual CR bit.
8418   else if ((StringRef(constraint) == "wa" ||
8419             StringRef(constraint) == "wd" ||
8420             StringRef(constraint) == "wf") &&
8421            type->isVectorTy())
8422     return CW_Register;
8423   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8424     return CW_Register;
8425
8426   switch (*constraint) {
8427   default:
8428     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8429     break;
8430   case 'b':
8431     if (type->isIntegerTy())
8432       weight = CW_Register;
8433     break;
8434   case 'f':
8435     if (type->isFloatTy())
8436       weight = CW_Register;
8437     break;
8438   case 'd':
8439     if (type->isDoubleTy())
8440       weight = CW_Register;
8441     break;
8442   case 'v':
8443     if (type->isVectorTy())
8444       weight = CW_Register;
8445     break;
8446   case 'y':
8447     weight = CW_Register;
8448     break;
8449   case 'Z':
8450     weight = CW_Memory;
8451     break;
8452   }
8453   return weight;
8454 }
8455
8456 std::pair<unsigned, const TargetRegisterClass*>
8457 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8458                                                 MVT VT) const {
8459   if (Constraint.size() == 1) {
8460     // GCC RS6000 Constraint Letters
8461     switch (Constraint[0]) {
8462     case 'b':   // R1-R31
8463       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8464         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8465       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8466     case 'r':   // R0-R31
8467       if (VT == MVT::i64 && PPCSubTarget.isPPC64())
8468         return std::make_pair(0U, &PPC::G8RCRegClass);
8469       return std::make_pair(0U, &PPC::GPRCRegClass);
8470     case 'f':
8471       if (VT == MVT::f32 || VT == MVT::i32)
8472         return std::make_pair(0U, &PPC::F4RCRegClass);
8473       if (VT == MVT::f64 || VT == MVT::i64)
8474         return std::make_pair(0U, &PPC::F8RCRegClass);
8475       break;
8476     case 'v':
8477       return std::make_pair(0U, &PPC::VRRCRegClass);
8478     case 'y':   // crrc
8479       return std::make_pair(0U, &PPC::CRRCRegClass);
8480     }
8481   } else if (Constraint == "wc") { // an individual CR bit.
8482     return std::make_pair(0U, &PPC::CRBITRCRegClass);
8483   } else if (Constraint == "wa" || Constraint == "wd" ||
8484              Constraint == "wf" || Constraint == "ws") {
8485     return std::make_pair(0U, &PPC::VSRCRegClass);
8486   }
8487
8488   std::pair<unsigned, const TargetRegisterClass*> R =
8489     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8490
8491   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8492   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8493   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8494   // register.
8495   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8496   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8497   if (R.first && VT == MVT::i64 && PPCSubTarget.isPPC64() &&
8498       PPC::GPRCRegClass.contains(R.first)) {
8499     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8500     return std::make_pair(TRI->getMatchingSuperReg(R.first,
8501                             PPC::sub_32, &PPC::G8RCRegClass),
8502                           &PPC::G8RCRegClass);
8503   }
8504
8505   return R;
8506 }
8507
8508
8509 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8510 /// vector.  If it is invalid, don't add anything to Ops.
8511 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8512                                                      std::string &Constraint,
8513                                                      std::vector<SDValue>&Ops,
8514                                                      SelectionDAG &DAG) const {
8515   SDValue Result(0,0);
8516
8517   // Only support length 1 constraints.
8518   if (Constraint.length() > 1) return;
8519
8520   char Letter = Constraint[0];
8521   switch (Letter) {
8522   default: break;
8523   case 'I':
8524   case 'J':
8525   case 'K':
8526   case 'L':
8527   case 'M':
8528   case 'N':
8529   case 'O':
8530   case 'P': {
8531     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8532     if (!CST) return; // Must be an immediate to match.
8533     unsigned Value = CST->getZExtValue();
8534     switch (Letter) {
8535     default: llvm_unreachable("Unknown constraint letter!");
8536     case 'I':  // "I" is a signed 16-bit constant.
8537       if ((short)Value == (int)Value)
8538         Result = DAG.getTargetConstant(Value, Op.getValueType());
8539       break;
8540     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
8541     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
8542       if ((short)Value == 0)
8543         Result = DAG.getTargetConstant(Value, Op.getValueType());
8544       break;
8545     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
8546       if ((Value >> 16) == 0)
8547         Result = DAG.getTargetConstant(Value, Op.getValueType());
8548       break;
8549     case 'M':  // "M" is a constant that is greater than 31.
8550       if (Value > 31)
8551         Result = DAG.getTargetConstant(Value, Op.getValueType());
8552       break;
8553     case 'N':  // "N" is a positive constant that is an exact power of two.
8554       if ((int)Value > 0 && isPowerOf2_32(Value))
8555         Result = DAG.getTargetConstant(Value, Op.getValueType());
8556       break;
8557     case 'O':  // "O" is the constant zero.
8558       if (Value == 0)
8559         Result = DAG.getTargetConstant(Value, Op.getValueType());
8560       break;
8561     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
8562       if ((short)-Value == (int)-Value)
8563         Result = DAG.getTargetConstant(Value, Op.getValueType());
8564       break;
8565     }
8566     break;
8567   }
8568   }
8569
8570   if (Result.getNode()) {
8571     Ops.push_back(Result);
8572     return;
8573   }
8574
8575   // Handle standard constraint letters.
8576   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8577 }
8578
8579 // isLegalAddressingMode - Return true if the addressing mode represented
8580 // by AM is legal for this target, for a load/store of the specified type.
8581 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8582                                               Type *Ty) const {
8583   // FIXME: PPC does not allow r+i addressing modes for vectors!
8584
8585   // PPC allows a sign-extended 16-bit immediate field.
8586   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8587     return false;
8588
8589   // No global is ever allowed as a base.
8590   if (AM.BaseGV)
8591     return false;
8592
8593   // PPC only support r+r,
8594   switch (AM.Scale) {
8595   case 0:  // "r+i" or just "i", depending on HasBaseReg.
8596     break;
8597   case 1:
8598     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
8599       return false;
8600     // Otherwise we have r+r or r+i.
8601     break;
8602   case 2:
8603     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
8604       return false;
8605     // Allow 2*r as r+r.
8606     break;
8607   default:
8608     // No other scales are supported.
8609     return false;
8610   }
8611
8612   return true;
8613 }
8614
8615 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8616                                            SelectionDAG &DAG) const {
8617   MachineFunction &MF = DAG.getMachineFunction();
8618   MachineFrameInfo *MFI = MF.getFrameInfo();
8619   MFI->setReturnAddressIsTaken(true);
8620
8621   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8622     return SDValue();
8623
8624   SDLoc dl(Op);
8625   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8626
8627   // Make sure the function does not optimize away the store of the RA to
8628   // the stack.
8629   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8630   FuncInfo->setLRStoreRequired();
8631   bool isPPC64 = PPCSubTarget.isPPC64();
8632   bool isDarwinABI = PPCSubTarget.isDarwinABI();
8633
8634   if (Depth > 0) {
8635     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8636     SDValue Offset =
8637
8638       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8639                       isPPC64? MVT::i64 : MVT::i32);
8640     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8641                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8642                                    FrameAddr, Offset),
8643                        MachinePointerInfo(), false, false, false, 0);
8644   }
8645
8646   // Just load the return address off the stack.
8647   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8648   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8649                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8650 }
8651
8652 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8653                                           SelectionDAG &DAG) const {
8654   SDLoc dl(Op);
8655   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8656
8657   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8658   bool isPPC64 = PtrVT == MVT::i64;
8659
8660   MachineFunction &MF = DAG.getMachineFunction();
8661   MachineFrameInfo *MFI = MF.getFrameInfo();
8662   MFI->setFrameAddressIsTaken(true);
8663
8664   // Naked functions never have a frame pointer, and so we use r1. For all
8665   // other functions, this decision must be delayed until during PEI.
8666   unsigned FrameReg;
8667   if (MF.getFunction()->getAttributes().hasAttribute(
8668         AttributeSet::FunctionIndex, Attribute::Naked))
8669     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8670   else
8671     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8672
8673   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8674                                          PtrVT);
8675   while (Depth--)
8676     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8677                             FrameAddr, MachinePointerInfo(), false, false,
8678                             false, 0);
8679   return FrameAddr;
8680 }
8681
8682 bool
8683 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
8684   // The PowerPC target isn't yet aware of offsets.
8685   return false;
8686 }
8687
8688 /// getOptimalMemOpType - Returns the target specific optimal type for load
8689 /// and store operations as a result of memset, memcpy, and memmove
8690 /// lowering. If DstAlign is zero that means it's safe to destination
8691 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
8692 /// means there isn't a need to check it against alignment requirement,
8693 /// probably because the source does not need to be loaded. If 'IsMemset' is
8694 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
8695 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
8696 /// source is constant so it does not need to be loaded.
8697 /// It returns EVT::Other if the type should be determined using generic
8698 /// target-independent logic.
8699 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
8700                                            unsigned DstAlign, unsigned SrcAlign,
8701                                            bool IsMemset, bool ZeroMemset,
8702                                            bool MemcpyStrSrc,
8703                                            MachineFunction &MF) const {
8704   if (this->PPCSubTarget.isPPC64()) {
8705     return MVT::i64;
8706   } else {
8707     return MVT::i32;
8708   }
8709 }
8710
8711 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
8712                                                       unsigned,
8713                                                       bool *Fast) const {
8714   if (DisablePPCUnaligned)
8715     return false;
8716
8717   // PowerPC supports unaligned memory access for simple non-vector types.
8718   // Although accessing unaligned addresses is not as efficient as accessing
8719   // aligned addresses, it is generally more efficient than manual expansion,
8720   // and generally only traps for software emulation when crossing page
8721   // boundaries.
8722
8723   if (!VT.isSimple())
8724     return false;
8725
8726   if (VT.getSimpleVT().isVector()) {
8727     if (PPCSubTarget.hasVSX()) {
8728       if (VT != MVT::v2f64 && VT != MVT::v2i64)
8729         return false;
8730     } else {
8731       return false;
8732     }
8733   }
8734
8735   if (VT == MVT::ppcf128)
8736     return false;
8737
8738   if (Fast)
8739     *Fast = true;
8740
8741   return true;
8742 }
8743
8744 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8745   VT = VT.getScalarType();
8746
8747   if (!VT.isSimple())
8748     return false;
8749
8750   switch (VT.getSimpleVT().SimpleTy) {
8751   case MVT::f32:
8752   case MVT::f64:
8753     return true;
8754   default:
8755     break;
8756   }
8757
8758   return false;
8759 }
8760
8761 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
8762   if (DisableILPPref || PPCSubTarget.enableMachineScheduler())
8763     return TargetLowering::getSchedulingPreference(N);
8764
8765   return Sched::ILP;
8766 }
8767
8768 // Create a fast isel object.
8769 FastISel *
8770 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
8771                                   const TargetLibraryInfo *LibInfo) const {
8772   return PPC::createFastISel(FuncInfo, LibInfo);
8773 }