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