Change the generation of the vmuluwm instruction to be based on the MUL opcode.
[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 "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
50
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
53
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
56
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
59
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
61                                      const PPCSubtarget &STI)
62     : TargetLowering(TM), Subtarget(STI) {
63   // Use _setjmp/_longjmp instead of setjmp/longjmp.
64   setUseUnderscoreSetJmp(true);
65   setUseUnderscoreLongJmp(true);
66
67   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68   // arguments are at least 4/8 bytes aligned.
69   bool isPPC64 = Subtarget.isPPC64();
70   setMinStackArgumentAlignment(isPPC64 ? 8:4);
71
72   // Set up the register classes.
73   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76
77   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78   for (MVT VT : MVT::integer_valuetypes()) {
79     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
81   }
82
83   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84
85   // PowerPC has pre-inc load and store's.
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
93   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
100
101   if (Subtarget.useCRBits()) {
102     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103
104     if (isPPC64 || Subtarget.hasFPCVT()) {
105       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107                          isPPC64 ? MVT::i64 : MVT::i32);
108       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
110                          isPPC64 ? MVT::i64 : MVT::i32);
111     } else {
112       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
114     }
115
116     // PowerPC does not support direct load / store of condition registers
117     setOperationAction(ISD::LOAD, MVT::i1, Custom);
118     setOperationAction(ISD::STORE, MVT::i1, Custom);
119
120     // FIXME: Remove this once the ANDI glue bug is fixed:
121     if (ANDIGlueBug)
122       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123
124     for (MVT VT : MVT::integer_valuetypes()) {
125       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127       setTruncStoreAction(VT, MVT::i1, Expand);
128     }
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 && Subtarget.hasFRSQRTE() &&
180         Subtarget.hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget.hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
185         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 (Subtarget.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 (Subtarget.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 (MVT VT : MVT::vector_valuetypes()) {
404       // add/sub are legal for all supported vector VT's.
405       setOperationAction(ISD::ADD , VT, Legal);
406       setOperationAction(ISD::SUB , VT, Legal);
407
408       // Vector instructions introduced in P8
409       if (Subtarget.hasP8Altivec()) {
410         setOperationAction(ISD::CTPOP, VT, Legal);
411         setOperationAction(ISD::CTLZ, VT, Legal);
412       }
413       else {
414         setOperationAction(ISD::CTPOP, VT, Expand);
415         setOperationAction(ISD::CTLZ, VT, Expand);
416       }
417
418       // We promote all shuffles to v16i8.
419       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
420       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
421
422       // We promote all non-typed operations to v4i32.
423       setOperationAction(ISD::AND   , VT, Promote);
424       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
425       setOperationAction(ISD::OR    , VT, Promote);
426       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
427       setOperationAction(ISD::XOR   , VT, Promote);
428       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
429       setOperationAction(ISD::LOAD  , VT, Promote);
430       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
431       setOperationAction(ISD::SELECT, VT, Promote);
432       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
433       setOperationAction(ISD::STORE, VT, Promote);
434       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
435
436       // No other operations are legal.
437       setOperationAction(ISD::MUL , VT, Expand);
438       setOperationAction(ISD::SDIV, VT, Expand);
439       setOperationAction(ISD::SREM, VT, Expand);
440       setOperationAction(ISD::UDIV, VT, Expand);
441       setOperationAction(ISD::UREM, VT, Expand);
442       setOperationAction(ISD::FDIV, VT, Expand);
443       setOperationAction(ISD::FREM, VT, Expand);
444       setOperationAction(ISD::FNEG, VT, Expand);
445       setOperationAction(ISD::FSQRT, VT, Expand);
446       setOperationAction(ISD::FLOG, VT, Expand);
447       setOperationAction(ISD::FLOG10, VT, Expand);
448       setOperationAction(ISD::FLOG2, VT, Expand);
449       setOperationAction(ISD::FEXP, VT, Expand);
450       setOperationAction(ISD::FEXP2, VT, Expand);
451       setOperationAction(ISD::FSIN, VT, Expand);
452       setOperationAction(ISD::FCOS, VT, Expand);
453       setOperationAction(ISD::FABS, VT, Expand);
454       setOperationAction(ISD::FPOWI, VT, Expand);
455       setOperationAction(ISD::FFLOOR, VT, Expand);
456       setOperationAction(ISD::FCEIL,  VT, Expand);
457       setOperationAction(ISD::FTRUNC, VT, Expand);
458       setOperationAction(ISD::FRINT,  VT, Expand);
459       setOperationAction(ISD::FNEARBYINT, VT, Expand);
460       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
461       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
462       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
463       setOperationAction(ISD::MULHU, VT, Expand);
464       setOperationAction(ISD::MULHS, VT, Expand);
465       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
466       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
467       setOperationAction(ISD::UDIVREM, VT, Expand);
468       setOperationAction(ISD::SDIVREM, VT, Expand);
469       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
470       setOperationAction(ISD::FPOW, VT, Expand);
471       setOperationAction(ISD::BSWAP, VT, Expand);
472       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
473       setOperationAction(ISD::CTTZ, VT, Expand);
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
475       setOperationAction(ISD::VSELECT, VT, Expand);
476       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
477
478       for (MVT InnerVT : MVT::vector_valuetypes()) {
479         setTruncStoreAction(VT, InnerVT, Expand);
480         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
481         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
482         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
483       }
484     }
485
486     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
487     // with merges, splats, etc.
488     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
489
490     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
491     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
492     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
493     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
494     setOperationAction(ISD::SELECT, MVT::v4i32,
495                        Subtarget.useCRBits() ? Legal : Expand);
496     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
497     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
498     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
499     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
500     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
501     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
502     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
503     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
504     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
505
506     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
507     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
508     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
509     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
510
511     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
512     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
513
514     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
515       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
516       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
517     }
518
519     
520     if (Subtarget.hasP8Altivec()) 
521       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
522     else
523       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
524       
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
527
528     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
529     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
530
531     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
532     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
533     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
534     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
535
536     // Altivec does not contain unordered floating-point compare instructions
537     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
538     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
539     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
540     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
541
542     if (Subtarget.hasVSX()) {
543       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
544       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
545
546       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
547       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
548       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
549       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
550       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
551
552       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
553
554       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
555       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
556
557       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
558       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
559
560       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
561       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
562       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
563       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
564       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
565
566       // Share the Altivec comparison restrictions.
567       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
568       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
569       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
570       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
571
572       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
573       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
574
575       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
576
577       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
578
579       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
580       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
581
582       if (Subtarget.hasP8Altivec()) {
583         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
584         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
585         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
586
587         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
588       }
589       else {
590         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
591         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
592         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
593
594         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
595
596         // VSX v2i64 only supports non-arithmetic operations.
597         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
598         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
599       }
600
601       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
602       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
603       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
604       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
605
606       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
607
608       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
609       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
610       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
611       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
612
613       // Vector operation legalization checks the result type of
614       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
615       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
616       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
617       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
618       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
619
620       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
621     }
622
623     if (Subtarget.hasP8Altivec()) 
624       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
625   }
626
627   if (Subtarget.hasQPX()) {
628     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
629     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
630     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
631     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
632
633     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
634     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
635
636     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
637     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
638
639     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
640     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
641
642     if (!Subtarget.useCRBits())
643       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
644     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
645
646     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
647     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
648     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
649     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
650     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
651     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
652     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
653
654     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
655     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
656
657     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
658     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
659     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
660
661     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
662     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
663     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
664     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
665     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
666     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
667     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
668     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
669     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
670     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
671     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
672
673     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
674     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
675
676     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
677     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
678
679     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
680
681     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
682     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
683     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
684     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
685
686     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
687     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
688
689     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
690     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
691
692     if (!Subtarget.useCRBits())
693       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
694     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
695
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
697     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
698     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
699     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
701     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
702     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
703
704     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
705     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
706
707     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
708     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
709     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
710     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
711     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
712     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
713     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
714     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
715     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
716     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
717     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
718
719     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
720     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
721
722     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
723     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
724
725     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
726
727     setOperationAction(ISD::AND , MVT::v4i1, Legal);
728     setOperationAction(ISD::OR , MVT::v4i1, Legal);
729     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
730
731     if (!Subtarget.useCRBits())
732       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
733     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
734
735     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
736     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
737
738     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
739     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
740     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
741     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
742     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
743     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
744     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
745
746     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
747     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
748
749     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
750
751     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
752     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
753     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
754     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
755
756     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
757     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
758     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
759     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
760
761     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
762     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
763
764     // These need to set FE_INEXACT, and so cannot be vectorized here.
765     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
766     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
767
768     if (TM.Options.UnsafeFPMath) {
769       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
770       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
771
772       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
773       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
774     } else {
775       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
776       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
777
778       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
779       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
780     }
781   }
782
783   if (Subtarget.has64BitSupport())
784     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
785
786   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
787
788   if (!isPPC64) {
789     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
790     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
791   }
792
793   setBooleanContents(ZeroOrOneBooleanContent);
794
795   if (Subtarget.hasAltivec()) {
796     // Altivec instructions set fields to all zeros or all ones.
797     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
798   }
799
800   if (!isPPC64) {
801     // These libcalls are not available in 32-bit.
802     setLibcallName(RTLIB::SHL_I128, nullptr);
803     setLibcallName(RTLIB::SRL_I128, nullptr);
804     setLibcallName(RTLIB::SRA_I128, nullptr);
805   }
806
807   if (isPPC64) {
808     setStackPointerRegisterToSaveRestore(PPC::X1);
809     setExceptionPointerRegister(PPC::X3);
810     setExceptionSelectorRegister(PPC::X4);
811   } else {
812     setStackPointerRegisterToSaveRestore(PPC::R1);
813     setExceptionPointerRegister(PPC::R3);
814     setExceptionSelectorRegister(PPC::R4);
815   }
816
817   // We have target-specific dag combine patterns for the following nodes:
818   setTargetDAGCombine(ISD::SINT_TO_FP);
819   if (Subtarget.hasFPCVT())
820     setTargetDAGCombine(ISD::UINT_TO_FP);
821   setTargetDAGCombine(ISD::LOAD);
822   setTargetDAGCombine(ISD::STORE);
823   setTargetDAGCombine(ISD::BR_CC);
824   if (Subtarget.useCRBits())
825     setTargetDAGCombine(ISD::BRCOND);
826   setTargetDAGCombine(ISD::BSWAP);
827   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
828   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
829   setTargetDAGCombine(ISD::INTRINSIC_VOID);
830
831   setTargetDAGCombine(ISD::SIGN_EXTEND);
832   setTargetDAGCombine(ISD::ZERO_EXTEND);
833   setTargetDAGCombine(ISD::ANY_EXTEND);
834
835   if (Subtarget.useCRBits()) {
836     setTargetDAGCombine(ISD::TRUNCATE);
837     setTargetDAGCombine(ISD::SETCC);
838     setTargetDAGCombine(ISD::SELECT_CC);
839   }
840
841   // Use reciprocal estimates.
842   if (TM.Options.UnsafeFPMath) {
843     setTargetDAGCombine(ISD::FDIV);
844     setTargetDAGCombine(ISD::FSQRT);
845   }
846
847   // Darwin long double math library functions have $LDBL128 appended.
848   if (Subtarget.isDarwin()) {
849     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
850     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
851     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
852     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
853     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
854     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
855     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
856     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
857     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
858     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
859   }
860
861   // With 32 condition bits, we don't need to sink (and duplicate) compares
862   // aggressively in CodeGenPrep.
863   if (Subtarget.useCRBits()) {
864     setHasMultipleConditionRegisters();
865     setJumpIsExpensive();
866   }
867
868   setMinFunctionAlignment(2);
869   if (Subtarget.isDarwin())
870     setPrefFunctionAlignment(4);
871
872   switch (Subtarget.getDarwinDirective()) {
873   default: break;
874   case PPC::DIR_970:
875   case PPC::DIR_A2:
876   case PPC::DIR_E500mc:
877   case PPC::DIR_E5500:
878   case PPC::DIR_PWR4:
879   case PPC::DIR_PWR5:
880   case PPC::DIR_PWR5X:
881   case PPC::DIR_PWR6:
882   case PPC::DIR_PWR6X:
883   case PPC::DIR_PWR7:
884   case PPC::DIR_PWR8:
885     setPrefFunctionAlignment(4);
886     setPrefLoopAlignment(4);
887     break;
888   }
889
890   setInsertFencesForAtomic(true);
891
892   if (Subtarget.enableMachineScheduler())
893     setSchedulingPreference(Sched::Source);
894   else
895     setSchedulingPreference(Sched::Hybrid);
896
897   computeRegisterProperties(STI.getRegisterInfo());
898
899   // The Freescale cores do better with aggressive inlining of memcpy and
900   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
901   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
902       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
903     MaxStoresPerMemset = 32;
904     MaxStoresPerMemsetOptSize = 16;
905     MaxStoresPerMemcpy = 32;
906     MaxStoresPerMemcpyOptSize = 8;
907     MaxStoresPerMemmove = 32;
908     MaxStoresPerMemmoveOptSize = 8;
909   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
910     // The A2 also benefits from (very) aggressive inlining of memcpy and
911     // friends. The overhead of a the function call, even when warm, can be
912     // over one hundred cycles.
913     MaxStoresPerMemset = 128;
914     MaxStoresPerMemcpy = 128;
915     MaxStoresPerMemmove = 128;
916   }
917 }
918
919 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
920 /// the desired ByVal argument alignment.
921 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
922                              unsigned MaxMaxAlign) {
923   if (MaxAlign == MaxMaxAlign)
924     return;
925   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
926     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
927       MaxAlign = 32;
928     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
929       MaxAlign = 16;
930   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
931     unsigned EltAlign = 0;
932     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
933     if (EltAlign > MaxAlign)
934       MaxAlign = EltAlign;
935   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
936     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
937       unsigned EltAlign = 0;
938       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
939       if (EltAlign > MaxAlign)
940         MaxAlign = EltAlign;
941       if (MaxAlign == MaxMaxAlign)
942         break;
943     }
944   }
945 }
946
947 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
948 /// function arguments in the caller parameter area.
949 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
950   // Darwin passes everything on 4 byte boundary.
951   if (Subtarget.isDarwin())
952     return 4;
953
954   // 16byte and wider vectors are passed on 16byte boundary.
955   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
956   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
957   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
958     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
959   return Align;
960 }
961
962 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
963   switch (Opcode) {
964   default: return nullptr;
965   case PPCISD::FSEL:            return "PPCISD::FSEL";
966   case PPCISD::FCFID:           return "PPCISD::FCFID";
967   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
968   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
969   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
970   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
971   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
972   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
973   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
974   case PPCISD::FRE:             return "PPCISD::FRE";
975   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
976   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
977   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
978   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
979   case PPCISD::VPERM:           return "PPCISD::VPERM";
980   case PPCISD::CMPB:            return "PPCISD::CMPB";
981   case PPCISD::Hi:              return "PPCISD::Hi";
982   case PPCISD::Lo:              return "PPCISD::Lo";
983   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
984   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
985   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
986   case PPCISD::SRL:             return "PPCISD::SRL";
987   case PPCISD::SRA:             return "PPCISD::SRA";
988   case PPCISD::SHL:             return "PPCISD::SHL";
989   case PPCISD::CALL:            return "PPCISD::CALL";
990   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
991   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
992   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
993   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
994   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
995   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
996   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
997   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
998   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
999   case PPCISD::VCMP:            return "PPCISD::VCMP";
1000   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1001   case PPCISD::LBRX:            return "PPCISD::LBRX";
1002   case PPCISD::STBRX:           return "PPCISD::STBRX";
1003   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1004   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1005   case PPCISD::LARX:            return "PPCISD::LARX";
1006   case PPCISD::STCX:            return "PPCISD::STCX";
1007   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1008   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1009   case PPCISD::BDZ:             return "PPCISD::BDZ";
1010   case PPCISD::MFFS:            return "PPCISD::MFFS";
1011   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1012   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1013   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1014   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1015   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1016   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1017   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1018   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1019   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1020   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1021   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1022   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1023   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1024   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1025   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1026   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1027   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1028   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1029   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1030   case PPCISD::SC:              return "PPCISD::SC";
1031   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1032   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1033   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1034   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1035   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1036   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1037   }
1038 }
1039
1040 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1041   if (!VT.isVector())
1042     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1043
1044   if (Subtarget.hasQPX())
1045     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1046
1047   return VT.changeVectorElementTypeToInteger();
1048 }
1049
1050 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1051   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1052   return true;
1053 }
1054
1055 //===----------------------------------------------------------------------===//
1056 // Node matching predicates, for use by the tblgen matching code.
1057 //===----------------------------------------------------------------------===//
1058
1059 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1060 static bool isFloatingPointZero(SDValue Op) {
1061   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1062     return CFP->getValueAPF().isZero();
1063   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1064     // Maybe this has already been legalized into the constant pool?
1065     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1066       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1067         return CFP->getValueAPF().isZero();
1068   }
1069   return false;
1070 }
1071
1072 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1073 /// true if Op is undef or if it matches the specified value.
1074 static bool isConstantOrUndef(int Op, int Val) {
1075   return Op < 0 || Op == Val;
1076 }
1077
1078 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1079 /// VPKUHUM instruction.
1080 /// The ShuffleKind distinguishes between big-endian operations with
1081 /// two different inputs (0), either-endian operations with two identical
1082 /// inputs (1), and little-endian operantion with two different inputs (2).
1083 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1084 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1085                                SelectionDAG &DAG) {
1086   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1087   if (ShuffleKind == 0) {
1088     if (IsLE)
1089       return false;
1090     for (unsigned i = 0; i != 16; ++i)
1091       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1092         return false;
1093   } else if (ShuffleKind == 2) {
1094     if (!IsLE)
1095       return false;
1096     for (unsigned i = 0; i != 16; ++i)
1097       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1098         return false;
1099   } else if (ShuffleKind == 1) {
1100     unsigned j = IsLE ? 0 : 1;
1101     for (unsigned i = 0; i != 8; ++i)
1102       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1103           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1104         return false;
1105   }
1106   return true;
1107 }
1108
1109 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1110 /// VPKUWUM instruction.
1111 /// The ShuffleKind distinguishes between big-endian operations with
1112 /// two different inputs (0), either-endian operations with two identical
1113 /// inputs (1), and little-endian operantion with two different inputs (2).
1114 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1115 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1116                                SelectionDAG &DAG) {
1117   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1118   if (ShuffleKind == 0) {
1119     if (IsLE)
1120       return false;
1121     for (unsigned i = 0; i != 16; i += 2)
1122       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1123           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1124         return false;
1125   } else if (ShuffleKind == 2) {
1126     if (!IsLE)
1127       return false;
1128     for (unsigned i = 0; i != 16; i += 2)
1129       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1130           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1131         return false;
1132   } else if (ShuffleKind == 1) {
1133     unsigned j = IsLE ? 0 : 2;
1134     for (unsigned i = 0; i != 8; i += 2)
1135       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1136           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1137           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1138           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1139         return false;
1140   }
1141   return true;
1142 }
1143
1144 /// isVMerge - Common function, used to match vmrg* shuffles.
1145 ///
1146 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1147                      unsigned LHSStart, unsigned RHSStart) {
1148   if (N->getValueType(0) != MVT::v16i8)
1149     return false;
1150   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1151          "Unsupported merge size!");
1152
1153   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1154     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1155       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1156                              LHSStart+j+i*UnitSize) ||
1157           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1158                              RHSStart+j+i*UnitSize))
1159         return false;
1160     }
1161   return true;
1162 }
1163
1164 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1165 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1166 /// The ShuffleKind distinguishes between big-endian merges with two 
1167 /// different inputs (0), either-endian merges with two identical inputs (1),
1168 /// and little-endian merges with two different inputs (2).  For the latter,
1169 /// the input operands are swapped (see PPCInstrAltivec.td).
1170 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1171                              unsigned ShuffleKind, SelectionDAG &DAG) {
1172   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1173     if (ShuffleKind == 1) // unary
1174       return isVMerge(N, UnitSize, 0, 0);
1175     else if (ShuffleKind == 2) // swapped
1176       return isVMerge(N, UnitSize, 0, 16);
1177     else
1178       return false;
1179   } else {
1180     if (ShuffleKind == 1) // unary
1181       return isVMerge(N, UnitSize, 8, 8);
1182     else if (ShuffleKind == 0) // normal
1183       return isVMerge(N, UnitSize, 8, 24);
1184     else
1185       return false;
1186   }
1187 }
1188
1189 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1190 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1191 /// The ShuffleKind distinguishes between big-endian merges with two 
1192 /// different inputs (0), either-endian merges with two identical inputs (1),
1193 /// and little-endian merges with two different inputs (2).  For the latter,
1194 /// the input operands are swapped (see PPCInstrAltivec.td).
1195 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1196                              unsigned ShuffleKind, SelectionDAG &DAG) {
1197   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1198     if (ShuffleKind == 1) // unary
1199       return isVMerge(N, UnitSize, 8, 8);
1200     else if (ShuffleKind == 2) // swapped
1201       return isVMerge(N, UnitSize, 8, 24);
1202     else
1203       return false;
1204   } else {
1205     if (ShuffleKind == 1) // unary
1206       return isVMerge(N, UnitSize, 0, 0);
1207     else if (ShuffleKind == 0) // normal
1208       return isVMerge(N, UnitSize, 0, 16);
1209     else
1210       return false;
1211   }
1212 }
1213
1214
1215 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1216 /// amount, otherwise return -1.
1217 /// The ShuffleKind distinguishes between big-endian operations with two 
1218 /// different inputs (0), either-endian operations with two identical inputs
1219 /// (1), and little-endian operations with two different inputs (2).  For the
1220 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1221 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1222                              SelectionDAG &DAG) {
1223   if (N->getValueType(0) != MVT::v16i8)
1224     return -1;
1225
1226   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1227
1228   // Find the first non-undef value in the shuffle mask.
1229   unsigned i;
1230   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1231     /*search*/;
1232
1233   if (i == 16) return -1;  // all undef.
1234
1235   // Otherwise, check to see if the rest of the elements are consecutively
1236   // numbered from this value.
1237   unsigned ShiftAmt = SVOp->getMaskElt(i);
1238   if (ShiftAmt < i) return -1;
1239
1240   ShiftAmt -= i;
1241   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1242
1243   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1244     // Check the rest of the elements to see if they are consecutive.
1245     for (++i; i != 16; ++i)
1246       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1247         return -1;
1248   } else if (ShuffleKind == 1) {
1249     // Check the rest of the elements to see if they are consecutive.
1250     for (++i; i != 16; ++i)
1251       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1252         return -1;
1253   } else
1254     return -1;
1255
1256   if (ShuffleKind == 2 && isLE)
1257     ShiftAmt = 16 - ShiftAmt;
1258
1259   return ShiftAmt;
1260 }
1261
1262 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1263 /// specifies a splat of a single element that is suitable for input to
1264 /// VSPLTB/VSPLTH/VSPLTW.
1265 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1266   assert(N->getValueType(0) == MVT::v16i8 &&
1267          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1268
1269   // This is a splat operation if each element of the permute is the same, and
1270   // if the value doesn't reference the second vector.
1271   unsigned ElementBase = N->getMaskElt(0);
1272
1273   // FIXME: Handle UNDEF elements too!
1274   if (ElementBase >= 16)
1275     return false;
1276
1277   // Check that the indices are consecutive, in the case of a multi-byte element
1278   // splatted with a v16i8 mask.
1279   for (unsigned i = 1; i != EltSize; ++i)
1280     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1281       return false;
1282
1283   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1284     if (N->getMaskElt(i) < 0) continue;
1285     for (unsigned j = 0; j != EltSize; ++j)
1286       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1287         return false;
1288   }
1289   return true;
1290 }
1291
1292 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1293 /// are -0.0.
1294 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1295   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1296
1297   APInt APVal, APUndef;
1298   unsigned BitSize;
1299   bool HasAnyUndefs;
1300
1301   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1302     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1303       return CFP->getValueAPF().isNegZero();
1304
1305   return false;
1306 }
1307
1308 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1309 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1310 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1311                                 SelectionDAG &DAG) {
1312   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1313   assert(isSplatShuffleMask(SVOp, EltSize));
1314   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1315     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1316   else
1317     return SVOp->getMaskElt(0) / EltSize;
1318 }
1319
1320 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1321 /// by using a vspltis[bhw] instruction of the specified element size, return
1322 /// the constant being splatted.  The ByteSize field indicates the number of
1323 /// bytes of each element [124] -> [bhw].
1324 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1325   SDValue OpVal(nullptr, 0);
1326
1327   // If ByteSize of the splat is bigger than the element size of the
1328   // build_vector, then we have a case where we are checking for a splat where
1329   // multiple elements of the buildvector are folded together into a single
1330   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1331   unsigned EltSize = 16/N->getNumOperands();
1332   if (EltSize < ByteSize) {
1333     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1334     SDValue UniquedVals[4];
1335     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1336
1337     // See if all of the elements in the buildvector agree across.
1338     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1339       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1340       // If the element isn't a constant, bail fully out.
1341       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1342
1343
1344       if (!UniquedVals[i&(Multiple-1)].getNode())
1345         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1346       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1347         return SDValue();  // no match.
1348     }
1349
1350     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1351     // either constant or undef values that are identical for each chunk.  See
1352     // if these chunks can form into a larger vspltis*.
1353
1354     // Check to see if all of the leading entries are either 0 or -1.  If
1355     // neither, then this won't fit into the immediate field.
1356     bool LeadingZero = true;
1357     bool LeadingOnes = true;
1358     for (unsigned i = 0; i != Multiple-1; ++i) {
1359       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1360
1361       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1362       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1363     }
1364     // Finally, check the least significant entry.
1365     if (LeadingZero) {
1366       if (!UniquedVals[Multiple-1].getNode())
1367         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1368       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1369       if (Val < 16)
1370         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1371     }
1372     if (LeadingOnes) {
1373       if (!UniquedVals[Multiple-1].getNode())
1374         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1375       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1376       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1377         return DAG.getTargetConstant(Val, MVT::i32);
1378     }
1379
1380     return SDValue();
1381   }
1382
1383   // Check to see if this buildvec has a single non-undef value in its elements.
1384   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1385     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1386     if (!OpVal.getNode())
1387       OpVal = N->getOperand(i);
1388     else if (OpVal != N->getOperand(i))
1389       return SDValue();
1390   }
1391
1392   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1393
1394   unsigned ValSizeInBytes = EltSize;
1395   uint64_t Value = 0;
1396   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1397     Value = CN->getZExtValue();
1398   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1399     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1400     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1401   }
1402
1403   // If the splat value is larger than the element value, then we can never do
1404   // this splat.  The only case that we could fit the replicated bits into our
1405   // immediate field for would be zero, and we prefer to use vxor for it.
1406   if (ValSizeInBytes < ByteSize) return SDValue();
1407
1408   // If the element value is larger than the splat value, cut it in half and
1409   // check to see if the two halves are equal.  Continue doing this until we
1410   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1411   while (ValSizeInBytes > ByteSize) {
1412     ValSizeInBytes >>= 1;
1413
1414     // If the top half equals the bottom half, we're still ok.
1415     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1416          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1417       return SDValue();
1418   }
1419
1420   // Properly sign extend the value.
1421   int MaskVal = SignExtend32(Value, ByteSize * 8);
1422
1423   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1424   if (MaskVal == 0) return SDValue();
1425
1426   // Finally, if this value fits in a 5 bit sext field, return it
1427   if (SignExtend32<5>(MaskVal) == MaskVal)
1428     return DAG.getTargetConstant(MaskVal, MVT::i32);
1429   return SDValue();
1430 }
1431
1432 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1433 /// amount, otherwise return -1.
1434 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1435   EVT VT = N->getValueType(0);
1436   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1437     return -1;
1438
1439   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1440
1441   // Find the first non-undef value in the shuffle mask.
1442   unsigned i;
1443   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1444     /*search*/;
1445
1446   if (i == 4) return -1;  // all undef.
1447
1448   // Otherwise, check to see if the rest of the elements are consecutively
1449   // numbered from this value.
1450   unsigned ShiftAmt = SVOp->getMaskElt(i);
1451   if (ShiftAmt < i) return -1;
1452   ShiftAmt -= i;
1453
1454   // Check the rest of the elements to see if they are consecutive.
1455   for (++i; i != 4; ++i)
1456     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1457       return -1;
1458
1459   return ShiftAmt;
1460 }
1461
1462 //===----------------------------------------------------------------------===//
1463 //  Addressing Mode Selection
1464 //===----------------------------------------------------------------------===//
1465
1466 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1467 /// or 64-bit immediate, and if the value can be accurately represented as a
1468 /// sign extension from a 16-bit value.  If so, this returns true and the
1469 /// immediate.
1470 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1471   if (!isa<ConstantSDNode>(N))
1472     return false;
1473
1474   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1475   if (N->getValueType(0) == MVT::i32)
1476     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1477   else
1478     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1479 }
1480 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1481   return isIntS16Immediate(Op.getNode(), Imm);
1482 }
1483
1484
1485 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1486 /// can be represented as an indexed [r+r] operation.  Returns false if it
1487 /// can be more efficiently represented with [r+imm].
1488 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1489                                             SDValue &Index,
1490                                             SelectionDAG &DAG) const {
1491   short imm = 0;
1492   if (N.getOpcode() == ISD::ADD) {
1493     if (isIntS16Immediate(N.getOperand(1), imm))
1494       return false;    // r+i
1495     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1496       return false;    // r+i
1497
1498     Base = N.getOperand(0);
1499     Index = N.getOperand(1);
1500     return true;
1501   } else if (N.getOpcode() == ISD::OR) {
1502     if (isIntS16Immediate(N.getOperand(1), imm))
1503       return false;    // r+i can fold it if we can.
1504
1505     // If this is an or of disjoint bitfields, we can codegen this as an add
1506     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1507     // disjoint.
1508     APInt LHSKnownZero, LHSKnownOne;
1509     APInt RHSKnownZero, RHSKnownOne;
1510     DAG.computeKnownBits(N.getOperand(0),
1511                          LHSKnownZero, LHSKnownOne);
1512
1513     if (LHSKnownZero.getBoolValue()) {
1514       DAG.computeKnownBits(N.getOperand(1),
1515                            RHSKnownZero, RHSKnownOne);
1516       // If all of the bits are known zero on the LHS or RHS, the add won't
1517       // carry.
1518       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1519         Base = N.getOperand(0);
1520         Index = N.getOperand(1);
1521         return true;
1522       }
1523     }
1524   }
1525
1526   return false;
1527 }
1528
1529 // If we happen to be doing an i64 load or store into a stack slot that has
1530 // less than a 4-byte alignment, then the frame-index elimination may need to
1531 // use an indexed load or store instruction (because the offset may not be a
1532 // multiple of 4). The extra register needed to hold the offset comes from the
1533 // register scavenger, and it is possible that the scavenger will need to use
1534 // an emergency spill slot. As a result, we need to make sure that a spill slot
1535 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1536 // stack slot.
1537 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1538   // FIXME: This does not handle the LWA case.
1539   if (VT != MVT::i64)
1540     return;
1541
1542   // NOTE: We'll exclude negative FIs here, which come from argument
1543   // lowering, because there are no known test cases triggering this problem
1544   // using packed structures (or similar). We can remove this exclusion if
1545   // we find such a test case. The reason why this is so test-case driven is
1546   // because this entire 'fixup' is only to prevent crashes (from the
1547   // register scavenger) on not-really-valid inputs. For example, if we have:
1548   //   %a = alloca i1
1549   //   %b = bitcast i1* %a to i64*
1550   //   store i64* a, i64 b
1551   // then the store should really be marked as 'align 1', but is not. If it
1552   // were marked as 'align 1' then the indexed form would have been
1553   // instruction-selected initially, and the problem this 'fixup' is preventing
1554   // won't happen regardless.
1555   if (FrameIdx < 0)
1556     return;
1557
1558   MachineFunction &MF = DAG.getMachineFunction();
1559   MachineFrameInfo *MFI = MF.getFrameInfo();
1560
1561   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1562   if (Align >= 4)
1563     return;
1564
1565   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1566   FuncInfo->setHasNonRISpills();
1567 }
1568
1569 /// Returns true if the address N can be represented by a base register plus
1570 /// a signed 16-bit displacement [r+imm], and if it is not better
1571 /// represented as reg+reg.  If Aligned is true, only accept displacements
1572 /// suitable for STD and friends, i.e. multiples of 4.
1573 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1574                                             SDValue &Base,
1575                                             SelectionDAG &DAG,
1576                                             bool Aligned) const {
1577   // FIXME dl should come from parent load or store, not from address
1578   SDLoc dl(N);
1579   // If this can be more profitably realized as r+r, fail.
1580   if (SelectAddressRegReg(N, Disp, Base, DAG))
1581     return false;
1582
1583   if (N.getOpcode() == ISD::ADD) {
1584     short imm = 0;
1585     if (isIntS16Immediate(N.getOperand(1), imm) &&
1586         (!Aligned || (imm & 3) == 0)) {
1587       Disp = DAG.getTargetConstant(imm, N.getValueType());
1588       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1589         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1590         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1591       } else {
1592         Base = N.getOperand(0);
1593       }
1594       return true; // [r+i]
1595     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1596       // Match LOAD (ADD (X, Lo(G))).
1597       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1598              && "Cannot handle constant offsets yet!");
1599       Disp = N.getOperand(1).getOperand(0);  // The global address.
1600       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1601              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1602              Disp.getOpcode() == ISD::TargetConstantPool ||
1603              Disp.getOpcode() == ISD::TargetJumpTable);
1604       Base = N.getOperand(0);
1605       return true;  // [&g+r]
1606     }
1607   } else if (N.getOpcode() == ISD::OR) {
1608     short imm = 0;
1609     if (isIntS16Immediate(N.getOperand(1), imm) &&
1610         (!Aligned || (imm & 3) == 0)) {
1611       // If this is an or of disjoint bitfields, we can codegen this as an add
1612       // (for better address arithmetic) if the LHS and RHS of the OR are
1613       // provably disjoint.
1614       APInt LHSKnownZero, LHSKnownOne;
1615       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1616
1617       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1618         // If all of the bits are known zero on the LHS or RHS, the add won't
1619         // carry.
1620         if (FrameIndexSDNode *FI =
1621               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1622           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1623           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1624         } else {
1625           Base = N.getOperand(0);
1626         }
1627         Disp = DAG.getTargetConstant(imm, N.getValueType());
1628         return true;
1629       }
1630     }
1631   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1632     // Loading from a constant address.
1633
1634     // If this address fits entirely in a 16-bit sext immediate field, codegen
1635     // this as "d, 0"
1636     short Imm;
1637     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1638       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1639       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1640                              CN->getValueType(0));
1641       return true;
1642     }
1643
1644     // Handle 32-bit sext immediates with LIS + addr mode.
1645     if ((CN->getValueType(0) == MVT::i32 ||
1646          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1647         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1648       int Addr = (int)CN->getZExtValue();
1649
1650       // Otherwise, break this down into an LIS + disp.
1651       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1652
1653       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1654       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1655       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1656       return true;
1657     }
1658   }
1659
1660   Disp = DAG.getTargetConstant(0, getPointerTy());
1661   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1662     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1663     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1664   } else
1665     Base = N;
1666   return true;      // [r+0]
1667 }
1668
1669 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1670 /// represented as an indexed [r+r] operation.
1671 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1672                                                 SDValue &Index,
1673                                                 SelectionDAG &DAG) const {
1674   // Check to see if we can easily represent this as an [r+r] address.  This
1675   // will fail if it thinks that the address is more profitably represented as
1676   // reg+imm, e.g. where imm = 0.
1677   if (SelectAddressRegReg(N, Base, Index, DAG))
1678     return true;
1679
1680   // If the operand is an addition, always emit this as [r+r], since this is
1681   // better (for code size, and execution, as the memop does the add for free)
1682   // than emitting an explicit add.
1683   if (N.getOpcode() == ISD::ADD) {
1684     Base = N.getOperand(0);
1685     Index = N.getOperand(1);
1686     return true;
1687   }
1688
1689   // Otherwise, do it the hard way, using R0 as the base register.
1690   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1691                          N.getValueType());
1692   Index = N;
1693   return true;
1694 }
1695
1696 /// getPreIndexedAddressParts - returns true by value, base pointer and
1697 /// offset pointer and addressing mode by reference if the node's address
1698 /// can be legally represented as pre-indexed load / store address.
1699 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1700                                                   SDValue &Offset,
1701                                                   ISD::MemIndexedMode &AM,
1702                                                   SelectionDAG &DAG) const {
1703   if (DisablePPCPreinc) return false;
1704
1705   bool isLoad = true;
1706   SDValue Ptr;
1707   EVT VT;
1708   unsigned Alignment;
1709   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1710     Ptr = LD->getBasePtr();
1711     VT = LD->getMemoryVT();
1712     Alignment = LD->getAlignment();
1713   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1714     Ptr = ST->getBasePtr();
1715     VT  = ST->getMemoryVT();
1716     Alignment = ST->getAlignment();
1717     isLoad = false;
1718   } else
1719     return false;
1720
1721   // PowerPC doesn't have preinc load/store instructions for vectors (except
1722   // for QPX, which does have preinc r+r forms).
1723   if (VT.isVector()) {
1724     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1725       return false;
1726     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1727       AM = ISD::PRE_INC;
1728       return true;
1729     }
1730   }
1731
1732   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1733
1734     // Common code will reject creating a pre-inc form if the base pointer
1735     // is a frame index, or if N is a store and the base pointer is either
1736     // the same as or a predecessor of the value being stored.  Check for
1737     // those situations here, and try with swapped Base/Offset instead.
1738     bool Swap = false;
1739
1740     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1741       Swap = true;
1742     else if (!isLoad) {
1743       SDValue Val = cast<StoreSDNode>(N)->getValue();
1744       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1745         Swap = true;
1746     }
1747
1748     if (Swap)
1749       std::swap(Base, Offset);
1750
1751     AM = ISD::PRE_INC;
1752     return true;
1753   }
1754
1755   // LDU/STU can only handle immediates that are a multiple of 4.
1756   if (VT != MVT::i64) {
1757     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1758       return false;
1759   } else {
1760     // LDU/STU need an address with at least 4-byte alignment.
1761     if (Alignment < 4)
1762       return false;
1763
1764     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1765       return false;
1766   }
1767
1768   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1769     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1770     // sext i32 to i64 when addr mode is r+i.
1771     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1772         LD->getExtensionType() == ISD::SEXTLOAD &&
1773         isa<ConstantSDNode>(Offset))
1774       return false;
1775   }
1776
1777   AM = ISD::PRE_INC;
1778   return true;
1779 }
1780
1781 //===----------------------------------------------------------------------===//
1782 //  LowerOperation implementation
1783 //===----------------------------------------------------------------------===//
1784
1785 /// GetLabelAccessInfo - Return true if we should reference labels using a
1786 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1787 static bool GetLabelAccessInfo(const TargetMachine &TM,
1788                                const PPCSubtarget &Subtarget,
1789                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1790                                const GlobalValue *GV = nullptr) {
1791   HiOpFlags = PPCII::MO_HA;
1792   LoOpFlags = PPCII::MO_LO;
1793
1794   // Don't use the pic base if not in PIC relocation model.
1795   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1796
1797   if (isPIC) {
1798     HiOpFlags |= PPCII::MO_PIC_FLAG;
1799     LoOpFlags |= PPCII::MO_PIC_FLAG;
1800   }
1801
1802   // If this is a reference to a global value that requires a non-lazy-ptr, make
1803   // sure that instruction lowering adds it.
1804   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1805     HiOpFlags |= PPCII::MO_NLP_FLAG;
1806     LoOpFlags |= PPCII::MO_NLP_FLAG;
1807
1808     if (GV->hasHiddenVisibility()) {
1809       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1810       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1811     }
1812   }
1813
1814   return isPIC;
1815 }
1816
1817 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1818                              SelectionDAG &DAG) {
1819   EVT PtrVT = HiPart.getValueType();
1820   SDValue Zero = DAG.getConstant(0, PtrVT);
1821   SDLoc DL(HiPart);
1822
1823   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1824   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1825
1826   // With PIC, the first instruction is actually "GR+hi(&G)".
1827   if (isPIC)
1828     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1829                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1830
1831   // Generate non-pic code that has direct accesses to the constant pool.
1832   // The address of the global is just (hi(&g)+lo(&g)).
1833   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1834 }
1835
1836 static void setUsesTOCBasePtr(MachineFunction &MF) {
1837   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1838   FuncInfo->setUsesTOCBasePtr();
1839 }
1840
1841 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1842   setUsesTOCBasePtr(DAG.getMachineFunction());
1843 }
1844
1845 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1846                            SDValue GA) {
1847   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1848   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1849                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1850
1851   SDValue Ops[] = { GA, Reg };
1852   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1853                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1854                                  MachinePointerInfo::getGOT(), 0, false, true,
1855                                  false, 0);
1856 }
1857
1858 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1859                                              SelectionDAG &DAG) const {
1860   EVT PtrVT = Op.getValueType();
1861   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1862   const Constant *C = CP->getConstVal();
1863
1864   // 64-bit SVR4 ABI code is always position-independent.
1865   // The actual address of the GlobalValue is stored in the TOC.
1866   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1867     setUsesTOCBasePtr(DAG);
1868     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1869     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1870   }
1871
1872   unsigned MOHiFlag, MOLoFlag;
1873   bool isPIC =
1874       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1875
1876   if (isPIC && Subtarget.isSVR4ABI()) {
1877     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1878                                            PPCII::MO_PIC_FLAG);
1879     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1880   }
1881
1882   SDValue CPIHi =
1883     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1884   SDValue CPILo =
1885     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1886   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1887 }
1888
1889 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1890   EVT PtrVT = Op.getValueType();
1891   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1892
1893   // 64-bit SVR4 ABI code is always position-independent.
1894   // The actual address of the GlobalValue is stored in the TOC.
1895   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1896     setUsesTOCBasePtr(DAG);
1897     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1898     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1899   }
1900
1901   unsigned MOHiFlag, MOLoFlag;
1902   bool isPIC =
1903       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1904
1905   if (isPIC && Subtarget.isSVR4ABI()) {
1906     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1907                                         PPCII::MO_PIC_FLAG);
1908     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1909   }
1910
1911   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1912   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1913   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1914 }
1915
1916 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1917                                              SelectionDAG &DAG) const {
1918   EVT PtrVT = Op.getValueType();
1919   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1920   const BlockAddress *BA = BASDN->getBlockAddress();
1921
1922   // 64-bit SVR4 ABI code is always position-independent.
1923   // The actual BlockAddress is stored in the TOC.
1924   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1925     setUsesTOCBasePtr(DAG);
1926     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1927     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1928   }
1929
1930   unsigned MOHiFlag, MOLoFlag;
1931   bool isPIC =
1932       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1933   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1934   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1935   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1936 }
1937
1938 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1939                                               SelectionDAG &DAG) const {
1940
1941   // FIXME: TLS addresses currently use medium model code sequences,
1942   // which is the most useful form.  Eventually support for small and
1943   // large models could be added if users need it, at the cost of
1944   // additional complexity.
1945   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1946   SDLoc dl(GA);
1947   const GlobalValue *GV = GA->getGlobal();
1948   EVT PtrVT = getPointerTy();
1949   bool is64bit = Subtarget.isPPC64();
1950   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1951   PICLevel::Level picLevel = M->getPICLevel();
1952
1953   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1954
1955   if (Model == TLSModel::LocalExec) {
1956     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1957                                                PPCII::MO_TPREL_HA);
1958     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1959                                                PPCII::MO_TPREL_LO);
1960     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1961                                      is64bit ? MVT::i64 : MVT::i32);
1962     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1963     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1964   }
1965
1966   if (Model == TLSModel::InitialExec) {
1967     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1968     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1969                                                 PPCII::MO_TLS);
1970     SDValue GOTPtr;
1971     if (is64bit) {
1972       setUsesTOCBasePtr(DAG);
1973       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1974       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1975                            PtrVT, GOTReg, TGA);
1976     } else
1977       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1978     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1979                                    PtrVT, TGA, GOTPtr);
1980     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1981   }
1982
1983   if (Model == TLSModel::GeneralDynamic) {
1984     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1985     SDValue GOTPtr;
1986     if (is64bit) {
1987       setUsesTOCBasePtr(DAG);
1988       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1989       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1990                                    GOTReg, TGA);
1991     } else {
1992       if (picLevel == PICLevel::Small)
1993         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1994       else
1995         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1996     }
1997     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1998                        GOTPtr, TGA, TGA);
1999   }
2000
2001   if (Model == TLSModel::LocalDynamic) {
2002     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2003     SDValue GOTPtr;
2004     if (is64bit) {
2005       setUsesTOCBasePtr(DAG);
2006       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2007       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2008                            GOTReg, TGA);
2009     } else {
2010       if (picLevel == PICLevel::Small)
2011         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2012       else
2013         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2014     }
2015     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2016                                   PtrVT, GOTPtr, TGA, TGA);
2017     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2018                                       PtrVT, TLSAddr, TGA);
2019     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2020   }
2021
2022   llvm_unreachable("Unknown TLS model!");
2023 }
2024
2025 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2026                                               SelectionDAG &DAG) const {
2027   EVT PtrVT = Op.getValueType();
2028   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2029   SDLoc DL(GSDN);
2030   const GlobalValue *GV = GSDN->getGlobal();
2031
2032   // 64-bit SVR4 ABI code is always position-independent.
2033   // The actual address of the GlobalValue is stored in the TOC.
2034   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2035     setUsesTOCBasePtr(DAG);
2036     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2037     return getTOCEntry(DAG, DL, true, GA);
2038   }
2039
2040   unsigned MOHiFlag, MOLoFlag;
2041   bool isPIC =
2042       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2043
2044   if (isPIC && Subtarget.isSVR4ABI()) {
2045     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2046                                             GSDN->getOffset(),
2047                                             PPCII::MO_PIC_FLAG);
2048     return getTOCEntry(DAG, DL, false, GA);
2049   }
2050
2051   SDValue GAHi =
2052     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2053   SDValue GALo =
2054     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2055
2056   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2057
2058   // If the global reference is actually to a non-lazy-pointer, we have to do an
2059   // extra load to get the address of the global.
2060   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2061     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2062                       false, false, false, 0);
2063   return Ptr;
2064 }
2065
2066 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2067   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2068   SDLoc dl(Op);
2069
2070   if (Op.getValueType() == MVT::v2i64) {
2071     // When the operands themselves are v2i64 values, we need to do something
2072     // special because VSX has no underlying comparison operations for these.
2073     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2074       // Equality can be handled by casting to the legal type for Altivec
2075       // comparisons, everything else needs to be expanded.
2076       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2077         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2078                  DAG.getSetCC(dl, MVT::v4i32,
2079                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2080                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2081                    CC));
2082       }
2083
2084       return SDValue();
2085     }
2086
2087     // We handle most of these in the usual way.
2088     return Op;
2089   }
2090
2091   // If we're comparing for equality to zero, expose the fact that this is
2092   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2093   // fold the new nodes.
2094   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2095     if (C->isNullValue() && CC == ISD::SETEQ) {
2096       EVT VT = Op.getOperand(0).getValueType();
2097       SDValue Zext = Op.getOperand(0);
2098       if (VT.bitsLT(MVT::i32)) {
2099         VT = MVT::i32;
2100         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2101       }
2102       unsigned Log2b = Log2_32(VT.getSizeInBits());
2103       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2104       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2105                                 DAG.getConstant(Log2b, MVT::i32));
2106       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2107     }
2108     // Leave comparisons against 0 and -1 alone for now, since they're usually
2109     // optimized.  FIXME: revisit this when we can custom lower all setcc
2110     // optimizations.
2111     if (C->isAllOnesValue() || C->isNullValue())
2112       return SDValue();
2113   }
2114
2115   // If we have an integer seteq/setne, turn it into a compare against zero
2116   // by xor'ing the rhs with the lhs, which is faster than setting a
2117   // condition register, reading it back out, and masking the correct bit.  The
2118   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2119   // the result to other bit-twiddling opportunities.
2120   EVT LHSVT = Op.getOperand(0).getValueType();
2121   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2122     EVT VT = Op.getValueType();
2123     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2124                                 Op.getOperand(1));
2125     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2126   }
2127   return SDValue();
2128 }
2129
2130 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2131                                       const PPCSubtarget &Subtarget) const {
2132   SDNode *Node = Op.getNode();
2133   EVT VT = Node->getValueType(0);
2134   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2135   SDValue InChain = Node->getOperand(0);
2136   SDValue VAListPtr = Node->getOperand(1);
2137   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2138   SDLoc dl(Node);
2139
2140   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2141
2142   // gpr_index
2143   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2144                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2145                                     false, false, false, 0);
2146   InChain = GprIndex.getValue(1);
2147
2148   if (VT == MVT::i64) {
2149     // Check if GprIndex is even
2150     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2151                                  DAG.getConstant(1, MVT::i32));
2152     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2153                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2154     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2155                                           DAG.getConstant(1, MVT::i32));
2156     // Align GprIndex to be even if it isn't
2157     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2158                            GprIndex);
2159   }
2160
2161   // fpr index is 1 byte after gpr
2162   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2163                                DAG.getConstant(1, MVT::i32));
2164
2165   // fpr
2166   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2167                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2168                                     false, false, false, 0);
2169   InChain = FprIndex.getValue(1);
2170
2171   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2172                                        DAG.getConstant(8, MVT::i32));
2173
2174   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2175                                         DAG.getConstant(4, MVT::i32));
2176
2177   // areas
2178   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2179                                      MachinePointerInfo(), false, false,
2180                                      false, 0);
2181   InChain = OverflowArea.getValue(1);
2182
2183   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2184                                     MachinePointerInfo(), false, false,
2185                                     false, 0);
2186   InChain = RegSaveArea.getValue(1);
2187
2188   // select overflow_area if index > 8
2189   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2190                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
2191
2192   // adjustment constant gpr_index * 4/8
2193   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2194                                     VT.isInteger() ? GprIndex : FprIndex,
2195                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
2196                                                     MVT::i32));
2197
2198   // OurReg = RegSaveArea + RegConstant
2199   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2200                                RegConstant);
2201
2202   // Floating types are 32 bytes into RegSaveArea
2203   if (VT.isFloatingPoint())
2204     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2205                          DAG.getConstant(32, MVT::i32));
2206
2207   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2208   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2209                                    VT.isInteger() ? GprIndex : FprIndex,
2210                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2211                                                    MVT::i32));
2212
2213   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2214                               VT.isInteger() ? VAListPtr : FprPtr,
2215                               MachinePointerInfo(SV),
2216                               MVT::i8, false, false, 0);
2217
2218   // determine if we should load from reg_save_area or overflow_area
2219   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2220
2221   // increase overflow_area by 4/8 if gpr/fpr > 8
2222   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2223                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2224                                           MVT::i32));
2225
2226   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2227                              OverflowAreaPlusN);
2228
2229   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2230                               OverflowAreaPtr,
2231                               MachinePointerInfo(),
2232                               MVT::i32, false, false, 0);
2233
2234   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2235                      false, false, false, 0);
2236 }
2237
2238 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2239                                        const PPCSubtarget &Subtarget) const {
2240   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2241
2242   // We have to copy the entire va_list struct:
2243   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2244   return DAG.getMemcpy(Op.getOperand(0), Op,
2245                        Op.getOperand(1), Op.getOperand(2),
2246                        DAG.getConstant(12, MVT::i32), 8, false, true,
2247                        MachinePointerInfo(), MachinePointerInfo());
2248 }
2249
2250 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2251                                                   SelectionDAG &DAG) const {
2252   return Op.getOperand(0);
2253 }
2254
2255 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2256                                                 SelectionDAG &DAG) const {
2257   SDValue Chain = Op.getOperand(0);
2258   SDValue Trmp = Op.getOperand(1); // trampoline
2259   SDValue FPtr = Op.getOperand(2); // nested function
2260   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2261   SDLoc dl(Op);
2262
2263   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2264   bool isPPC64 = (PtrVT == MVT::i64);
2265   Type *IntPtrTy =
2266     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2267                                                              *DAG.getContext());
2268
2269   TargetLowering::ArgListTy Args;
2270   TargetLowering::ArgListEntry Entry;
2271
2272   Entry.Ty = IntPtrTy;
2273   Entry.Node = Trmp; Args.push_back(Entry);
2274
2275   // TrampSize == (isPPC64 ? 48 : 40);
2276   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2277                                isPPC64 ? MVT::i64 : MVT::i32);
2278   Args.push_back(Entry);
2279
2280   Entry.Node = FPtr; Args.push_back(Entry);
2281   Entry.Node = Nest; Args.push_back(Entry);
2282
2283   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2284   TargetLowering::CallLoweringInfo CLI(DAG);
2285   CLI.setDebugLoc(dl).setChain(Chain)
2286     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2287                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2288                std::move(Args), 0);
2289
2290   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2291   return CallResult.second;
2292 }
2293
2294 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2295                                         const PPCSubtarget &Subtarget) const {
2296   MachineFunction &MF = DAG.getMachineFunction();
2297   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2298
2299   SDLoc dl(Op);
2300
2301   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2302     // vastart just stores the address of the VarArgsFrameIndex slot into the
2303     // memory location argument.
2304     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2305     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2306     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2307     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2308                         MachinePointerInfo(SV),
2309                         false, false, 0);
2310   }
2311
2312   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2313   // We suppose the given va_list is already allocated.
2314   //
2315   // typedef struct {
2316   //  char gpr;     /* index into the array of 8 GPRs
2317   //                 * stored in the register save area
2318   //                 * gpr=0 corresponds to r3,
2319   //                 * gpr=1 to r4, etc.
2320   //                 */
2321   //  char fpr;     /* index into the array of 8 FPRs
2322   //                 * stored in the register save area
2323   //                 * fpr=0 corresponds to f1,
2324   //                 * fpr=1 to f2, etc.
2325   //                 */
2326   //  char *overflow_arg_area;
2327   //                /* location on stack that holds
2328   //                 * the next overflow argument
2329   //                 */
2330   //  char *reg_save_area;
2331   //               /* where r3:r10 and f1:f8 (if saved)
2332   //                * are stored
2333   //                */
2334   // } va_list[1];
2335
2336
2337   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2338   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2339
2340
2341   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2342
2343   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2344                                             PtrVT);
2345   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2346                                  PtrVT);
2347
2348   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2349   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2350
2351   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2352   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2353
2354   uint64_t FPROffset = 1;
2355   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2356
2357   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2358
2359   // Store first byte : number of int regs
2360   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2361                                          Op.getOperand(1),
2362                                          MachinePointerInfo(SV),
2363                                          MVT::i8, false, false, 0);
2364   uint64_t nextOffset = FPROffset;
2365   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2366                                   ConstFPROffset);
2367
2368   // Store second byte : number of float regs
2369   SDValue secondStore =
2370     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2371                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2372                       false, false, 0);
2373   nextOffset += StackOffset;
2374   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2375
2376   // Store second word : arguments given on stack
2377   SDValue thirdStore =
2378     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2379                  MachinePointerInfo(SV, nextOffset),
2380                  false, false, 0);
2381   nextOffset += FrameOffset;
2382   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2383
2384   // Store third word : arguments given in registers
2385   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2386                       MachinePointerInfo(SV, nextOffset),
2387                       false, false, 0);
2388
2389 }
2390
2391 #include "PPCGenCallingConv.inc"
2392
2393 // Function whose sole purpose is to kill compiler warnings 
2394 // stemming from unused functions included from PPCGenCallingConv.inc.
2395 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2396   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2397 }
2398
2399 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2400                                       CCValAssign::LocInfo &LocInfo,
2401                                       ISD::ArgFlagsTy &ArgFlags,
2402                                       CCState &State) {
2403   return true;
2404 }
2405
2406 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2407                                              MVT &LocVT,
2408                                              CCValAssign::LocInfo &LocInfo,
2409                                              ISD::ArgFlagsTy &ArgFlags,
2410                                              CCState &State) {
2411   static const MCPhysReg ArgRegs[] = {
2412     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2413     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2414   };
2415   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2416
2417   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2418
2419   // Skip one register if the first unallocated register has an even register
2420   // number and there are still argument registers available which have not been
2421   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2422   // need to skip a register if RegNum is odd.
2423   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2424     State.AllocateReg(ArgRegs[RegNum]);
2425   }
2426
2427   // Always return false here, as this function only makes sure that the first
2428   // unallocated register has an odd register number and does not actually
2429   // allocate a register for the current argument.
2430   return false;
2431 }
2432
2433 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2434                                                MVT &LocVT,
2435                                                CCValAssign::LocInfo &LocInfo,
2436                                                ISD::ArgFlagsTy &ArgFlags,
2437                                                CCState &State) {
2438   static const MCPhysReg ArgRegs[] = {
2439     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2440     PPC::F8
2441   };
2442
2443   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2444
2445   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2446
2447   // If there is only one Floating-point register left we need to put both f64
2448   // values of a split ppc_fp128 value on the stack.
2449   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2450     State.AllocateReg(ArgRegs[RegNum]);
2451   }
2452
2453   // Always return false here, as this function only makes sure that the two f64
2454   // values a ppc_fp128 value is split into are both passed in registers or both
2455   // passed on the stack and does not actually allocate a register for the
2456   // current argument.
2457   return false;
2458 }
2459
2460 /// FPR - The set of FP registers that should be allocated for arguments,
2461 /// on Darwin.
2462 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2463                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2464                                 PPC::F11, PPC::F12, PPC::F13};
2465
2466 /// QFPR - The set of QPX registers that should be allocated for arguments.
2467 static const MCPhysReg QFPR[] = {
2468     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2469     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2470
2471 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2472 /// the stack.
2473 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2474                                        unsigned PtrByteSize) {
2475   unsigned ArgSize = ArgVT.getStoreSize();
2476   if (Flags.isByVal())
2477     ArgSize = Flags.getByValSize();
2478
2479   // Round up to multiples of the pointer size, except for array members,
2480   // which are always packed.
2481   if (!Flags.isInConsecutiveRegs())
2482     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2483
2484   return ArgSize;
2485 }
2486
2487 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2488 /// on the stack.
2489 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2490                                             ISD::ArgFlagsTy Flags,
2491                                             unsigned PtrByteSize) {
2492   unsigned Align = PtrByteSize;
2493
2494   // Altivec parameters are padded to a 16 byte boundary.
2495   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2496       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2497       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2498     Align = 16;
2499   // QPX vector types stored in double-precision are padded to a 32 byte
2500   // boundary.
2501   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2502     Align = 32;
2503
2504   // ByVal parameters are aligned as requested.
2505   if (Flags.isByVal()) {
2506     unsigned BVAlign = Flags.getByValAlign();
2507     if (BVAlign > PtrByteSize) {
2508       if (BVAlign % PtrByteSize != 0)
2509           llvm_unreachable(
2510             "ByVal alignment is not a multiple of the pointer size");
2511
2512       Align = BVAlign;
2513     }
2514   }
2515
2516   // Array members are always packed to their original alignment.
2517   if (Flags.isInConsecutiveRegs()) {
2518     // If the array member was split into multiple registers, the first
2519     // needs to be aligned to the size of the full type.  (Except for
2520     // ppcf128, which is only aligned as its f64 components.)
2521     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2522       Align = OrigVT.getStoreSize();
2523     else
2524       Align = ArgVT.getStoreSize();
2525   }
2526
2527   return Align;
2528 }
2529
2530 /// CalculateStackSlotUsed - Return whether this argument will use its
2531 /// stack slot (instead of being passed in registers).  ArgOffset,
2532 /// AvailableFPRs, and AvailableVRs must hold the current argument
2533 /// position, and will be updated to account for this argument.
2534 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2535                                    ISD::ArgFlagsTy Flags,
2536                                    unsigned PtrByteSize,
2537                                    unsigned LinkageSize,
2538                                    unsigned ParamAreaSize,
2539                                    unsigned &ArgOffset,
2540                                    unsigned &AvailableFPRs,
2541                                    unsigned &AvailableVRs, bool HasQPX) {
2542   bool UseMemory = false;
2543
2544   // Respect alignment of argument on the stack.
2545   unsigned Align =
2546     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2547   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2548   // If there's no space left in the argument save area, we must
2549   // use memory (this check also catches zero-sized arguments).
2550   if (ArgOffset >= LinkageSize + ParamAreaSize)
2551     UseMemory = true;
2552
2553   // Allocate argument on the stack.
2554   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2555   if (Flags.isInConsecutiveRegsLast())
2556     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2557   // If we overran the argument save area, we must use memory
2558   // (this check catches arguments passed partially in memory)
2559   if (ArgOffset > LinkageSize + ParamAreaSize)
2560     UseMemory = true;
2561
2562   // However, if the argument is actually passed in an FPR or a VR,
2563   // we don't use memory after all.
2564   if (!Flags.isByVal()) {
2565     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2566         // QPX registers overlap with the scalar FP registers.
2567         (HasQPX && (ArgVT == MVT::v4f32 ||
2568                     ArgVT == MVT::v4f64 ||
2569                     ArgVT == MVT::v4i1)))
2570       if (AvailableFPRs > 0) {
2571         --AvailableFPRs;
2572         return false;
2573       }
2574     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2575         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2576         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2577       if (AvailableVRs > 0) {
2578         --AvailableVRs;
2579         return false;
2580       }
2581   }
2582
2583   return UseMemory;
2584 }
2585
2586 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2587 /// ensure minimum alignment required for target.
2588 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2589                                      unsigned NumBytes) {
2590   unsigned TargetAlign = Lowering->getStackAlignment();
2591   unsigned AlignMask = TargetAlign - 1;
2592   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2593   return NumBytes;
2594 }
2595
2596 SDValue
2597 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2598                                         CallingConv::ID CallConv, bool isVarArg,
2599                                         const SmallVectorImpl<ISD::InputArg>
2600                                           &Ins,
2601                                         SDLoc dl, SelectionDAG &DAG,
2602                                         SmallVectorImpl<SDValue> &InVals)
2603                                           const {
2604   if (Subtarget.isSVR4ABI()) {
2605     if (Subtarget.isPPC64())
2606       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2607                                          dl, DAG, InVals);
2608     else
2609       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2610                                          dl, DAG, InVals);
2611   } else {
2612     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2613                                        dl, DAG, InVals);
2614   }
2615 }
2616
2617 SDValue
2618 PPCTargetLowering::LowerFormalArguments_32SVR4(
2619                                       SDValue Chain,
2620                                       CallingConv::ID CallConv, bool isVarArg,
2621                                       const SmallVectorImpl<ISD::InputArg>
2622                                         &Ins,
2623                                       SDLoc dl, SelectionDAG &DAG,
2624                                       SmallVectorImpl<SDValue> &InVals) const {
2625
2626   // 32-bit SVR4 ABI Stack Frame Layout:
2627   //              +-----------------------------------+
2628   //        +-->  |            Back chain             |
2629   //        |     +-----------------------------------+
2630   //        |     | Floating-point register save area |
2631   //        |     +-----------------------------------+
2632   //        |     |    General register save area     |
2633   //        |     +-----------------------------------+
2634   //        |     |          CR save word             |
2635   //        |     +-----------------------------------+
2636   //        |     |         VRSAVE save word          |
2637   //        |     +-----------------------------------+
2638   //        |     |         Alignment padding         |
2639   //        |     +-----------------------------------+
2640   //        |     |     Vector register save area     |
2641   //        |     +-----------------------------------+
2642   //        |     |       Local variable space        |
2643   //        |     +-----------------------------------+
2644   //        |     |        Parameter list area        |
2645   //        |     +-----------------------------------+
2646   //        |     |           LR save word            |
2647   //        |     +-----------------------------------+
2648   // SP-->  +---  |            Back chain             |
2649   //              +-----------------------------------+
2650   //
2651   // Specifications:
2652   //   System V Application Binary Interface PowerPC Processor Supplement
2653   //   AltiVec Technology Programming Interface Manual
2654
2655   MachineFunction &MF = DAG.getMachineFunction();
2656   MachineFrameInfo *MFI = MF.getFrameInfo();
2657   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2658
2659   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2660   // Potential tail calls could cause overwriting of argument stack slots.
2661   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2662                        (CallConv == CallingConv::Fast));
2663   unsigned PtrByteSize = 4;
2664
2665   // Assign locations to all of the incoming arguments.
2666   SmallVector<CCValAssign, 16> ArgLocs;
2667   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2668                  *DAG.getContext());
2669
2670   // Reserve space for the linkage area on the stack.
2671   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2672   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2673
2674   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2675
2676   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2677     CCValAssign &VA = ArgLocs[i];
2678
2679     // Arguments stored in registers.
2680     if (VA.isRegLoc()) {
2681       const TargetRegisterClass *RC;
2682       EVT ValVT = VA.getValVT();
2683
2684       switch (ValVT.getSimpleVT().SimpleTy) {
2685         default:
2686           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2687         case MVT::i1:
2688         case MVT::i32:
2689           RC = &PPC::GPRCRegClass;
2690           break;
2691         case MVT::f32:
2692           RC = &PPC::F4RCRegClass;
2693           break;
2694         case MVT::f64:
2695           if (Subtarget.hasVSX())
2696             RC = &PPC::VSFRCRegClass;
2697           else
2698             RC = &PPC::F8RCRegClass;
2699           break;
2700         case MVT::v16i8:
2701         case MVT::v8i16:
2702         case MVT::v4i32:
2703           RC = &PPC::VRRCRegClass;
2704           break;
2705         case MVT::v4f32:
2706           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2707           break;
2708         case MVT::v2f64:
2709         case MVT::v2i64:
2710           RC = &PPC::VSHRCRegClass;
2711           break;
2712         case MVT::v4f64:
2713           RC = &PPC::QFRCRegClass;
2714           break;
2715         case MVT::v4i1:
2716           RC = &PPC::QBRCRegClass;
2717           break;
2718       }
2719
2720       // Transform the arguments stored in physical registers into virtual ones.
2721       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2722       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2723                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2724
2725       if (ValVT == MVT::i1)
2726         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2727
2728       InVals.push_back(ArgValue);
2729     } else {
2730       // Argument stored in memory.
2731       assert(VA.isMemLoc());
2732
2733       unsigned ArgSize = VA.getLocVT().getStoreSize();
2734       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2735                                       isImmutable);
2736
2737       // Create load nodes to retrieve arguments from the stack.
2738       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2739       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2740                                    MachinePointerInfo(),
2741                                    false, false, false, 0));
2742     }
2743   }
2744
2745   // Assign locations to all of the incoming aggregate by value arguments.
2746   // Aggregates passed by value are stored in the local variable space of the
2747   // caller's stack frame, right above the parameter list area.
2748   SmallVector<CCValAssign, 16> ByValArgLocs;
2749   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2750                       ByValArgLocs, *DAG.getContext());
2751
2752   // Reserve stack space for the allocations in CCInfo.
2753   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2754
2755   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2756
2757   // Area that is at least reserved in the caller of this function.
2758   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2759   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2760
2761   // Set the size that is at least reserved in caller of this function.  Tail
2762   // call optimized function's reserved stack space needs to be aligned so that
2763   // taking the difference between two stack areas will result in an aligned
2764   // stack.
2765   MinReservedArea =
2766       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2767   FuncInfo->setMinReservedArea(MinReservedArea);
2768
2769   SmallVector<SDValue, 8> MemOps;
2770
2771   // If the function takes variable number of arguments, make a frame index for
2772   // the start of the first vararg value... for expansion of llvm.va_start.
2773   if (isVarArg) {
2774     static const MCPhysReg GPArgRegs[] = {
2775       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2776       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2777     };
2778     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2779
2780     static const MCPhysReg FPArgRegs[] = {
2781       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2782       PPC::F8
2783     };
2784     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2785     if (DisablePPCFloatInVariadic)
2786       NumFPArgRegs = 0;
2787
2788     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2789     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2790
2791     // Make room for NumGPArgRegs and NumFPArgRegs.
2792     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2793                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2794
2795     FuncInfo->setVarArgsStackOffset(
2796       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2797                              CCInfo.getNextStackOffset(), true));
2798
2799     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2800     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2801
2802     // The fixed integer arguments of a variadic function are stored to the
2803     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2804     // the result of va_next.
2805     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2806       // Get an existing live-in vreg, or add a new one.
2807       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2808       if (!VReg)
2809         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2810
2811       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2812       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2813                                    MachinePointerInfo(), false, false, 0);
2814       MemOps.push_back(Store);
2815       // Increment the address by four for the next argument to store
2816       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2817       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2818     }
2819
2820     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2821     // is set.
2822     // The double arguments are stored to the VarArgsFrameIndex
2823     // on the stack.
2824     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2825       // Get an existing live-in vreg, or add a new one.
2826       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2827       if (!VReg)
2828         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2829
2830       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2831       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2832                                    MachinePointerInfo(), false, false, 0);
2833       MemOps.push_back(Store);
2834       // Increment the address by eight for the next argument to store
2835       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2836                                          PtrVT);
2837       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2838     }
2839   }
2840
2841   if (!MemOps.empty())
2842     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2843
2844   return Chain;
2845 }
2846
2847 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2848 // value to MVT::i64 and then truncate to the correct register size.
2849 SDValue
2850 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2851                                      SelectionDAG &DAG, SDValue ArgVal,
2852                                      SDLoc dl) const {
2853   if (Flags.isSExt())
2854     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2855                          DAG.getValueType(ObjectVT));
2856   else if (Flags.isZExt())
2857     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2858                          DAG.getValueType(ObjectVT));
2859
2860   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2861 }
2862
2863 SDValue
2864 PPCTargetLowering::LowerFormalArguments_64SVR4(
2865                                       SDValue Chain,
2866                                       CallingConv::ID CallConv, bool isVarArg,
2867                                       const SmallVectorImpl<ISD::InputArg>
2868                                         &Ins,
2869                                       SDLoc dl, SelectionDAG &DAG,
2870                                       SmallVectorImpl<SDValue> &InVals) const {
2871   // TODO: add description of PPC stack frame format, or at least some docs.
2872   //
2873   bool isELFv2ABI = Subtarget.isELFv2ABI();
2874   bool isLittleEndian = Subtarget.isLittleEndian();
2875   MachineFunction &MF = DAG.getMachineFunction();
2876   MachineFrameInfo *MFI = MF.getFrameInfo();
2877   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2878
2879   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2880          "fastcc not supported on varargs functions");
2881
2882   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2883   // Potential tail calls could cause overwriting of argument stack slots.
2884   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2885                        (CallConv == CallingConv::Fast));
2886   unsigned PtrByteSize = 8;
2887   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2888
2889   static const MCPhysReg GPR[] = {
2890     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2891     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2892   };
2893   static const MCPhysReg VR[] = {
2894     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2895     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2896   };
2897   static const MCPhysReg VSRH[] = {
2898     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2899     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2900   };
2901
2902   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2903   const unsigned Num_FPR_Regs = 13;
2904   const unsigned Num_VR_Regs  = array_lengthof(VR);
2905   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2906
2907   // Do a first pass over the arguments to determine whether the ABI
2908   // guarantees that our caller has allocated the parameter save area
2909   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2910   // in the ELFv2 ABI, it is true if this is a vararg function or if
2911   // any parameter is located in a stack slot.
2912
2913   bool HasParameterArea = !isELFv2ABI || isVarArg;
2914   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2915   unsigned NumBytes = LinkageSize;
2916   unsigned AvailableFPRs = Num_FPR_Regs;
2917   unsigned AvailableVRs = Num_VR_Regs;
2918   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2919     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2920                                PtrByteSize, LinkageSize, ParamAreaSize,
2921                                NumBytes, AvailableFPRs, AvailableVRs,
2922                                Subtarget.hasQPX()))
2923       HasParameterArea = true;
2924
2925   // Add DAG nodes to load the arguments or copy them out of registers.  On
2926   // entry to a function on PPC, the arguments start after the linkage area,
2927   // although the first ones are often in registers.
2928
2929   unsigned ArgOffset = LinkageSize;
2930   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2931   unsigned &QFPR_idx = FPR_idx;
2932   SmallVector<SDValue, 8> MemOps;
2933   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2934   unsigned CurArgIdx = 0;
2935   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2936     SDValue ArgVal;
2937     bool needsLoad = false;
2938     EVT ObjectVT = Ins[ArgNo].VT;
2939     EVT OrigVT = Ins[ArgNo].ArgVT;
2940     unsigned ObjSize = ObjectVT.getStoreSize();
2941     unsigned ArgSize = ObjSize;
2942     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2943     if (Ins[ArgNo].isOrigArg()) {
2944       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2945       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2946     }
2947     // We re-align the argument offset for each argument, except when using the
2948     // fast calling convention, when we need to make sure we do that only when
2949     // we'll actually use a stack slot.
2950     unsigned CurArgOffset, Align;
2951     auto ComputeArgOffset = [&]() {
2952       /* Respect alignment of argument on the stack.  */
2953       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2954       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2955       CurArgOffset = ArgOffset;
2956     };
2957
2958     if (CallConv != CallingConv::Fast) {
2959       ComputeArgOffset();
2960
2961       /* Compute GPR index associated with argument offset.  */
2962       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2963       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2964     }
2965
2966     // FIXME the codegen can be much improved in some cases.
2967     // We do not have to keep everything in memory.
2968     if (Flags.isByVal()) {
2969       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2970
2971       if (CallConv == CallingConv::Fast)
2972         ComputeArgOffset();
2973
2974       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2975       ObjSize = Flags.getByValSize();
2976       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2977       // Empty aggregate parameters do not take up registers.  Examples:
2978       //   struct { } a;
2979       //   union  { } b;
2980       //   int c[0];
2981       // etc.  However, we have to provide a place-holder in InVals, so
2982       // pretend we have an 8-byte item at the current address for that
2983       // purpose.
2984       if (!ObjSize) {
2985         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2986         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2987         InVals.push_back(FIN);
2988         continue;
2989       }
2990
2991       // Create a stack object covering all stack doublewords occupied
2992       // by the argument.  If the argument is (fully or partially) on
2993       // the stack, or if the argument is fully in registers but the
2994       // caller has allocated the parameter save anyway, we can refer
2995       // directly to the caller's stack frame.  Otherwise, create a
2996       // local copy in our own frame.
2997       int FI;
2998       if (HasParameterArea ||
2999           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3000         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3001       else
3002         FI = MFI->CreateStackObject(ArgSize, Align, false);
3003       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3004
3005       // Handle aggregates smaller than 8 bytes.
3006       if (ObjSize < PtrByteSize) {
3007         // The value of the object is its address, which differs from the
3008         // address of the enclosing doubleword on big-endian systems.
3009         SDValue Arg = FIN;
3010         if (!isLittleEndian) {
3011           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3012           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3013         }
3014         InVals.push_back(Arg);
3015
3016         if (GPR_idx != Num_GPR_Regs) {
3017           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3018           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3019           SDValue Store;
3020
3021           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3022             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3023                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3024             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3025                                       MachinePointerInfo(FuncArg),
3026                                       ObjType, false, false, 0);
3027           } else {
3028             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3029             // store the whole register as-is to the parameter save area
3030             // slot.
3031             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3032                                  MachinePointerInfo(FuncArg),
3033                                  false, false, 0);
3034           }
3035
3036           MemOps.push_back(Store);
3037         }
3038         // Whether we copied from a register or not, advance the offset
3039         // into the parameter save area by a full doubleword.
3040         ArgOffset += PtrByteSize;
3041         continue;
3042       }
3043
3044       // The value of the object is its address, which is the address of
3045       // its first stack doubleword.
3046       InVals.push_back(FIN);
3047
3048       // Store whatever pieces of the object are in registers to memory.
3049       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3050         if (GPR_idx == Num_GPR_Regs)
3051           break;
3052
3053         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3054         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3055         SDValue Addr = FIN;
3056         if (j) {
3057           SDValue Off = DAG.getConstant(j, PtrVT);
3058           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3059         }
3060         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3061                                      MachinePointerInfo(FuncArg, j),
3062                                      false, false, 0);
3063         MemOps.push_back(Store);
3064         ++GPR_idx;
3065       }
3066       ArgOffset += ArgSize;
3067       continue;
3068     }
3069
3070     switch (ObjectVT.getSimpleVT().SimpleTy) {
3071     default: llvm_unreachable("Unhandled argument type!");
3072     case MVT::i1:
3073     case MVT::i32:
3074     case MVT::i64:
3075       // These can be scalar arguments or elements of an integer array type
3076       // passed directly.  Clang may use those instead of "byval" aggregate
3077       // types to avoid forcing arguments to memory unnecessarily.
3078       if (GPR_idx != Num_GPR_Regs) {
3079         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3080         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3081
3082         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3083           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3084           // value to MVT::i64 and then truncate to the correct register size.
3085           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3086       } else {
3087         if (CallConv == CallingConv::Fast)
3088           ComputeArgOffset();
3089
3090         needsLoad = true;
3091         ArgSize = PtrByteSize;
3092       }
3093       if (CallConv != CallingConv::Fast || needsLoad)
3094         ArgOffset += 8;
3095       break;
3096
3097     case MVT::f32:
3098     case MVT::f64:
3099       // These can be scalar arguments or elements of a float array type
3100       // passed directly.  The latter are used to implement ELFv2 homogenous
3101       // float aggregates.
3102       if (FPR_idx != Num_FPR_Regs) {
3103         unsigned VReg;
3104
3105         if (ObjectVT == MVT::f32)
3106           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3107         else
3108           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3109                                                 ? &PPC::VSFRCRegClass
3110                                                 : &PPC::F8RCRegClass);
3111
3112         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3113         ++FPR_idx;
3114       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3115         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3116         // once we support fp <-> gpr moves.
3117
3118         // This can only ever happen in the presence of f32 array types,
3119         // since otherwise we never run out of FPRs before running out
3120         // of GPRs.
3121         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3122         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3123
3124         if (ObjectVT == MVT::f32) {
3125           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3126             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3127                                  DAG.getConstant(32, MVT::i32));
3128           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3129         }
3130
3131         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3132       } else {
3133         if (CallConv == CallingConv::Fast)
3134           ComputeArgOffset();
3135
3136         needsLoad = true;
3137       }
3138
3139       // When passing an array of floats, the array occupies consecutive
3140       // space in the argument area; only round up to the next doubleword
3141       // at the end of the array.  Otherwise, each float takes 8 bytes.
3142       if (CallConv != CallingConv::Fast || needsLoad) {
3143         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3144         ArgOffset += ArgSize;
3145         if (Flags.isInConsecutiveRegsLast())
3146           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3147       }
3148       break;
3149     case MVT::v4f32:
3150     case MVT::v4i32:
3151     case MVT::v8i16:
3152     case MVT::v16i8:
3153     case MVT::v2f64:
3154     case MVT::v2i64:
3155       if (!Subtarget.hasQPX()) {
3156       // These can be scalar arguments or elements of a vector array type
3157       // passed directly.  The latter are used to implement ELFv2 homogenous
3158       // vector aggregates.
3159       if (VR_idx != Num_VR_Regs) {
3160         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3161                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3162                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3163         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3164         ++VR_idx;
3165       } else {
3166         if (CallConv == CallingConv::Fast)
3167           ComputeArgOffset();
3168
3169         needsLoad = true;
3170       }
3171       if (CallConv != CallingConv::Fast || needsLoad)
3172         ArgOffset += 16;
3173       break;
3174       } // not QPX
3175
3176       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3177              "Invalid QPX parameter type");
3178       /* fall through */
3179
3180     case MVT::v4f64:
3181     case MVT::v4i1:
3182       // QPX vectors are treated like their scalar floating-point subregisters
3183       // (except that they're larger).
3184       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3185       if (QFPR_idx != Num_QFPR_Regs) {
3186         const TargetRegisterClass *RC;
3187         switch (ObjectVT.getSimpleVT().SimpleTy) {
3188         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3189         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3190         default:         RC = &PPC::QBRCRegClass; break;
3191         }
3192
3193         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3194         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3195         ++QFPR_idx;
3196       } else {
3197         if (CallConv == CallingConv::Fast)
3198           ComputeArgOffset();
3199         needsLoad = true;
3200       }
3201       if (CallConv != CallingConv::Fast || needsLoad)
3202         ArgOffset += Sz;
3203       break;
3204     }
3205
3206     // We need to load the argument to a virtual register if we determined
3207     // above that we ran out of physical registers of the appropriate type.
3208     if (needsLoad) {
3209       if (ObjSize < ArgSize && !isLittleEndian)
3210         CurArgOffset += ArgSize - ObjSize;
3211       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3212       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3213       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3214                            false, false, false, 0);
3215     }
3216
3217     InVals.push_back(ArgVal);
3218   }
3219
3220   // Area that is at least reserved in the caller of this function.
3221   unsigned MinReservedArea;
3222   if (HasParameterArea)
3223     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3224   else
3225     MinReservedArea = LinkageSize;
3226
3227   // Set the size that is at least reserved in caller of this function.  Tail
3228   // call optimized functions' reserved stack space needs to be aligned so that
3229   // taking the difference between two stack areas will result in an aligned
3230   // stack.
3231   MinReservedArea =
3232       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3233   FuncInfo->setMinReservedArea(MinReservedArea);
3234
3235   // If the function takes variable number of arguments, make a frame index for
3236   // the start of the first vararg value... for expansion of llvm.va_start.
3237   if (isVarArg) {
3238     int Depth = ArgOffset;
3239
3240     FuncInfo->setVarArgsFrameIndex(
3241       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3242     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3243
3244     // If this function is vararg, store any remaining integer argument regs
3245     // to their spots on the stack so that they may be loaded by deferencing the
3246     // result of va_next.
3247     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3248          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3249       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3250       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3251       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3252                                    MachinePointerInfo(), false, false, 0);
3253       MemOps.push_back(Store);
3254       // Increment the address by four for the next argument to store
3255       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3256       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3257     }
3258   }
3259
3260   if (!MemOps.empty())
3261     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3262
3263   return Chain;
3264 }
3265
3266 SDValue
3267 PPCTargetLowering::LowerFormalArguments_Darwin(
3268                                       SDValue Chain,
3269                                       CallingConv::ID CallConv, bool isVarArg,
3270                                       const SmallVectorImpl<ISD::InputArg>
3271                                         &Ins,
3272                                       SDLoc dl, SelectionDAG &DAG,
3273                                       SmallVectorImpl<SDValue> &InVals) const {
3274   // TODO: add description of PPC stack frame format, or at least some docs.
3275   //
3276   MachineFunction &MF = DAG.getMachineFunction();
3277   MachineFrameInfo *MFI = MF.getFrameInfo();
3278   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3279
3280   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3281   bool isPPC64 = PtrVT == MVT::i64;
3282   // Potential tail calls could cause overwriting of argument stack slots.
3283   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3284                        (CallConv == CallingConv::Fast));
3285   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3286   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3287   unsigned ArgOffset = LinkageSize;
3288   // Area that is at least reserved in caller of this function.
3289   unsigned MinReservedArea = ArgOffset;
3290
3291   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3292     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3293     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3294   };
3295   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3296     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3297     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3298   };
3299   static const MCPhysReg VR[] = {
3300     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3301     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3302   };
3303
3304   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3305   const unsigned Num_FPR_Regs = 13;
3306   const unsigned Num_VR_Regs  = array_lengthof( VR);
3307
3308   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3309
3310   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3311
3312   // In 32-bit non-varargs functions, the stack space for vectors is after the
3313   // stack space for non-vectors.  We do not use this space unless we have
3314   // too many vectors to fit in registers, something that only occurs in
3315   // constructed examples:), but we have to walk the arglist to figure
3316   // that out...for the pathological case, compute VecArgOffset as the
3317   // start of the vector parameter area.  Computing VecArgOffset is the
3318   // entire point of the following loop.
3319   unsigned VecArgOffset = ArgOffset;
3320   if (!isVarArg && !isPPC64) {
3321     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3322          ++ArgNo) {
3323       EVT ObjectVT = Ins[ArgNo].VT;
3324       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3325
3326       if (Flags.isByVal()) {
3327         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3328         unsigned ObjSize = Flags.getByValSize();
3329         unsigned ArgSize =
3330                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3331         VecArgOffset += ArgSize;
3332         continue;
3333       }
3334
3335       switch(ObjectVT.getSimpleVT().SimpleTy) {
3336       default: llvm_unreachable("Unhandled argument type!");
3337       case MVT::i1:
3338       case MVT::i32:
3339       case MVT::f32:
3340         VecArgOffset += 4;
3341         break;
3342       case MVT::i64:  // PPC64
3343       case MVT::f64:
3344         // FIXME: We are guaranteed to be !isPPC64 at this point.
3345         // Does MVT::i64 apply?
3346         VecArgOffset += 8;
3347         break;
3348       case MVT::v4f32:
3349       case MVT::v4i32:
3350       case MVT::v8i16:
3351       case MVT::v16i8:
3352         // Nothing to do, we're only looking at Nonvector args here.
3353         break;
3354       }
3355     }
3356   }
3357   // We've found where the vector parameter area in memory is.  Skip the
3358   // first 12 parameters; these don't use that memory.
3359   VecArgOffset = ((VecArgOffset+15)/16)*16;
3360   VecArgOffset += 12*16;
3361
3362   // Add DAG nodes to load the arguments or copy them out of registers.  On
3363   // entry to a function on PPC, the arguments start after the linkage area,
3364   // although the first ones are often in registers.
3365
3366   SmallVector<SDValue, 8> MemOps;
3367   unsigned nAltivecParamsAtEnd = 0;
3368   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3369   unsigned CurArgIdx = 0;
3370   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3371     SDValue ArgVal;
3372     bool needsLoad = false;
3373     EVT ObjectVT = Ins[ArgNo].VT;
3374     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3375     unsigned ArgSize = ObjSize;
3376     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3377     if (Ins[ArgNo].isOrigArg()) {
3378       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3379       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3380     }
3381     unsigned CurArgOffset = ArgOffset;
3382
3383     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3384     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3385         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3386       if (isVarArg || isPPC64) {
3387         MinReservedArea = ((MinReservedArea+15)/16)*16;
3388         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3389                                                   Flags,
3390                                                   PtrByteSize);
3391       } else  nAltivecParamsAtEnd++;
3392     } else
3393       // Calculate min reserved area.
3394       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3395                                                 Flags,
3396                                                 PtrByteSize);
3397
3398     // FIXME the codegen can be much improved in some cases.
3399     // We do not have to keep everything in memory.
3400     if (Flags.isByVal()) {
3401       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3402
3403       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3404       ObjSize = Flags.getByValSize();
3405       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3406       // Objects of size 1 and 2 are right justified, everything else is
3407       // left justified.  This means the memory address is adjusted forwards.
3408       if (ObjSize==1 || ObjSize==2) {
3409         CurArgOffset = CurArgOffset + (4 - ObjSize);
3410       }
3411       // The value of the object is its address.
3412       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3413       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3414       InVals.push_back(FIN);
3415       if (ObjSize==1 || ObjSize==2) {
3416         if (GPR_idx != Num_GPR_Regs) {
3417           unsigned VReg;
3418           if (isPPC64)
3419             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3420           else
3421             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3422           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3423           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3424           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3425                                             MachinePointerInfo(FuncArg),
3426                                             ObjType, false, false, 0);
3427           MemOps.push_back(Store);
3428           ++GPR_idx;
3429         }
3430
3431         ArgOffset += PtrByteSize;
3432
3433         continue;
3434       }
3435       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3436         // Store whatever pieces of the object are in registers
3437         // to memory.  ArgOffset will be the address of the beginning
3438         // of the object.
3439         if (GPR_idx != Num_GPR_Regs) {
3440           unsigned VReg;
3441           if (isPPC64)
3442             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3443           else
3444             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3445           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3446           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3447           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3448           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3449                                        MachinePointerInfo(FuncArg, j),
3450                                        false, false, 0);
3451           MemOps.push_back(Store);
3452           ++GPR_idx;
3453           ArgOffset += PtrByteSize;
3454         } else {
3455           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3456           break;
3457         }
3458       }
3459       continue;
3460     }
3461
3462     switch (ObjectVT.getSimpleVT().SimpleTy) {
3463     default: llvm_unreachable("Unhandled argument type!");
3464     case MVT::i1:
3465     case MVT::i32:
3466       if (!isPPC64) {
3467         if (GPR_idx != Num_GPR_Regs) {
3468           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3469           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3470
3471           if (ObjectVT == MVT::i1)
3472             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3473
3474           ++GPR_idx;
3475         } else {
3476           needsLoad = true;
3477           ArgSize = PtrByteSize;
3478         }
3479         // All int arguments reserve stack space in the Darwin ABI.
3480         ArgOffset += PtrByteSize;
3481         break;
3482       }
3483       // FALLTHROUGH
3484     case MVT::i64:  // PPC64
3485       if (GPR_idx != Num_GPR_Regs) {
3486         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3487         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3488
3489         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3490           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3491           // value to MVT::i64 and then truncate to the correct register size.
3492           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3493
3494         ++GPR_idx;
3495       } else {
3496         needsLoad = true;
3497         ArgSize = PtrByteSize;
3498       }
3499       // All int arguments reserve stack space in the Darwin ABI.
3500       ArgOffset += 8;
3501       break;
3502
3503     case MVT::f32:
3504     case MVT::f64:
3505       // Every 4 bytes of argument space consumes one of the GPRs available for
3506       // argument passing.
3507       if (GPR_idx != Num_GPR_Regs) {
3508         ++GPR_idx;
3509         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3510           ++GPR_idx;
3511       }
3512       if (FPR_idx != Num_FPR_Regs) {
3513         unsigned VReg;
3514
3515         if (ObjectVT == MVT::f32)
3516           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3517         else
3518           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3519
3520         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3521         ++FPR_idx;
3522       } else {
3523         needsLoad = true;
3524       }
3525
3526       // All FP arguments reserve stack space in the Darwin ABI.
3527       ArgOffset += isPPC64 ? 8 : ObjSize;
3528       break;
3529     case MVT::v4f32:
3530     case MVT::v4i32:
3531     case MVT::v8i16:
3532     case MVT::v16i8:
3533       // Note that vector arguments in registers don't reserve stack space,
3534       // except in varargs functions.
3535       if (VR_idx != Num_VR_Regs) {
3536         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3537         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3538         if (isVarArg) {
3539           while ((ArgOffset % 16) != 0) {
3540             ArgOffset += PtrByteSize;
3541             if (GPR_idx != Num_GPR_Regs)
3542               GPR_idx++;
3543           }
3544           ArgOffset += 16;
3545           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3546         }
3547         ++VR_idx;
3548       } else {
3549         if (!isVarArg && !isPPC64) {
3550           // Vectors go after all the nonvectors.
3551           CurArgOffset = VecArgOffset;
3552           VecArgOffset += 16;
3553         } else {
3554           // Vectors are aligned.
3555           ArgOffset = ((ArgOffset+15)/16)*16;
3556           CurArgOffset = ArgOffset;
3557           ArgOffset += 16;
3558         }
3559         needsLoad = true;
3560       }
3561       break;
3562     }
3563
3564     // We need to load the argument to a virtual register if we determined above
3565     // that we ran out of physical registers of the appropriate type.
3566     if (needsLoad) {
3567       int FI = MFI->CreateFixedObject(ObjSize,
3568                                       CurArgOffset + (ArgSize - ObjSize),
3569                                       isImmutable);
3570       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3571       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3572                            false, false, false, 0);
3573     }
3574
3575     InVals.push_back(ArgVal);
3576   }
3577
3578   // Allow for Altivec parameters at the end, if needed.
3579   if (nAltivecParamsAtEnd) {
3580     MinReservedArea = ((MinReservedArea+15)/16)*16;
3581     MinReservedArea += 16*nAltivecParamsAtEnd;
3582   }
3583
3584   // Area that is at least reserved in the caller of this function.
3585   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3586
3587   // Set the size that is at least reserved in caller of this function.  Tail
3588   // call optimized functions' reserved stack space needs to be aligned so that
3589   // taking the difference between two stack areas will result in an aligned
3590   // stack.
3591   MinReservedArea =
3592       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3593   FuncInfo->setMinReservedArea(MinReservedArea);
3594
3595   // If the function takes variable number of arguments, make a frame index for
3596   // the start of the first vararg value... for expansion of llvm.va_start.
3597   if (isVarArg) {
3598     int Depth = ArgOffset;
3599
3600     FuncInfo->setVarArgsFrameIndex(
3601       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3602                              Depth, true));
3603     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3604
3605     // If this function is vararg, store any remaining integer argument regs
3606     // to their spots on the stack so that they may be loaded by deferencing the
3607     // result of va_next.
3608     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3609       unsigned VReg;
3610
3611       if (isPPC64)
3612         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3613       else
3614         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3615
3616       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3617       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3618                                    MachinePointerInfo(), false, false, 0);
3619       MemOps.push_back(Store);
3620       // Increment the address by four for the next argument to store
3621       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3622       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3623     }
3624   }
3625
3626   if (!MemOps.empty())
3627     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3628
3629   return Chain;
3630 }
3631
3632 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3633 /// adjusted to accommodate the arguments for the tailcall.
3634 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3635                                    unsigned ParamSize) {
3636
3637   if (!isTailCall) return 0;
3638
3639   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3640   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3641   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3642   // Remember only if the new adjustement is bigger.
3643   if (SPDiff < FI->getTailCallSPDelta())
3644     FI->setTailCallSPDelta(SPDiff);
3645
3646   return SPDiff;
3647 }
3648
3649 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3650 /// for tail call optimization. Targets which want to do tail call
3651 /// optimization should implement this function.
3652 bool
3653 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3654                                                      CallingConv::ID CalleeCC,
3655                                                      bool isVarArg,
3656                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3657                                                      SelectionDAG& DAG) const {
3658   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3659     return false;
3660
3661   // Variable argument functions are not supported.
3662   if (isVarArg)
3663     return false;
3664
3665   MachineFunction &MF = DAG.getMachineFunction();
3666   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3667   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3668     // Functions containing by val parameters are not supported.
3669     for (unsigned i = 0; i != Ins.size(); i++) {
3670        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3671        if (Flags.isByVal()) return false;
3672     }
3673
3674     // Non-PIC/GOT tail calls are supported.
3675     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3676       return true;
3677
3678     // At the moment we can only do local tail calls (in same module, hidden
3679     // or protected) if we are generating PIC.
3680     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3681       return G->getGlobal()->hasHiddenVisibility()
3682           || G->getGlobal()->hasProtectedVisibility();
3683   }
3684
3685   return false;
3686 }
3687
3688 /// isCallCompatibleAddress - Return the immediate to use if the specified
3689 /// 32-bit value is representable in the immediate field of a BxA instruction.
3690 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3691   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3692   if (!C) return nullptr;
3693
3694   int Addr = C->getZExtValue();
3695   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3696       SignExtend32<26>(Addr) != Addr)
3697     return nullptr;  // Top 6 bits have to be sext of immediate.
3698
3699   return DAG.getConstant((int)C->getZExtValue() >> 2,
3700                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3701 }
3702
3703 namespace {
3704
3705 struct TailCallArgumentInfo {
3706   SDValue Arg;
3707   SDValue FrameIdxOp;
3708   int       FrameIdx;
3709
3710   TailCallArgumentInfo() : FrameIdx(0) {}
3711 };
3712
3713 }
3714
3715 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3716 static void
3717 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3718                                            SDValue Chain,
3719                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3720                    SmallVectorImpl<SDValue> &MemOpChains,
3721                    SDLoc dl) {
3722   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3723     SDValue Arg = TailCallArgs[i].Arg;
3724     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3725     int FI = TailCallArgs[i].FrameIdx;
3726     // Store relative to framepointer.
3727     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3728                                        MachinePointerInfo::getFixedStack(FI),
3729                                        false, false, 0));
3730   }
3731 }
3732
3733 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3734 /// the appropriate stack slot for the tail call optimized function call.
3735 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3736                                                MachineFunction &MF,
3737                                                SDValue Chain,
3738                                                SDValue OldRetAddr,
3739                                                SDValue OldFP,
3740                                                int SPDiff,
3741                                                bool isPPC64,
3742                                                bool isDarwinABI,
3743                                                SDLoc dl) {
3744   if (SPDiff) {
3745     // Calculate the new stack slot for the return address.
3746     int SlotSize = isPPC64 ? 8 : 4;
3747     const PPCFrameLowering *FL =
3748         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3749     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3750     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3751                                                           NewRetAddrLoc, true);
3752     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3753     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3754     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3755                          MachinePointerInfo::getFixedStack(NewRetAddr),
3756                          false, false, 0);
3757
3758     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3759     // slot as the FP is never overwritten.
3760     if (isDarwinABI) {
3761       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3762       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3763                                                           true);
3764       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3765       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3766                            MachinePointerInfo::getFixedStack(NewFPIdx),
3767                            false, false, 0);
3768     }
3769   }
3770   return Chain;
3771 }
3772
3773 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3774 /// the position of the argument.
3775 static void
3776 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3777                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3778                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3779   int Offset = ArgOffset + SPDiff;
3780   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3781   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3782   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3783   SDValue FIN = DAG.getFrameIndex(FI, VT);
3784   TailCallArgumentInfo Info;
3785   Info.Arg = Arg;
3786   Info.FrameIdxOp = FIN;
3787   Info.FrameIdx = FI;
3788   TailCallArguments.push_back(Info);
3789 }
3790
3791 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3792 /// stack slot. Returns the chain as result and the loaded frame pointers in
3793 /// LROpOut/FPOpout. Used when tail calling.
3794 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3795                                                         int SPDiff,
3796                                                         SDValue Chain,
3797                                                         SDValue &LROpOut,
3798                                                         SDValue &FPOpOut,
3799                                                         bool isDarwinABI,
3800                                                         SDLoc dl) const {
3801   if (SPDiff) {
3802     // Load the LR and FP stack slot for later adjusting.
3803     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3804     LROpOut = getReturnAddrFrameIndex(DAG);
3805     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3806                           false, false, false, 0);
3807     Chain = SDValue(LROpOut.getNode(), 1);
3808
3809     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3810     // slot as the FP is never overwritten.
3811     if (isDarwinABI) {
3812       FPOpOut = getFramePointerFrameIndex(DAG);
3813       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3814                             false, false, false, 0);
3815       Chain = SDValue(FPOpOut.getNode(), 1);
3816     }
3817   }
3818   return Chain;
3819 }
3820
3821 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3822 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3823 /// specified by the specific parameter attribute. The copy will be passed as
3824 /// a byval function parameter.
3825 /// Sometimes what we are copying is the end of a larger object, the part that
3826 /// does not fit in registers.
3827 static SDValue
3828 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3829                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3830                           SDLoc dl) {
3831   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3832   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3833                        false, false, MachinePointerInfo(),
3834                        MachinePointerInfo());
3835 }
3836
3837 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3838 /// tail calls.
3839 static void
3840 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3841                  SDValue Arg, SDValue PtrOff, int SPDiff,
3842                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3843                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3844                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3845                  SDLoc dl) {
3846   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3847   if (!isTailCall) {
3848     if (isVector) {
3849       SDValue StackPtr;
3850       if (isPPC64)
3851         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3852       else
3853         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3854       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3855                            DAG.getConstant(ArgOffset, PtrVT));
3856     }
3857     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3858                                        MachinePointerInfo(), false, false, 0));
3859   // Calculate and remember argument location.
3860   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3861                                   TailCallArguments);
3862 }
3863
3864 static
3865 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3866                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3867                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3868                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3869   MachineFunction &MF = DAG.getMachineFunction();
3870
3871   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3872   // might overwrite each other in case of tail call optimization.
3873   SmallVector<SDValue, 8> MemOpChains2;
3874   // Do not flag preceding copytoreg stuff together with the following stuff.
3875   InFlag = SDValue();
3876   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3877                                     MemOpChains2, dl);
3878   if (!MemOpChains2.empty())
3879     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3880
3881   // Store the return address to the appropriate stack slot.
3882   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3883                                         isPPC64, isDarwinABI, dl);
3884
3885   // Emit callseq_end just before tailcall node.
3886   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3887                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3888   InFlag = Chain.getValue(1);
3889 }
3890
3891 // Is this global address that of a function that can be called by name? (as
3892 // opposed to something that must hold a descriptor for an indirect call).
3893 static bool isFunctionGlobalAddress(SDValue Callee) {
3894   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3895     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3896         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3897       return false;
3898
3899     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3900   }
3901
3902   return false;
3903 }
3904
3905 static
3906 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3907                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3908                      bool isTailCall, bool IsPatchPoint,
3909                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3910                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3911                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3912
3913   bool isPPC64 = Subtarget.isPPC64();
3914   bool isSVR4ABI = Subtarget.isSVR4ABI();
3915   bool isELFv2ABI = Subtarget.isELFv2ABI();
3916
3917   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3918   NodeTys.push_back(MVT::Other);   // Returns a chain
3919   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3920
3921   unsigned CallOpc = PPCISD::CALL;
3922
3923   bool needIndirectCall = true;
3924   if (!isSVR4ABI || !isPPC64)
3925     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3926       // If this is an absolute destination address, use the munged value.
3927       Callee = SDValue(Dest, 0);
3928       needIndirectCall = false;
3929     }
3930
3931   if (isFunctionGlobalAddress(Callee)) {
3932     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3933     // A call to a TLS address is actually an indirect call to a
3934     // thread-specific pointer.
3935     unsigned OpFlags = 0;
3936     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3937          (Subtarget.getTargetTriple().isMacOSX() &&
3938           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3939          (G->getGlobal()->isDeclaration() ||
3940           G->getGlobal()->isWeakForLinker())) ||
3941         (Subtarget.isTargetELF() && !isPPC64 &&
3942          !G->getGlobal()->hasLocalLinkage() &&
3943          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3944       // PC-relative references to external symbols should go through $stub,
3945       // unless we're building with the leopard linker or later, which
3946       // automatically synthesizes these stubs.
3947       OpFlags = PPCII::MO_PLT_OR_STUB;
3948     }
3949
3950     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3951     // every direct call is) turn it into a TargetGlobalAddress /
3952     // TargetExternalSymbol node so that legalize doesn't hack it.
3953     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3954                                         Callee.getValueType(), 0, OpFlags);
3955     needIndirectCall = false;
3956   }
3957
3958   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3959     unsigned char OpFlags = 0;
3960
3961     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3962          (Subtarget.getTargetTriple().isMacOSX() &&
3963           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3964         (Subtarget.isTargetELF() && !isPPC64 &&
3965          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3966       // PC-relative references to external symbols should go through $stub,
3967       // unless we're building with the leopard linker or later, which
3968       // automatically synthesizes these stubs.
3969       OpFlags = PPCII::MO_PLT_OR_STUB;
3970     }
3971
3972     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3973                                          OpFlags);
3974     needIndirectCall = false;
3975   }
3976
3977   if (IsPatchPoint) {
3978     // We'll form an invalid direct call when lowering a patchpoint; the full
3979     // sequence for an indirect call is complicated, and many of the
3980     // instructions introduced might have side effects (and, thus, can't be
3981     // removed later). The call itself will be removed as soon as the
3982     // argument/return lowering is complete, so the fact that it has the wrong
3983     // kind of operands should not really matter.
3984     needIndirectCall = false;
3985   }
3986
3987   if (needIndirectCall) {
3988     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3989     // to do the call, we can't use PPCISD::CALL.
3990     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3991
3992     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3993       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3994       // entry point, but to the function descriptor (the function entry point
3995       // address is part of the function descriptor though).
3996       // The function descriptor is a three doubleword structure with the
3997       // following fields: function entry point, TOC base address and
3998       // environment pointer.
3999       // Thus for a call through a function pointer, the following actions need
4000       // to be performed:
4001       //   1. Save the TOC of the caller in the TOC save area of its stack
4002       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4003       //   2. Load the address of the function entry point from the function
4004       //      descriptor.
4005       //   3. Load the TOC of the callee from the function descriptor into r2.
4006       //   4. Load the environment pointer from the function descriptor into
4007       //      r11.
4008       //   5. Branch to the function entry point address.
4009       //   6. On return of the callee, the TOC of the caller needs to be
4010       //      restored (this is done in FinishCall()).
4011       //
4012       // The loads are scheduled at the beginning of the call sequence, and the
4013       // register copies are flagged together to ensure that no other
4014       // operations can be scheduled in between. E.g. without flagging the
4015       // copies together, a TOC access in the caller could be scheduled between
4016       // the assignment of the callee TOC and the branch to the callee, which
4017       // results in the TOC access going through the TOC of the callee instead
4018       // of going through the TOC of the caller, which leads to incorrect code.
4019
4020       // Load the address of the function entry point from the function
4021       // descriptor.
4022       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4023       if (LDChain.getValueType() == MVT::Glue)
4024         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4025
4026       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4027
4028       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4029       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4030                                         false, false, LoadsInv, 8);
4031
4032       // Load environment pointer into r11.
4033       SDValue PtrOff = DAG.getIntPtrConstant(16);
4034       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4035       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4036                                        MPI.getWithOffset(16), false, false,
4037                                        LoadsInv, 8);
4038
4039       SDValue TOCOff = DAG.getIntPtrConstant(8);
4040       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4041       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4042                                    MPI.getWithOffset(8), false, false,
4043                                    LoadsInv, 8);
4044
4045       setUsesTOCBasePtr(DAG);
4046       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4047                                         InFlag);
4048       Chain = TOCVal.getValue(0);
4049       InFlag = TOCVal.getValue(1);
4050
4051       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4052                                         InFlag);
4053
4054       Chain = EnvVal.getValue(0);
4055       InFlag = EnvVal.getValue(1);
4056
4057       MTCTROps[0] = Chain;
4058       MTCTROps[1] = LoadFuncPtr;
4059       MTCTROps[2] = InFlag;
4060     }
4061
4062     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4063                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4064     InFlag = Chain.getValue(1);
4065
4066     NodeTys.clear();
4067     NodeTys.push_back(MVT::Other);
4068     NodeTys.push_back(MVT::Glue);
4069     Ops.push_back(Chain);
4070     CallOpc = PPCISD::BCTRL;
4071     Callee.setNode(nullptr);
4072     // Add use of X11 (holding environment pointer)
4073     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4074       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4075     // Add CTR register as callee so a bctr can be emitted later.
4076     if (isTailCall)
4077       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4078   }
4079
4080   // If this is a direct call, pass the chain and the callee.
4081   if (Callee.getNode()) {
4082     Ops.push_back(Chain);
4083     Ops.push_back(Callee);
4084   }
4085   // If this is a tail call add stack pointer delta.
4086   if (isTailCall)
4087     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4088
4089   // Add argument registers to the end of the list so that they are known live
4090   // into the call.
4091   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4092     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4093                                   RegsToPass[i].second.getValueType()));
4094
4095   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4096   // into the call.
4097   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4098     setUsesTOCBasePtr(DAG);
4099     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4100   }
4101
4102   return CallOpc;
4103 }
4104
4105 static
4106 bool isLocalCall(const SDValue &Callee)
4107 {
4108   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4109     return !G->getGlobal()->isDeclaration() &&
4110            !G->getGlobal()->isWeakForLinker();
4111   return false;
4112 }
4113
4114 SDValue
4115 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4116                                    CallingConv::ID CallConv, bool isVarArg,
4117                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4118                                    SDLoc dl, SelectionDAG &DAG,
4119                                    SmallVectorImpl<SDValue> &InVals) const {
4120
4121   SmallVector<CCValAssign, 16> RVLocs;
4122   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4123                     *DAG.getContext());
4124   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4125
4126   // Copy all of the result registers out of their specified physreg.
4127   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4128     CCValAssign &VA = RVLocs[i];
4129     assert(VA.isRegLoc() && "Can only return in registers!");
4130
4131     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4132                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4133     Chain = Val.getValue(1);
4134     InFlag = Val.getValue(2);
4135
4136     switch (VA.getLocInfo()) {
4137     default: llvm_unreachable("Unknown loc info!");
4138     case CCValAssign::Full: break;
4139     case CCValAssign::AExt:
4140       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4141       break;
4142     case CCValAssign::ZExt:
4143       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4144                         DAG.getValueType(VA.getValVT()));
4145       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4146       break;
4147     case CCValAssign::SExt:
4148       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4149                         DAG.getValueType(VA.getValVT()));
4150       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4151       break;
4152     }
4153
4154     InVals.push_back(Val);
4155   }
4156
4157   return Chain;
4158 }
4159
4160 SDValue
4161 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4162                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4163                               SelectionDAG &DAG,
4164                               SmallVector<std::pair<unsigned, SDValue>, 8>
4165                                 &RegsToPass,
4166                               SDValue InFlag, SDValue Chain,
4167                               SDValue CallSeqStart, SDValue &Callee,
4168                               int SPDiff, unsigned NumBytes,
4169                               const SmallVectorImpl<ISD::InputArg> &Ins,
4170                               SmallVectorImpl<SDValue> &InVals,
4171                               ImmutableCallSite *CS) const {
4172
4173   std::vector<EVT> NodeTys;
4174   SmallVector<SDValue, 8> Ops;
4175   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4176                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4177                                  Ops, NodeTys, CS, Subtarget);
4178
4179   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4180   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4181     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4182
4183   // When performing tail call optimization the callee pops its arguments off
4184   // the stack. Account for this here so these bytes can be pushed back on in
4185   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4186   int BytesCalleePops =
4187     (CallConv == CallingConv::Fast &&
4188      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4189
4190   // Add a register mask operand representing the call-preserved registers.
4191   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4192   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
4193   assert(Mask && "Missing call preserved mask for calling convention");
4194   Ops.push_back(DAG.getRegisterMask(Mask));
4195
4196   if (InFlag.getNode())
4197     Ops.push_back(InFlag);
4198
4199   // Emit tail call.
4200   if (isTailCall) {
4201     assert(((Callee.getOpcode() == ISD::Register &&
4202              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4203             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4204             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4205             isa<ConstantSDNode>(Callee)) &&
4206     "Expecting an global address, external symbol, absolute value or register");
4207
4208     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4209   }
4210
4211   // Add a NOP immediately after the branch instruction when using the 64-bit
4212   // SVR4 ABI. At link time, if caller and callee are in a different module and
4213   // thus have a different TOC, the call will be replaced with a call to a stub
4214   // function which saves the current TOC, loads the TOC of the callee and
4215   // branches to the callee. The NOP will be replaced with a load instruction
4216   // which restores the TOC of the caller from the TOC save slot of the current
4217   // stack frame. If caller and callee belong to the same module (and have the
4218   // same TOC), the NOP will remain unchanged.
4219
4220   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4221       !IsPatchPoint) {
4222     if (CallOpc == PPCISD::BCTRL) {
4223       // This is a call through a function pointer.
4224       // Restore the caller TOC from the save area into R2.
4225       // See PrepareCall() for more information about calls through function
4226       // pointers in the 64-bit SVR4 ABI.
4227       // We are using a target-specific load with r2 hard coded, because the
4228       // result of a target-independent load would never go directly into r2,
4229       // since r2 is a reserved register (which prevents the register allocator
4230       // from allocating it), resulting in an additional register being
4231       // allocated and an unnecessary move instruction being generated.
4232       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4233
4234       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4235       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4236       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4237       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4238       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4239
4240       // The address needs to go after the chain input but before the flag (or
4241       // any other variadic arguments).
4242       Ops.insert(std::next(Ops.begin()), AddTOC);
4243     } else if ((CallOpc == PPCISD::CALL) &&
4244                (!isLocalCall(Callee) ||
4245                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4246       // Otherwise insert NOP for non-local calls.
4247       CallOpc = PPCISD::CALL_NOP;
4248   }
4249
4250   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4251   InFlag = Chain.getValue(1);
4252
4253   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4254                              DAG.getIntPtrConstant(BytesCalleePops, true),
4255                              InFlag, dl);
4256   if (!Ins.empty())
4257     InFlag = Chain.getValue(1);
4258
4259   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4260                          Ins, dl, DAG, InVals);
4261 }
4262
4263 SDValue
4264 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4265                              SmallVectorImpl<SDValue> &InVals) const {
4266   SelectionDAG &DAG                     = CLI.DAG;
4267   SDLoc &dl                             = CLI.DL;
4268   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4269   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4270   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4271   SDValue Chain                         = CLI.Chain;
4272   SDValue Callee                        = CLI.Callee;
4273   bool &isTailCall                      = CLI.IsTailCall;
4274   CallingConv::ID CallConv              = CLI.CallConv;
4275   bool isVarArg                         = CLI.IsVarArg;
4276   bool IsPatchPoint                     = CLI.IsPatchPoint;
4277   ImmutableCallSite *CS                 = CLI.CS;
4278
4279   if (isTailCall)
4280     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4281                                                    Ins, DAG);
4282
4283   if (!isTailCall && CS && CS->isMustTailCall())
4284     report_fatal_error("failed to perform tail call elimination on a call "
4285                        "site marked musttail");
4286
4287   if (Subtarget.isSVR4ABI()) {
4288     if (Subtarget.isPPC64())
4289       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4290                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4291                               dl, DAG, InVals, CS);
4292     else
4293       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4294                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4295                               dl, DAG, InVals, CS);
4296   }
4297
4298   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4299                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4300                           dl, DAG, InVals, CS);
4301 }
4302
4303 SDValue
4304 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4305                                     CallingConv::ID CallConv, bool isVarArg,
4306                                     bool isTailCall, bool IsPatchPoint,
4307                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4308                                     const SmallVectorImpl<SDValue> &OutVals,
4309                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4310                                     SDLoc dl, SelectionDAG &DAG,
4311                                     SmallVectorImpl<SDValue> &InVals,
4312                                     ImmutableCallSite *CS) const {
4313   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4314   // of the 32-bit SVR4 ABI stack frame layout.
4315
4316   assert((CallConv == CallingConv::C ||
4317           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4318
4319   unsigned PtrByteSize = 4;
4320
4321   MachineFunction &MF = DAG.getMachineFunction();
4322
4323   // Mark this function as potentially containing a function that contains a
4324   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4325   // and restoring the callers stack pointer in this functions epilog. This is
4326   // done because by tail calling the called function might overwrite the value
4327   // in this function's (MF) stack pointer stack slot 0(SP).
4328   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4329       CallConv == CallingConv::Fast)
4330     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4331
4332   // Count how many bytes are to be pushed on the stack, including the linkage
4333   // area, parameter list area and the part of the local variable space which
4334   // contains copies of aggregates which are passed by value.
4335
4336   // Assign locations to all of the outgoing arguments.
4337   SmallVector<CCValAssign, 16> ArgLocs;
4338   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4339                  *DAG.getContext());
4340
4341   // Reserve space for the linkage area on the stack.
4342   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4343                        PtrByteSize);
4344
4345   if (isVarArg) {
4346     // Handle fixed and variable vector arguments differently.
4347     // Fixed vector arguments go into registers as long as registers are
4348     // available. Variable vector arguments always go into memory.
4349     unsigned NumArgs = Outs.size();
4350
4351     for (unsigned i = 0; i != NumArgs; ++i) {
4352       MVT ArgVT = Outs[i].VT;
4353       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4354       bool Result;
4355
4356       if (Outs[i].IsFixed) {
4357         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4358                                CCInfo);
4359       } else {
4360         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4361                                       ArgFlags, CCInfo);
4362       }
4363
4364       if (Result) {
4365 #ifndef NDEBUG
4366         errs() << "Call operand #" << i << " has unhandled type "
4367              << EVT(ArgVT).getEVTString() << "\n";
4368 #endif
4369         llvm_unreachable(nullptr);
4370       }
4371     }
4372   } else {
4373     // All arguments are treated the same.
4374     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4375   }
4376
4377   // Assign locations to all of the outgoing aggregate by value arguments.
4378   SmallVector<CCValAssign, 16> ByValArgLocs;
4379   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4380                       ByValArgLocs, *DAG.getContext());
4381
4382   // Reserve stack space for the allocations in CCInfo.
4383   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4384
4385   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4386
4387   // Size of the linkage area, parameter list area and the part of the local
4388   // space variable where copies of aggregates which are passed by value are
4389   // stored.
4390   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4391
4392   // Calculate by how many bytes the stack has to be adjusted in case of tail
4393   // call optimization.
4394   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4395
4396   // Adjust the stack pointer for the new arguments...
4397   // These operations are automatically eliminated by the prolog/epilog pass
4398   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4399                                dl);
4400   SDValue CallSeqStart = Chain;
4401
4402   // Load the return address and frame pointer so it can be moved somewhere else
4403   // later.
4404   SDValue LROp, FPOp;
4405   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4406                                        dl);
4407
4408   // Set up a copy of the stack pointer for use loading and storing any
4409   // arguments that may not fit in the registers available for argument
4410   // passing.
4411   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4412
4413   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4414   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4415   SmallVector<SDValue, 8> MemOpChains;
4416
4417   bool seenFloatArg = false;
4418   // Walk the register/memloc assignments, inserting copies/loads.
4419   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4420        i != e;
4421        ++i) {
4422     CCValAssign &VA = ArgLocs[i];
4423     SDValue Arg = OutVals[i];
4424     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4425
4426     if (Flags.isByVal()) {
4427       // Argument is an aggregate which is passed by value, thus we need to
4428       // create a copy of it in the local variable space of the current stack
4429       // frame (which is the stack frame of the caller) and pass the address of
4430       // this copy to the callee.
4431       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4432       CCValAssign &ByValVA = ByValArgLocs[j++];
4433       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4434
4435       // Memory reserved in the local variable space of the callers stack frame.
4436       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4437
4438       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4439       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4440
4441       // Create a copy of the argument in the local area of the current
4442       // stack frame.
4443       SDValue MemcpyCall =
4444         CreateCopyOfByValArgument(Arg, PtrOff,
4445                                   CallSeqStart.getNode()->getOperand(0),
4446                                   Flags, DAG, dl);
4447
4448       // This must go outside the CALLSEQ_START..END.
4449       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4450                            CallSeqStart.getNode()->getOperand(1),
4451                            SDLoc(MemcpyCall));
4452       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4453                              NewCallSeqStart.getNode());
4454       Chain = CallSeqStart = NewCallSeqStart;
4455
4456       // Pass the address of the aggregate copy on the stack either in a
4457       // physical register or in the parameter list area of the current stack
4458       // frame to the callee.
4459       Arg = PtrOff;
4460     }
4461
4462     if (VA.isRegLoc()) {
4463       if (Arg.getValueType() == MVT::i1)
4464         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4465
4466       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4467       // Put argument in a physical register.
4468       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4469     } else {
4470       // Put argument in the parameter list area of the current stack frame.
4471       assert(VA.isMemLoc());
4472       unsigned LocMemOffset = VA.getLocMemOffset();
4473
4474       if (!isTailCall) {
4475         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4476         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4477
4478         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4479                                            MachinePointerInfo(),
4480                                            false, false, 0));
4481       } else {
4482         // Calculate and remember argument location.
4483         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4484                                  TailCallArguments);
4485       }
4486     }
4487   }
4488
4489   if (!MemOpChains.empty())
4490     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4491
4492   // Build a sequence of copy-to-reg nodes chained together with token chain
4493   // and flag operands which copy the outgoing args into the appropriate regs.
4494   SDValue InFlag;
4495   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4496     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4497                              RegsToPass[i].second, InFlag);
4498     InFlag = Chain.getValue(1);
4499   }
4500
4501   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4502   // registers.
4503   if (isVarArg) {
4504     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4505     SDValue Ops[] = { Chain, InFlag };
4506
4507     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4508                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4509
4510     InFlag = Chain.getValue(1);
4511   }
4512
4513   if (isTailCall)
4514     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4515                     false, TailCallArguments);
4516
4517   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4518                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4519                     NumBytes, Ins, InVals, CS);
4520 }
4521
4522 // Copy an argument into memory, being careful to do this outside the
4523 // call sequence for the call to which the argument belongs.
4524 SDValue
4525 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4526                                               SDValue CallSeqStart,
4527                                               ISD::ArgFlagsTy Flags,
4528                                               SelectionDAG &DAG,
4529                                               SDLoc dl) const {
4530   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4531                         CallSeqStart.getNode()->getOperand(0),
4532                         Flags, DAG, dl);
4533   // The MEMCPY must go outside the CALLSEQ_START..END.
4534   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4535                              CallSeqStart.getNode()->getOperand(1),
4536                              SDLoc(MemcpyCall));
4537   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4538                          NewCallSeqStart.getNode());
4539   return NewCallSeqStart;
4540 }
4541
4542 SDValue
4543 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4544                                     CallingConv::ID CallConv, bool isVarArg,
4545                                     bool isTailCall, bool IsPatchPoint,
4546                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4547                                     const SmallVectorImpl<SDValue> &OutVals,
4548                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4549                                     SDLoc dl, SelectionDAG &DAG,
4550                                     SmallVectorImpl<SDValue> &InVals,
4551                                     ImmutableCallSite *CS) const {
4552
4553   bool isELFv2ABI = Subtarget.isELFv2ABI();
4554   bool isLittleEndian = Subtarget.isLittleEndian();
4555   unsigned NumOps = Outs.size();
4556
4557   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4558   unsigned PtrByteSize = 8;
4559
4560   MachineFunction &MF = DAG.getMachineFunction();
4561
4562   // Mark this function as potentially containing a function that contains a
4563   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4564   // and restoring the callers stack pointer in this functions epilog. This is
4565   // done because by tail calling the called function might overwrite the value
4566   // in this function's (MF) stack pointer stack slot 0(SP).
4567   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4568       CallConv == CallingConv::Fast)
4569     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4570
4571   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4572          "fastcc not supported on varargs functions");
4573
4574   // Count how many bytes are to be pushed on the stack, including the linkage
4575   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4576   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4577   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4578   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4579   unsigned NumBytes = LinkageSize;
4580   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4581   unsigned &QFPR_idx = FPR_idx;
4582
4583   static const MCPhysReg GPR[] = {
4584     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4585     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4586   };
4587   static const MCPhysReg VR[] = {
4588     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4589     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4590   };
4591   static const MCPhysReg VSRH[] = {
4592     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4593     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4594   };
4595
4596   const unsigned NumGPRs = array_lengthof(GPR);
4597   const unsigned NumFPRs = 13;
4598   const unsigned NumVRs  = array_lengthof(VR);
4599   const unsigned NumQFPRs = NumFPRs;
4600
4601   // When using the fast calling convention, we don't provide backing for
4602   // arguments that will be in registers.
4603   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4604
4605   // Add up all the space actually used.
4606   for (unsigned i = 0; i != NumOps; ++i) {
4607     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4608     EVT ArgVT = Outs[i].VT;
4609     EVT OrigVT = Outs[i].ArgVT;
4610
4611     if (CallConv == CallingConv::Fast) {
4612       if (Flags.isByVal())
4613         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4614       else
4615         switch (ArgVT.getSimpleVT().SimpleTy) {
4616         default: llvm_unreachable("Unexpected ValueType for argument!");
4617         case MVT::i1:
4618         case MVT::i32:
4619         case MVT::i64:
4620           if (++NumGPRsUsed <= NumGPRs)
4621             continue;
4622           break;
4623         case MVT::v4i32:
4624         case MVT::v8i16:
4625         case MVT::v16i8:
4626         case MVT::v2f64:
4627         case MVT::v2i64:
4628           if (++NumVRsUsed <= NumVRs)
4629             continue;
4630           break;
4631         case MVT::v4f32:
4632           // When using QPX, this is handled like a FP register, otherwise, it
4633           // is an Altivec register.
4634           if (Subtarget.hasQPX()) {
4635             if (++NumFPRsUsed <= NumFPRs)
4636               continue;
4637           } else {
4638             if (++NumVRsUsed <= NumVRs)
4639               continue;
4640           }
4641           break;
4642         case MVT::f32:
4643         case MVT::f64:
4644         case MVT::v4f64: // QPX
4645         case MVT::v4i1:  // QPX
4646           if (++NumFPRsUsed <= NumFPRs)
4647             continue;
4648           break;
4649         }
4650     }
4651
4652     /* Respect alignment of argument on the stack.  */
4653     unsigned Align =
4654       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4655     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4656
4657     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4658     if (Flags.isInConsecutiveRegsLast())
4659       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4660   }
4661
4662   unsigned NumBytesActuallyUsed = NumBytes;
4663
4664   // The prolog code of the callee may store up to 8 GPR argument registers to
4665   // the stack, allowing va_start to index over them in memory if its varargs.
4666   // Because we cannot tell if this is needed on the caller side, we have to
4667   // conservatively assume that it is needed.  As such, make sure we have at
4668   // least enough stack space for the caller to store the 8 GPRs.
4669   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4670   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4671
4672   // Tail call needs the stack to be aligned.
4673   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4674       CallConv == CallingConv::Fast)
4675     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4676
4677   // Calculate by how many bytes the stack has to be adjusted in case of tail
4678   // call optimization.
4679   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4680
4681   // To protect arguments on the stack from being clobbered in a tail call,
4682   // force all the loads to happen before doing any other lowering.
4683   if (isTailCall)
4684     Chain = DAG.getStackArgumentTokenFactor(Chain);
4685
4686   // Adjust the stack pointer for the new arguments...
4687   // These operations are automatically eliminated by the prolog/epilog pass
4688   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4689                                dl);
4690   SDValue CallSeqStart = Chain;
4691
4692   // Load the return address and frame pointer so it can be move somewhere else
4693   // later.
4694   SDValue LROp, FPOp;
4695   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4696                                        dl);
4697
4698   // Set up a copy of the stack pointer for use loading and storing any
4699   // arguments that may not fit in the registers available for argument
4700   // passing.
4701   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4702
4703   // Figure out which arguments are going to go in registers, and which in
4704   // memory.  Also, if this is a vararg function, floating point operations
4705   // must be stored to our stack, and loaded into integer regs as well, if
4706   // any integer regs are available for argument passing.
4707   unsigned ArgOffset = LinkageSize;
4708
4709   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4710   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4711
4712   SmallVector<SDValue, 8> MemOpChains;
4713   for (unsigned i = 0; i != NumOps; ++i) {
4714     SDValue Arg = OutVals[i];
4715     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4716     EVT ArgVT = Outs[i].VT;
4717     EVT OrigVT = Outs[i].ArgVT;
4718
4719     // PtrOff will be used to store the current argument to the stack if a
4720     // register cannot be found for it.
4721     SDValue PtrOff;
4722
4723     // We re-align the argument offset for each argument, except when using the
4724     // fast calling convention, when we need to make sure we do that only when
4725     // we'll actually use a stack slot.
4726     auto ComputePtrOff = [&]() {
4727       /* Respect alignment of argument on the stack.  */
4728       unsigned Align =
4729         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4730       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4731
4732       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4733
4734       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4735     };
4736
4737     if (CallConv != CallingConv::Fast) {
4738       ComputePtrOff();
4739
4740       /* Compute GPR index associated with argument offset.  */
4741       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4742       GPR_idx = std::min(GPR_idx, NumGPRs);
4743     }
4744
4745     // Promote integers to 64-bit values.
4746     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4747       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4748       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4749       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4750     }
4751
4752     // FIXME memcpy is used way more than necessary.  Correctness first.
4753     // Note: "by value" is code for passing a structure by value, not
4754     // basic types.
4755     if (Flags.isByVal()) {
4756       // Note: Size includes alignment padding, so
4757       //   struct x { short a; char b; }
4758       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4759       // These are the proper values we need for right-justifying the
4760       // aggregate in a parameter register.
4761       unsigned Size = Flags.getByValSize();
4762
4763       // An empty aggregate parameter takes up no storage and no
4764       // registers.
4765       if (Size == 0)
4766         continue;
4767
4768       if (CallConv == CallingConv::Fast)
4769         ComputePtrOff();
4770
4771       // All aggregates smaller than 8 bytes must be passed right-justified.
4772       if (Size==1 || Size==2 || Size==4) {
4773         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4774         if (GPR_idx != NumGPRs) {
4775           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4776                                         MachinePointerInfo(), VT,
4777                                         false, false, false, 0);
4778           MemOpChains.push_back(Load.getValue(1));
4779           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4780
4781           ArgOffset += PtrByteSize;
4782           continue;
4783         }
4784       }
4785
4786       if (GPR_idx == NumGPRs && Size < 8) {
4787         SDValue AddPtr = PtrOff;
4788         if (!isLittleEndian) {
4789           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4790                                           PtrOff.getValueType());
4791           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4792         }
4793         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4794                                                           CallSeqStart,
4795                                                           Flags, DAG, dl);
4796         ArgOffset += PtrByteSize;
4797         continue;
4798       }
4799       // Copy entire object into memory.  There are cases where gcc-generated
4800       // code assumes it is there, even if it could be put entirely into
4801       // registers.  (This is not what the doc says.)
4802
4803       // FIXME: The above statement is likely due to a misunderstanding of the
4804       // documents.  All arguments must be copied into the parameter area BY
4805       // THE CALLEE in the event that the callee takes the address of any
4806       // formal argument.  That has not yet been implemented.  However, it is
4807       // reasonable to use the stack area as a staging area for the register
4808       // load.
4809
4810       // Skip this for small aggregates, as we will use the same slot for a
4811       // right-justified copy, below.
4812       if (Size >= 8)
4813         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4814                                                           CallSeqStart,
4815                                                           Flags, DAG, dl);
4816
4817       // When a register is available, pass a small aggregate right-justified.
4818       if (Size < 8 && GPR_idx != NumGPRs) {
4819         // The easiest way to get this right-justified in a register
4820         // is to copy the structure into the rightmost portion of a
4821         // local variable slot, then load the whole slot into the
4822         // register.
4823         // FIXME: The memcpy seems to produce pretty awful code for
4824         // small aggregates, particularly for packed ones.
4825         // FIXME: It would be preferable to use the slot in the
4826         // parameter save area instead of a new local variable.
4827         SDValue AddPtr = PtrOff;
4828         if (!isLittleEndian) {
4829           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4830           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4831         }
4832         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4833                                                           CallSeqStart,
4834                                                           Flags, DAG, dl);
4835
4836         // Load the slot into the register.
4837         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4838                                    MachinePointerInfo(),
4839                                    false, false, false, 0);
4840         MemOpChains.push_back(Load.getValue(1));
4841         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4842
4843         // Done with this argument.
4844         ArgOffset += PtrByteSize;
4845         continue;
4846       }
4847
4848       // For aggregates larger than PtrByteSize, copy the pieces of the
4849       // object that fit into registers from the parameter save area.
4850       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4851         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4852         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4853         if (GPR_idx != NumGPRs) {
4854           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4855                                      MachinePointerInfo(),
4856                                      false, false, false, 0);
4857           MemOpChains.push_back(Load.getValue(1));
4858           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4859           ArgOffset += PtrByteSize;
4860         } else {
4861           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4862           break;
4863         }
4864       }
4865       continue;
4866     }
4867
4868     switch (Arg.getSimpleValueType().SimpleTy) {
4869     default: llvm_unreachable("Unexpected ValueType for argument!");
4870     case MVT::i1:
4871     case MVT::i32:
4872     case MVT::i64:
4873       // These can be scalar arguments or elements of an integer array type
4874       // passed directly.  Clang may use those instead of "byval" aggregate
4875       // types to avoid forcing arguments to memory unnecessarily.
4876       if (GPR_idx != NumGPRs) {
4877         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4878       } else {
4879         if (CallConv == CallingConv::Fast)
4880           ComputePtrOff();
4881
4882         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4883                          true, isTailCall, false, MemOpChains,
4884                          TailCallArguments, dl);
4885         if (CallConv == CallingConv::Fast)
4886           ArgOffset += PtrByteSize;
4887       }
4888       if (CallConv != CallingConv::Fast)
4889         ArgOffset += PtrByteSize;
4890       break;
4891     case MVT::f32:
4892     case MVT::f64: {
4893       // These can be scalar arguments or elements of a float array type
4894       // passed directly.  The latter are used to implement ELFv2 homogenous
4895       // float aggregates.
4896
4897       // Named arguments go into FPRs first, and once they overflow, the
4898       // remaining arguments go into GPRs and then the parameter save area.
4899       // Unnamed arguments for vararg functions always go to GPRs and
4900       // then the parameter save area.  For now, put all arguments to vararg
4901       // routines always in both locations (FPR *and* GPR or stack slot).
4902       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4903       bool NeededLoad = false;
4904
4905       // First load the argument into the next available FPR.
4906       if (FPR_idx != NumFPRs)
4907         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4908
4909       // Next, load the argument into GPR or stack slot if needed.
4910       if (!NeedGPROrStack)
4911         ;
4912       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4913         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4914         // once we support fp <-> gpr moves.
4915
4916         // In the non-vararg case, this can only ever happen in the
4917         // presence of f32 array types, since otherwise we never run
4918         // out of FPRs before running out of GPRs.
4919         SDValue ArgVal;
4920
4921         // Double values are always passed in a single GPR.
4922         if (Arg.getValueType() != MVT::f32) {
4923           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4924
4925         // Non-array float values are extended and passed in a GPR.
4926         } else if (!Flags.isInConsecutiveRegs()) {
4927           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4928           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4929
4930         // If we have an array of floats, we collect every odd element
4931         // together with its predecessor into one GPR.
4932         } else if (ArgOffset % PtrByteSize != 0) {
4933           SDValue Lo, Hi;
4934           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4935           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4936           if (!isLittleEndian)
4937             std::swap(Lo, Hi);
4938           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4939
4940         // The final element, if even, goes into the first half of a GPR.
4941         } else if (Flags.isInConsecutiveRegsLast()) {
4942           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4943           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4944           if (!isLittleEndian)
4945             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4946                                  DAG.getConstant(32, MVT::i32));
4947
4948         // Non-final even elements are skipped; they will be handled
4949         // together the with subsequent argument on the next go-around.
4950         } else
4951           ArgVal = SDValue();
4952
4953         if (ArgVal.getNode())
4954           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4955       } else {
4956         if (CallConv == CallingConv::Fast)
4957           ComputePtrOff();
4958
4959         // Single-precision floating-point values are mapped to the
4960         // second (rightmost) word of the stack doubleword.
4961         if (Arg.getValueType() == MVT::f32 &&
4962             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4963           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4964           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4965         }
4966
4967         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4968                          true, isTailCall, false, MemOpChains,
4969                          TailCallArguments, dl);
4970
4971         NeededLoad = true;
4972       }
4973       // When passing an array of floats, the array occupies consecutive
4974       // space in the argument area; only round up to the next doubleword
4975       // at the end of the array.  Otherwise, each float takes 8 bytes.
4976       if (CallConv != CallingConv::Fast || NeededLoad) {
4977         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4978                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4979         if (Flags.isInConsecutiveRegsLast())
4980           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4981       }
4982       break;
4983     }
4984     case MVT::v4f32:
4985     case MVT::v4i32:
4986     case MVT::v8i16:
4987     case MVT::v16i8:
4988     case MVT::v2f64:
4989     case MVT::v2i64:
4990       if (!Subtarget.hasQPX()) {
4991       // These can be scalar arguments or elements of a vector array type
4992       // passed directly.  The latter are used to implement ELFv2 homogenous
4993       // vector aggregates.
4994
4995       // For a varargs call, named arguments go into VRs or on the stack as
4996       // usual; unnamed arguments always go to the stack or the corresponding
4997       // GPRs when within range.  For now, we always put the value in both
4998       // locations (or even all three).
4999       if (isVarArg) {
5000         // We could elide this store in the case where the object fits
5001         // entirely in R registers.  Maybe later.
5002         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5003                                      MachinePointerInfo(), false, false, 0);
5004         MemOpChains.push_back(Store);
5005         if (VR_idx != NumVRs) {
5006           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5007                                      MachinePointerInfo(),
5008                                      false, false, false, 0);
5009           MemOpChains.push_back(Load.getValue(1));
5010
5011           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5012                            Arg.getSimpleValueType() == MVT::v2i64) ?
5013                           VSRH[VR_idx] : VR[VR_idx];
5014           ++VR_idx;
5015
5016           RegsToPass.push_back(std::make_pair(VReg, Load));
5017         }
5018         ArgOffset += 16;
5019         for (unsigned i=0; i<16; i+=PtrByteSize) {
5020           if (GPR_idx == NumGPRs)
5021             break;
5022           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5023                                   DAG.getConstant(i, PtrVT));
5024           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5025                                      false, false, false, 0);
5026           MemOpChains.push_back(Load.getValue(1));
5027           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5028         }
5029         break;
5030       }
5031
5032       // Non-varargs Altivec params go into VRs or on the stack.
5033       if (VR_idx != NumVRs) {
5034         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5035                          Arg.getSimpleValueType() == MVT::v2i64) ?
5036                         VSRH[VR_idx] : VR[VR_idx];
5037         ++VR_idx;
5038
5039         RegsToPass.push_back(std::make_pair(VReg, Arg));
5040       } else {
5041         if (CallConv == CallingConv::Fast)
5042           ComputePtrOff();
5043
5044         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5045                          true, isTailCall, true, MemOpChains,
5046                          TailCallArguments, dl);
5047         if (CallConv == CallingConv::Fast)
5048           ArgOffset += 16;
5049       }
5050
5051       if (CallConv != CallingConv::Fast)
5052         ArgOffset += 16;
5053       break;
5054       } // not QPX
5055
5056       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5057              "Invalid QPX parameter type");
5058
5059       /* fall through */
5060     case MVT::v4f64:
5061     case MVT::v4i1: {
5062       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5063       if (isVarArg) {
5064         // We could elide this store in the case where the object fits
5065         // entirely in R registers.  Maybe later.
5066         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5067                                      MachinePointerInfo(), false, false, 0);
5068         MemOpChains.push_back(Store);
5069         if (QFPR_idx != NumQFPRs) {
5070           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5071                                      Store, PtrOff, MachinePointerInfo(),
5072                                      false, false, false, 0);
5073           MemOpChains.push_back(Load.getValue(1));
5074           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5075         }
5076         ArgOffset += (IsF32 ? 16 : 32);
5077         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5078           if (GPR_idx == NumGPRs)
5079             break;
5080           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5081                                   DAG.getConstant(i, PtrVT));
5082           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5083                                      false, false, false, 0);
5084           MemOpChains.push_back(Load.getValue(1));
5085           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5086         }
5087         break;
5088       }
5089
5090       // Non-varargs QPX params go into registers or on the stack.
5091       if (QFPR_idx != NumQFPRs) {
5092         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5093       } else {
5094         if (CallConv == CallingConv::Fast)
5095           ComputePtrOff();
5096
5097         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5098                          true, isTailCall, true, MemOpChains,
5099                          TailCallArguments, dl);
5100         if (CallConv == CallingConv::Fast)
5101           ArgOffset += (IsF32 ? 16 : 32);
5102       }
5103
5104       if (CallConv != CallingConv::Fast)
5105         ArgOffset += (IsF32 ? 16 : 32);
5106       break;
5107       }
5108     }
5109   }
5110
5111   assert(NumBytesActuallyUsed == ArgOffset);
5112   (void)NumBytesActuallyUsed;
5113
5114   if (!MemOpChains.empty())
5115     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5116
5117   // Check if this is an indirect call (MTCTR/BCTRL).
5118   // See PrepareCall() for more information about calls through function
5119   // pointers in the 64-bit SVR4 ABI.
5120   if (!isTailCall && !IsPatchPoint &&
5121       !isFunctionGlobalAddress(Callee) &&
5122       !isa<ExternalSymbolSDNode>(Callee)) {
5123     // Load r2 into a virtual register and store it to the TOC save area.
5124     setUsesTOCBasePtr(DAG);
5125     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5126     // TOC save area offset.
5127     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5128     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5129     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5130     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5131                          MachinePointerInfo::getStack(TOCSaveOffset),
5132                          false, false, 0);
5133     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5134     // This does not mean the MTCTR instruction must use R12; it's easier
5135     // to model this as an extra parameter, so do that.
5136     if (isELFv2ABI && !IsPatchPoint)
5137       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5138   }
5139
5140   // Build a sequence of copy-to-reg nodes chained together with token chain
5141   // and flag operands which copy the outgoing args into the appropriate regs.
5142   SDValue InFlag;
5143   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5144     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5145                              RegsToPass[i].second, InFlag);
5146     InFlag = Chain.getValue(1);
5147   }
5148
5149   if (isTailCall)
5150     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5151                     FPOp, true, TailCallArguments);
5152
5153   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5154                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5155                     NumBytes, Ins, InVals, CS);
5156 }
5157
5158 SDValue
5159 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5160                                     CallingConv::ID CallConv, bool isVarArg,
5161                                     bool isTailCall, bool IsPatchPoint,
5162                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5163                                     const SmallVectorImpl<SDValue> &OutVals,
5164                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5165                                     SDLoc dl, SelectionDAG &DAG,
5166                                     SmallVectorImpl<SDValue> &InVals,
5167                                     ImmutableCallSite *CS) const {
5168
5169   unsigned NumOps = Outs.size();
5170
5171   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5172   bool isPPC64 = PtrVT == MVT::i64;
5173   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5174
5175   MachineFunction &MF = DAG.getMachineFunction();
5176
5177   // Mark this function as potentially containing a function that contains a
5178   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5179   // and restoring the callers stack pointer in this functions epilog. This is
5180   // done because by tail calling the called function might overwrite the value
5181   // in this function's (MF) stack pointer stack slot 0(SP).
5182   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5183       CallConv == CallingConv::Fast)
5184     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5185
5186   // Count how many bytes are to be pushed on the stack, including the linkage
5187   // area, and parameter passing area.  We start with 24/48 bytes, which is
5188   // prereserved space for [SP][CR][LR][3 x unused].
5189   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5190   unsigned NumBytes = LinkageSize;
5191
5192   // Add up all the space actually used.
5193   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5194   // they all go in registers, but we must reserve stack space for them for
5195   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5196   // assigned stack space in order, with padding so Altivec parameters are
5197   // 16-byte aligned.
5198   unsigned nAltivecParamsAtEnd = 0;
5199   for (unsigned i = 0; i != NumOps; ++i) {
5200     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5201     EVT ArgVT = Outs[i].VT;
5202     // Varargs Altivec parameters are padded to a 16 byte boundary.
5203     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5204         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5205         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5206       if (!isVarArg && !isPPC64) {
5207         // Non-varargs Altivec parameters go after all the non-Altivec
5208         // parameters; handle those later so we know how much padding we need.
5209         nAltivecParamsAtEnd++;
5210         continue;
5211       }
5212       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5213       NumBytes = ((NumBytes+15)/16)*16;
5214     }
5215     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5216   }
5217
5218   // Allow for Altivec parameters at the end, if needed.
5219   if (nAltivecParamsAtEnd) {
5220     NumBytes = ((NumBytes+15)/16)*16;
5221     NumBytes += 16*nAltivecParamsAtEnd;
5222   }
5223
5224   // The prolog code of the callee may store up to 8 GPR argument registers to
5225   // the stack, allowing va_start to index over them in memory if its varargs.
5226   // Because we cannot tell if this is needed on the caller side, we have to
5227   // conservatively assume that it is needed.  As such, make sure we have at
5228   // least enough stack space for the caller to store the 8 GPRs.
5229   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5230
5231   // Tail call needs the stack to be aligned.
5232   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5233       CallConv == CallingConv::Fast)
5234     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5235
5236   // Calculate by how many bytes the stack has to be adjusted in case of tail
5237   // call optimization.
5238   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5239
5240   // To protect arguments on the stack from being clobbered in a tail call,
5241   // force all the loads to happen before doing any other lowering.
5242   if (isTailCall)
5243     Chain = DAG.getStackArgumentTokenFactor(Chain);
5244
5245   // Adjust the stack pointer for the new arguments...
5246   // These operations are automatically eliminated by the prolog/epilog pass
5247   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5248                                dl);
5249   SDValue CallSeqStart = Chain;
5250
5251   // Load the return address and frame pointer so it can be move somewhere else
5252   // later.
5253   SDValue LROp, FPOp;
5254   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5255                                        dl);
5256
5257   // Set up a copy of the stack pointer for use loading and storing any
5258   // arguments that may not fit in the registers available for argument
5259   // passing.
5260   SDValue StackPtr;
5261   if (isPPC64)
5262     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5263   else
5264     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5265
5266   // Figure out which arguments are going to go in registers, and which in
5267   // memory.  Also, if this is a vararg function, floating point operations
5268   // must be stored to our stack, and loaded into integer regs as well, if
5269   // any integer regs are available for argument passing.
5270   unsigned ArgOffset = LinkageSize;
5271   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5272
5273   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5274     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5275     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5276   };
5277   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5278     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5279     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5280   };
5281   static const MCPhysReg VR[] = {
5282     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5283     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5284   };
5285   const unsigned NumGPRs = array_lengthof(GPR_32);
5286   const unsigned NumFPRs = 13;
5287   const unsigned NumVRs  = array_lengthof(VR);
5288
5289   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5290
5291   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5292   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5293
5294   SmallVector<SDValue, 8> MemOpChains;
5295   for (unsigned i = 0; i != NumOps; ++i) {
5296     SDValue Arg = OutVals[i];
5297     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5298
5299     // PtrOff will be used to store the current argument to the stack if a
5300     // register cannot be found for it.
5301     SDValue PtrOff;
5302
5303     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5304
5305     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5306
5307     // On PPC64, promote integers to 64-bit values.
5308     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5309       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5310       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5311       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5312     }
5313
5314     // FIXME memcpy is used way more than necessary.  Correctness first.
5315     // Note: "by value" is code for passing a structure by value, not
5316     // basic types.
5317     if (Flags.isByVal()) {
5318       unsigned Size = Flags.getByValSize();
5319       // Very small objects are passed right-justified.  Everything else is
5320       // passed left-justified.
5321       if (Size==1 || Size==2) {
5322         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5323         if (GPR_idx != NumGPRs) {
5324           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5325                                         MachinePointerInfo(), VT,
5326                                         false, false, false, 0);
5327           MemOpChains.push_back(Load.getValue(1));
5328           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5329
5330           ArgOffset += PtrByteSize;
5331         } else {
5332           SDValue Const = DAG.getConstant(PtrByteSize - Size,
5333                                           PtrOff.getValueType());
5334           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5335           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5336                                                             CallSeqStart,
5337                                                             Flags, DAG, dl);
5338           ArgOffset += PtrByteSize;
5339         }
5340         continue;
5341       }
5342       // Copy entire object into memory.  There are cases where gcc-generated
5343       // code assumes it is there, even if it could be put entirely into
5344       // registers.  (This is not what the doc says.)
5345       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5346                                                         CallSeqStart,
5347                                                         Flags, DAG, dl);
5348
5349       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5350       // copy the pieces of the object that fit into registers from the
5351       // parameter save area.
5352       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5353         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5354         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5355         if (GPR_idx != NumGPRs) {
5356           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5357                                      MachinePointerInfo(),
5358                                      false, false, false, 0);
5359           MemOpChains.push_back(Load.getValue(1));
5360           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5361           ArgOffset += PtrByteSize;
5362         } else {
5363           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5364           break;
5365         }
5366       }
5367       continue;
5368     }
5369
5370     switch (Arg.getSimpleValueType().SimpleTy) {
5371     default: llvm_unreachable("Unexpected ValueType for argument!");
5372     case MVT::i1:
5373     case MVT::i32:
5374     case MVT::i64:
5375       if (GPR_idx != NumGPRs) {
5376         if (Arg.getValueType() == MVT::i1)
5377           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5378
5379         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5380       } else {
5381         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5382                          isPPC64, isTailCall, false, MemOpChains,
5383                          TailCallArguments, dl);
5384       }
5385       ArgOffset += PtrByteSize;
5386       break;
5387     case MVT::f32:
5388     case MVT::f64:
5389       if (FPR_idx != NumFPRs) {
5390         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5391
5392         if (isVarArg) {
5393           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5394                                        MachinePointerInfo(), false, false, 0);
5395           MemOpChains.push_back(Store);
5396
5397           // Float varargs are always shadowed in available integer registers
5398           if (GPR_idx != NumGPRs) {
5399             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5400                                        MachinePointerInfo(), false, false,
5401                                        false, 0);
5402             MemOpChains.push_back(Load.getValue(1));
5403             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5404           }
5405           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5406             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5407             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5408             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5409                                        MachinePointerInfo(),
5410                                        false, false, false, 0);
5411             MemOpChains.push_back(Load.getValue(1));
5412             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5413           }
5414         } else {
5415           // If we have any FPRs remaining, we may also have GPRs remaining.
5416           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5417           // GPRs.
5418           if (GPR_idx != NumGPRs)
5419             ++GPR_idx;
5420           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5421               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5422             ++GPR_idx;
5423         }
5424       } else
5425         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5426                          isPPC64, isTailCall, false, MemOpChains,
5427                          TailCallArguments, dl);
5428       if (isPPC64)
5429         ArgOffset += 8;
5430       else
5431         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5432       break;
5433     case MVT::v4f32:
5434     case MVT::v4i32:
5435     case MVT::v8i16:
5436     case MVT::v16i8:
5437       if (isVarArg) {
5438         // These go aligned on the stack, or in the corresponding R registers
5439         // when within range.  The Darwin PPC ABI doc claims they also go in
5440         // V registers; in fact gcc does this only for arguments that are
5441         // prototyped, not for those that match the ...  We do it for all
5442         // arguments, seems to work.
5443         while (ArgOffset % 16 !=0) {
5444           ArgOffset += PtrByteSize;
5445           if (GPR_idx != NumGPRs)
5446             GPR_idx++;
5447         }
5448         // We could elide this store in the case where the object fits
5449         // entirely in R registers.  Maybe later.
5450         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5451                             DAG.getConstant(ArgOffset, PtrVT));
5452         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5453                                      MachinePointerInfo(), false, false, 0);
5454         MemOpChains.push_back(Store);
5455         if (VR_idx != NumVRs) {
5456           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5457                                      MachinePointerInfo(),
5458                                      false, false, false, 0);
5459           MemOpChains.push_back(Load.getValue(1));
5460           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5461         }
5462         ArgOffset += 16;
5463         for (unsigned i=0; i<16; i+=PtrByteSize) {
5464           if (GPR_idx == NumGPRs)
5465             break;
5466           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5467                                   DAG.getConstant(i, PtrVT));
5468           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5469                                      false, false, false, 0);
5470           MemOpChains.push_back(Load.getValue(1));
5471           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5472         }
5473         break;
5474       }
5475
5476       // Non-varargs Altivec params generally go in registers, but have
5477       // stack space allocated at the end.
5478       if (VR_idx != NumVRs) {
5479         // Doesn't have GPR space allocated.
5480         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5481       } else if (nAltivecParamsAtEnd==0) {
5482         // We are emitting Altivec params in order.
5483         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5484                          isPPC64, isTailCall, true, MemOpChains,
5485                          TailCallArguments, dl);
5486         ArgOffset += 16;
5487       }
5488       break;
5489     }
5490   }
5491   // If all Altivec parameters fit in registers, as they usually do,
5492   // they get stack space following the non-Altivec parameters.  We
5493   // don't track this here because nobody below needs it.
5494   // If there are more Altivec parameters than fit in registers emit
5495   // the stores here.
5496   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5497     unsigned j = 0;
5498     // Offset is aligned; skip 1st 12 params which go in V registers.
5499     ArgOffset = ((ArgOffset+15)/16)*16;
5500     ArgOffset += 12*16;
5501     for (unsigned i = 0; i != NumOps; ++i) {
5502       SDValue Arg = OutVals[i];
5503       EVT ArgType = Outs[i].VT;
5504       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5505           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5506         if (++j > NumVRs) {
5507           SDValue PtrOff;
5508           // We are emitting Altivec params in order.
5509           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5510                            isPPC64, isTailCall, true, MemOpChains,
5511                            TailCallArguments, dl);
5512           ArgOffset += 16;
5513         }
5514       }
5515     }
5516   }
5517
5518   if (!MemOpChains.empty())
5519     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5520
5521   // On Darwin, R12 must contain the address of an indirect callee.  This does
5522   // not mean the MTCTR instruction must use R12; it's easier to model this as
5523   // an extra parameter, so do that.
5524   if (!isTailCall &&
5525       !isFunctionGlobalAddress(Callee) &&
5526       !isa<ExternalSymbolSDNode>(Callee) &&
5527       !isBLACompatibleAddress(Callee, DAG))
5528     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5529                                                    PPC::R12), Callee));
5530
5531   // Build a sequence of copy-to-reg nodes chained together with token chain
5532   // and flag operands which copy the outgoing args into the appropriate regs.
5533   SDValue InFlag;
5534   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5535     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5536                              RegsToPass[i].second, InFlag);
5537     InFlag = Chain.getValue(1);
5538   }
5539
5540   if (isTailCall)
5541     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5542                     FPOp, true, TailCallArguments);
5543
5544   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5545                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5546                     NumBytes, Ins, InVals, CS);
5547 }
5548
5549 bool
5550 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5551                                   MachineFunction &MF, bool isVarArg,
5552                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5553                                   LLVMContext &Context) const {
5554   SmallVector<CCValAssign, 16> RVLocs;
5555   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5556   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5557 }
5558
5559 SDValue
5560 PPCTargetLowering::LowerReturn(SDValue Chain,
5561                                CallingConv::ID CallConv, bool isVarArg,
5562                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5563                                const SmallVectorImpl<SDValue> &OutVals,
5564                                SDLoc dl, SelectionDAG &DAG) const {
5565
5566   SmallVector<CCValAssign, 16> RVLocs;
5567   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5568                  *DAG.getContext());
5569   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5570
5571   SDValue Flag;
5572   SmallVector<SDValue, 4> RetOps(1, Chain);
5573
5574   // Copy the result values into the output registers.
5575   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5576     CCValAssign &VA = RVLocs[i];
5577     assert(VA.isRegLoc() && "Can only return in registers!");
5578
5579     SDValue Arg = OutVals[i];
5580
5581     switch (VA.getLocInfo()) {
5582     default: llvm_unreachable("Unknown loc info!");
5583     case CCValAssign::Full: break;
5584     case CCValAssign::AExt:
5585       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5586       break;
5587     case CCValAssign::ZExt:
5588       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5589       break;
5590     case CCValAssign::SExt:
5591       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5592       break;
5593     }
5594
5595     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5596     Flag = Chain.getValue(1);
5597     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5598   }
5599
5600   RetOps[0] = Chain;  // Update chain.
5601
5602   // Add the flag if we have it.
5603   if (Flag.getNode())
5604     RetOps.push_back(Flag);
5605
5606   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5607 }
5608
5609 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5610                                    const PPCSubtarget &Subtarget) const {
5611   // When we pop the dynamic allocation we need to restore the SP link.
5612   SDLoc dl(Op);
5613
5614   // Get the corect type for pointers.
5615   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5616
5617   // Construct the stack pointer operand.
5618   bool isPPC64 = Subtarget.isPPC64();
5619   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5620   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5621
5622   // Get the operands for the STACKRESTORE.
5623   SDValue Chain = Op.getOperand(0);
5624   SDValue SaveSP = Op.getOperand(1);
5625
5626   // Load the old link SP.
5627   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5628                                    MachinePointerInfo(),
5629                                    false, false, false, 0);
5630
5631   // Restore the stack pointer.
5632   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5633
5634   // Store the old link SP.
5635   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5636                       false, false, 0);
5637 }
5638
5639
5640
5641 SDValue
5642 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5643   MachineFunction &MF = DAG.getMachineFunction();
5644   bool isPPC64 = Subtarget.isPPC64();
5645   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5646
5647   // Get current frame pointer save index.  The users of this index will be
5648   // primarily DYNALLOC instructions.
5649   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5650   int RASI = FI->getReturnAddrSaveIndex();
5651
5652   // If the frame pointer save index hasn't been defined yet.
5653   if (!RASI) {
5654     // Find out what the fix offset of the frame pointer save area.
5655     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5656     // Allocate the frame index for frame pointer save area.
5657     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5658     // Save the result.
5659     FI->setReturnAddrSaveIndex(RASI);
5660   }
5661   return DAG.getFrameIndex(RASI, PtrVT);
5662 }
5663
5664 SDValue
5665 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5666   MachineFunction &MF = DAG.getMachineFunction();
5667   bool isPPC64 = Subtarget.isPPC64();
5668   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5669
5670   // Get current frame pointer save index.  The users of this index will be
5671   // primarily DYNALLOC instructions.
5672   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5673   int FPSI = FI->getFramePointerSaveIndex();
5674
5675   // If the frame pointer save index hasn't been defined yet.
5676   if (!FPSI) {
5677     // Find out what the fix offset of the frame pointer save area.
5678     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5679     // Allocate the frame index for frame pointer save area.
5680     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5681     // Save the result.
5682     FI->setFramePointerSaveIndex(FPSI);
5683   }
5684   return DAG.getFrameIndex(FPSI, PtrVT);
5685 }
5686
5687 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5688                                          SelectionDAG &DAG,
5689                                          const PPCSubtarget &Subtarget) const {
5690   // Get the inputs.
5691   SDValue Chain = Op.getOperand(0);
5692   SDValue Size  = Op.getOperand(1);
5693   SDLoc dl(Op);
5694
5695   // Get the corect type for pointers.
5696   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5697   // Negate the size.
5698   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5699                                   DAG.getConstant(0, PtrVT), Size);
5700   // Construct a node for the frame pointer save index.
5701   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5702   // Build a DYNALLOC node.
5703   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5704   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5705   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5706 }
5707
5708 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5709                                                SelectionDAG &DAG) const {
5710   SDLoc DL(Op);
5711   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5712                      DAG.getVTList(MVT::i32, MVT::Other),
5713                      Op.getOperand(0), Op.getOperand(1));
5714 }
5715
5716 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5717                                                 SelectionDAG &DAG) const {
5718   SDLoc DL(Op);
5719   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5720                      Op.getOperand(0), Op.getOperand(1));
5721 }
5722
5723 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5724   if (Op.getValueType().isVector())
5725     return LowerVectorLoad(Op, DAG);
5726
5727   assert(Op.getValueType() == MVT::i1 &&
5728          "Custom lowering only for i1 loads");
5729
5730   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5731
5732   SDLoc dl(Op);
5733   LoadSDNode *LD = cast<LoadSDNode>(Op);
5734
5735   SDValue Chain = LD->getChain();
5736   SDValue BasePtr = LD->getBasePtr();
5737   MachineMemOperand *MMO = LD->getMemOperand();
5738
5739   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5740                                  BasePtr, MVT::i8, MMO);
5741   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5742
5743   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5744   return DAG.getMergeValues(Ops, dl);
5745 }
5746
5747 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5748   if (Op.getOperand(1).getValueType().isVector())
5749     return LowerVectorStore(Op, DAG);
5750
5751   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5752          "Custom lowering only for i1 stores");
5753
5754   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5755
5756   SDLoc dl(Op);
5757   StoreSDNode *ST = cast<StoreSDNode>(Op);
5758
5759   SDValue Chain = ST->getChain();
5760   SDValue BasePtr = ST->getBasePtr();
5761   SDValue Value = ST->getValue();
5762   MachineMemOperand *MMO = ST->getMemOperand();
5763
5764   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5765   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5766 }
5767
5768 // FIXME: Remove this once the ANDI glue bug is fixed:
5769 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5770   assert(Op.getValueType() == MVT::i1 &&
5771          "Custom lowering only for i1 results");
5772
5773   SDLoc DL(Op);
5774   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5775                      Op.getOperand(0));
5776 }
5777
5778 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5779 /// possible.
5780 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5781   // Not FP? Not a fsel.
5782   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5783       !Op.getOperand(2).getValueType().isFloatingPoint())
5784     return Op;
5785
5786   // We might be able to do better than this under some circumstances, but in
5787   // general, fsel-based lowering of select is a finite-math-only optimization.
5788   // For more information, see section F.3 of the 2.06 ISA specification.
5789   if (!DAG.getTarget().Options.NoInfsFPMath ||
5790       !DAG.getTarget().Options.NoNaNsFPMath)
5791     return Op;
5792
5793   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5794
5795   EVT ResVT = Op.getValueType();
5796   EVT CmpVT = Op.getOperand(0).getValueType();
5797   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5798   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5799   SDLoc dl(Op);
5800
5801   // If the RHS of the comparison is a 0.0, we don't need to do the
5802   // subtraction at all.
5803   SDValue Sel1;
5804   if (isFloatingPointZero(RHS))
5805     switch (CC) {
5806     default: break;       // SETUO etc aren't handled by fsel.
5807     case ISD::SETNE:
5808       std::swap(TV, FV);
5809     case ISD::SETEQ:
5810       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5811         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5812       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5813       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5814         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5815       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5816                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5817     case ISD::SETULT:
5818     case ISD::SETLT:
5819       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5820     case ISD::SETOGE:
5821     case ISD::SETGE:
5822       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5823         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5824       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5825     case ISD::SETUGT:
5826     case ISD::SETGT:
5827       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5828     case ISD::SETOLE:
5829     case ISD::SETLE:
5830       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5831         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5832       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5833                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5834     }
5835
5836   SDValue Cmp;
5837   switch (CC) {
5838   default: break;       // SETUO etc aren't handled by fsel.
5839   case ISD::SETNE:
5840     std::swap(TV, FV);
5841   case ISD::SETEQ:
5842     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5843     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5844       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5845     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5846     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5847       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5848     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5849                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5850   case ISD::SETULT:
5851   case ISD::SETLT:
5852     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5853     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5854       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5855     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5856   case ISD::SETOGE:
5857   case ISD::SETGE:
5858     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5859     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5860       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5861     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5862   case ISD::SETUGT:
5863   case ISD::SETGT:
5864     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5865     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5866       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5867     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5868   case ISD::SETOLE:
5869   case ISD::SETLE:
5870     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5871     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5872       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5873     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5874   }
5875   return Op;
5876 }
5877
5878 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5879                                                SelectionDAG &DAG,
5880                                                SDLoc dl) const {
5881   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5882   SDValue Src = Op.getOperand(0);
5883   if (Src.getValueType() == MVT::f32)
5884     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5885
5886   SDValue Tmp;
5887   switch (Op.getSimpleValueType().SimpleTy) {
5888   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5889   case MVT::i32:
5890     Tmp = DAG.getNode(
5891         Op.getOpcode() == ISD::FP_TO_SINT
5892             ? PPCISD::FCTIWZ
5893             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5894         dl, MVT::f64, Src);
5895     break;
5896   case MVT::i64:
5897     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5898            "i64 FP_TO_UINT is supported only with FPCVT");
5899     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5900                                                         PPCISD::FCTIDUZ,
5901                       dl, MVT::f64, Src);
5902     break;
5903   }
5904
5905   // Convert the FP value to an int value through memory.
5906   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5907     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5908   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5909   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5910   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5911
5912   // Emit a store to the stack slot.
5913   SDValue Chain;
5914   if (i32Stack) {
5915     MachineFunction &MF = DAG.getMachineFunction();
5916     MachineMemOperand *MMO =
5917       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5918     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5919     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5920               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5921   } else
5922     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5923                          MPI, false, false, 0);
5924
5925   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5926   // add in a bias.
5927   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5928     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5929                         DAG.getConstant(4, FIPtr.getValueType()));
5930     MPI = MPI.getWithOffset(4);
5931   }
5932
5933   RLI.Chain = Chain;
5934   RLI.Ptr = FIPtr;
5935   RLI.MPI = MPI;
5936 }
5937
5938 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5939                                           SDLoc dl) const {
5940   ReuseLoadInfo RLI;
5941   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5942
5943   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5944                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5945                      RLI.Ranges);
5946 }
5947
5948 // We're trying to insert a regular store, S, and then a load, L. If the
5949 // incoming value, O, is a load, we might just be able to have our load use the
5950 // address used by O. However, we don't know if anything else will store to
5951 // that address before we can load from it. To prevent this situation, we need
5952 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5953 // the same chain operand as O, we create a token factor from the chain results
5954 // of O and L, and we replace all uses of O's chain result with that token
5955 // factor (see spliceIntoChain below for this last part).
5956 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5957                                             ReuseLoadInfo &RLI,
5958                                             SelectionDAG &DAG,
5959                                             ISD::LoadExtType ET) const {
5960   SDLoc dl(Op);
5961   if (ET == ISD::NON_EXTLOAD &&
5962       (Op.getOpcode() == ISD::FP_TO_UINT ||
5963        Op.getOpcode() == ISD::FP_TO_SINT) &&
5964       isOperationLegalOrCustom(Op.getOpcode(),
5965                                Op.getOperand(0).getValueType())) {
5966
5967     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5968     return true;
5969   }
5970
5971   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5972   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5973       LD->isNonTemporal())
5974     return false;
5975   if (LD->getMemoryVT() != MemVT)
5976     return false;
5977
5978   RLI.Ptr = LD->getBasePtr();
5979   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5980     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5981            "Non-pre-inc AM on PPC?");
5982     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5983                           LD->getOffset());
5984   }
5985
5986   RLI.Chain = LD->getChain();
5987   RLI.MPI = LD->getPointerInfo();
5988   RLI.IsInvariant = LD->isInvariant();
5989   RLI.Alignment = LD->getAlignment();
5990   RLI.AAInfo = LD->getAAInfo();
5991   RLI.Ranges = LD->getRanges();
5992
5993   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5994   return true;
5995 }
5996
5997 // Given the head of the old chain, ResChain, insert a token factor containing
5998 // it and NewResChain, and make users of ResChain now be users of that token
5999 // factor.
6000 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6001                                         SDValue NewResChain,
6002                                         SelectionDAG &DAG) const {
6003   if (!ResChain)
6004     return;
6005
6006   SDLoc dl(NewResChain);
6007
6008   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6009                            NewResChain, DAG.getUNDEF(MVT::Other));
6010   assert(TF.getNode() != NewResChain.getNode() &&
6011          "A new TF really is required here");
6012
6013   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6014   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6015 }
6016
6017 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6018                                           SelectionDAG &DAG) const {
6019   SDLoc dl(Op);
6020
6021   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6022     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6023       return SDValue();
6024
6025     SDValue Value = Op.getOperand(0);
6026     // The values are now known to be -1 (false) or 1 (true). To convert this
6027     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6028     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6029     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6030   
6031     SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6032     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6033                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6034   
6035     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6036
6037     if (Op.getValueType() != MVT::v4f64)
6038       Value = DAG.getNode(ISD::FP_ROUND, dl,
6039                           Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6040     return Value;
6041   }
6042
6043   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6044   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6045     return SDValue();
6046
6047   if (Op.getOperand(0).getValueType() == MVT::i1)
6048     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6049                        DAG.getConstantFP(1.0, Op.getValueType()),
6050                        DAG.getConstantFP(0.0, Op.getValueType()));
6051
6052   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6053          "UINT_TO_FP is supported only with FPCVT");
6054
6055   // If we have FCFIDS, then use it when converting to single-precision.
6056   // Otherwise, convert to double-precision and then round.
6057   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6058                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6059                                                             : PPCISD::FCFIDS)
6060                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6061                                                             : PPCISD::FCFID);
6062   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6063                   ? MVT::f32
6064                   : MVT::f64;
6065
6066   if (Op.getOperand(0).getValueType() == MVT::i64) {
6067     SDValue SINT = Op.getOperand(0);
6068     // When converting to single-precision, we actually need to convert
6069     // to double-precision first and then round to single-precision.
6070     // To avoid double-rounding effects during that operation, we have
6071     // to prepare the input operand.  Bits that might be truncated when
6072     // converting to double-precision are replaced by a bit that won't
6073     // be lost at this stage, but is below the single-precision rounding
6074     // position.
6075     //
6076     // However, if -enable-unsafe-fp-math is in effect, accept double
6077     // rounding to avoid the extra overhead.
6078     if (Op.getValueType() == MVT::f32 &&
6079         !Subtarget.hasFPCVT() &&
6080         !DAG.getTarget().Options.UnsafeFPMath) {
6081
6082       // Twiddle input to make sure the low 11 bits are zero.  (If this
6083       // is the case, we are guaranteed the value will fit into the 53 bit
6084       // mantissa of an IEEE double-precision value without rounding.)
6085       // If any of those low 11 bits were not zero originally, make sure
6086       // bit 12 (value 2048) is set instead, so that the final rounding
6087       // to single-precision gets the correct result.
6088       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6089                                   SINT, DAG.getConstant(2047, MVT::i64));
6090       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6091                           Round, DAG.getConstant(2047, MVT::i64));
6092       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6093       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6094                           Round, DAG.getConstant(-2048, MVT::i64));
6095
6096       // However, we cannot use that value unconditionally: if the magnitude
6097       // of the input value is small, the bit-twiddling we did above might
6098       // end up visibly changing the output.  Fortunately, in that case, we
6099       // don't need to twiddle bits since the original input will convert
6100       // exactly to double-precision floating-point already.  Therefore,
6101       // construct a conditional to use the original value if the top 11
6102       // bits are all sign-bit copies, and use the rounded value computed
6103       // above otherwise.
6104       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6105                                  SINT, DAG.getConstant(53, MVT::i32));
6106       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6107                          Cond, DAG.getConstant(1, MVT::i64));
6108       Cond = DAG.getSetCC(dl, MVT::i32,
6109                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6110
6111       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6112     }
6113
6114     ReuseLoadInfo RLI;
6115     SDValue Bits;
6116
6117     MachineFunction &MF = DAG.getMachineFunction();
6118     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6119       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6120                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6121                          RLI.Ranges);
6122       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6123     } else if (Subtarget.hasLFIWAX() &&
6124                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6125       MachineMemOperand *MMO =
6126         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6127                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6128       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6129       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6130                                      DAG.getVTList(MVT::f64, MVT::Other),
6131                                      Ops, MVT::i32, MMO);
6132       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6133     } else if (Subtarget.hasFPCVT() &&
6134                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6135       MachineMemOperand *MMO =
6136         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6137                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6138       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6139       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6140                                      DAG.getVTList(MVT::f64, MVT::Other),
6141                                      Ops, MVT::i32, MMO);
6142       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6143     } else if (((Subtarget.hasLFIWAX() &&
6144                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6145                 (Subtarget.hasFPCVT() &&
6146                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6147                SINT.getOperand(0).getValueType() == MVT::i32) {
6148       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6149       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6150
6151       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6152       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6153
6154       SDValue Store =
6155         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6156                      MachinePointerInfo::getFixedStack(FrameIdx),
6157                      false, false, 0);
6158
6159       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6160              "Expected an i32 store");
6161
6162       RLI.Ptr = FIdx;
6163       RLI.Chain = Store;
6164       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6165       RLI.Alignment = 4;
6166
6167       MachineMemOperand *MMO =
6168         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6169                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6170       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6171       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6172                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6173                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6174                                      Ops, MVT::i32, MMO);
6175     } else
6176       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6177
6178     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6179
6180     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6181       FP = DAG.getNode(ISD::FP_ROUND, dl,
6182                        MVT::f32, FP, DAG.getIntPtrConstant(0));
6183     return FP;
6184   }
6185
6186   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6187          "Unhandled INT_TO_FP type in custom expander!");
6188   // Since we only generate this in 64-bit mode, we can take advantage of
6189   // 64-bit registers.  In particular, sign extend the input value into the
6190   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6191   // then lfd it and fcfid it.
6192   MachineFunction &MF = DAG.getMachineFunction();
6193   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6194   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6195
6196   SDValue Ld;
6197   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6198     ReuseLoadInfo RLI;
6199     bool ReusingLoad;
6200     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6201                                             DAG))) {
6202       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6203       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6204
6205       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6206                                    MachinePointerInfo::getFixedStack(FrameIdx),
6207                                    false, false, 0);
6208
6209       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6210              "Expected an i32 store");
6211
6212       RLI.Ptr = FIdx;
6213       RLI.Chain = Store;
6214       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6215       RLI.Alignment = 4;
6216     }
6217
6218     MachineMemOperand *MMO =
6219       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6220                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6221     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6222     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6223                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6224                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6225                                  Ops, MVT::i32, MMO);
6226     if (ReusingLoad)
6227       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6228   } else {
6229     assert(Subtarget.isPPC64() &&
6230            "i32->FP without LFIWAX supported only on PPC64");
6231
6232     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6233     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6234
6235     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6236                                 Op.getOperand(0));
6237
6238     // STD the extended value into the stack slot.
6239     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6240                                  MachinePointerInfo::getFixedStack(FrameIdx),
6241                                  false, false, 0);
6242
6243     // Load the value as a double.
6244     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6245                      MachinePointerInfo::getFixedStack(FrameIdx),
6246                      false, false, false, 0);
6247   }
6248
6249   // FCFID it and return it.
6250   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6251   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6252     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6253   return FP;
6254 }
6255
6256 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6257                                             SelectionDAG &DAG) const {
6258   SDLoc dl(Op);
6259   /*
6260    The rounding mode is in bits 30:31 of FPSR, and has the following
6261    settings:
6262      00 Round to nearest
6263      01 Round to 0
6264      10 Round to +inf
6265      11 Round to -inf
6266
6267   FLT_ROUNDS, on the other hand, expects the following:
6268     -1 Undefined
6269      0 Round to 0
6270      1 Round to nearest
6271      2 Round to +inf
6272      3 Round to -inf
6273
6274   To perform the conversion, we do:
6275     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6276   */
6277
6278   MachineFunction &MF = DAG.getMachineFunction();
6279   EVT VT = Op.getValueType();
6280   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6281
6282   // Save FP Control Word to register
6283   EVT NodeTys[] = {
6284     MVT::f64,    // return register
6285     MVT::Glue    // unused in this context
6286   };
6287   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6288
6289   // Save FP register to stack slot
6290   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6291   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6292   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6293                                StackSlot, MachinePointerInfo(), false, false,0);
6294
6295   // Load FP Control Word from low 32 bits of stack slot.
6296   SDValue Four = DAG.getConstant(4, PtrVT);
6297   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6298   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6299                             false, false, false, 0);
6300
6301   // Transform as necessary
6302   SDValue CWD1 =
6303     DAG.getNode(ISD::AND, dl, MVT::i32,
6304                 CWD, DAG.getConstant(3, MVT::i32));
6305   SDValue CWD2 =
6306     DAG.getNode(ISD::SRL, dl, MVT::i32,
6307                 DAG.getNode(ISD::AND, dl, MVT::i32,
6308                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6309                                         CWD, DAG.getConstant(3, MVT::i32)),
6310                             DAG.getConstant(3, MVT::i32)),
6311                 DAG.getConstant(1, MVT::i32));
6312
6313   SDValue RetVal =
6314     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6315
6316   return DAG.getNode((VT.getSizeInBits() < 16 ?
6317                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6318 }
6319
6320 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6321   EVT VT = Op.getValueType();
6322   unsigned BitWidth = VT.getSizeInBits();
6323   SDLoc dl(Op);
6324   assert(Op.getNumOperands() == 3 &&
6325          VT == Op.getOperand(1).getValueType() &&
6326          "Unexpected SHL!");
6327
6328   // Expand into a bunch of logical ops.  Note that these ops
6329   // depend on the PPC behavior for oversized shift amounts.
6330   SDValue Lo = Op.getOperand(0);
6331   SDValue Hi = Op.getOperand(1);
6332   SDValue Amt = Op.getOperand(2);
6333   EVT AmtVT = Amt.getValueType();
6334
6335   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6336                              DAG.getConstant(BitWidth, AmtVT), Amt);
6337   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6338   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6339   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6340   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6341                              DAG.getConstant(-BitWidth, AmtVT));
6342   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6343   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6344   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6345   SDValue OutOps[] = { OutLo, OutHi };
6346   return DAG.getMergeValues(OutOps, dl);
6347 }
6348
6349 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6350   EVT VT = Op.getValueType();
6351   SDLoc dl(Op);
6352   unsigned BitWidth = VT.getSizeInBits();
6353   assert(Op.getNumOperands() == 3 &&
6354          VT == Op.getOperand(1).getValueType() &&
6355          "Unexpected SRL!");
6356
6357   // Expand into a bunch of logical ops.  Note that these ops
6358   // depend on the PPC behavior for oversized shift amounts.
6359   SDValue Lo = Op.getOperand(0);
6360   SDValue Hi = Op.getOperand(1);
6361   SDValue Amt = Op.getOperand(2);
6362   EVT AmtVT = Amt.getValueType();
6363
6364   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6365                              DAG.getConstant(BitWidth, AmtVT), Amt);
6366   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6367   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6368   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6369   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6370                              DAG.getConstant(-BitWidth, AmtVT));
6371   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6372   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6373   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6374   SDValue OutOps[] = { OutLo, OutHi };
6375   return DAG.getMergeValues(OutOps, dl);
6376 }
6377
6378 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6379   SDLoc dl(Op);
6380   EVT VT = Op.getValueType();
6381   unsigned BitWidth = VT.getSizeInBits();
6382   assert(Op.getNumOperands() == 3 &&
6383          VT == Op.getOperand(1).getValueType() &&
6384          "Unexpected SRA!");
6385
6386   // Expand into a bunch of logical ops, followed by a select_cc.
6387   SDValue Lo = Op.getOperand(0);
6388   SDValue Hi = Op.getOperand(1);
6389   SDValue Amt = Op.getOperand(2);
6390   EVT AmtVT = Amt.getValueType();
6391
6392   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6393                              DAG.getConstant(BitWidth, AmtVT), Amt);
6394   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6395   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6396   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6397   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6398                              DAG.getConstant(-BitWidth, AmtVT));
6399   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6400   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6401   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6402                                   Tmp4, Tmp6, ISD::SETLE);
6403   SDValue OutOps[] = { OutLo, OutHi };
6404   return DAG.getMergeValues(OutOps, dl);
6405 }
6406
6407 //===----------------------------------------------------------------------===//
6408 // Vector related lowering.
6409 //
6410
6411 /// BuildSplatI - Build a canonical splati of Val with an element size of
6412 /// SplatSize.  Cast the result to VT.
6413 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6414                              SelectionDAG &DAG, SDLoc dl) {
6415   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6416
6417   static const MVT VTys[] = { // canonical VT to use for each size.
6418     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6419   };
6420
6421   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6422
6423   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6424   if (Val == -1)
6425     SplatSize = 1;
6426
6427   EVT CanonicalVT = VTys[SplatSize-1];
6428
6429   // Build a canonical splat for this value.
6430   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6431   SmallVector<SDValue, 8> Ops;
6432   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6433   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6434   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6435 }
6436
6437 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6438 /// specified intrinsic ID.
6439 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6440                                 SelectionDAG &DAG, SDLoc dl,
6441                                 EVT DestVT = MVT::Other) {
6442   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6443   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6444                      DAG.getConstant(IID, MVT::i32), Op);
6445 }
6446
6447 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6448 /// specified intrinsic ID.
6449 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6450                                 SelectionDAG &DAG, SDLoc dl,
6451                                 EVT DestVT = MVT::Other) {
6452   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6453   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6454                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6455 }
6456
6457 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6458 /// specified intrinsic ID.
6459 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6460                                 SDValue Op2, SelectionDAG &DAG,
6461                                 SDLoc dl, EVT DestVT = MVT::Other) {
6462   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6463   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6464                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6465 }
6466
6467
6468 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6469 /// amount.  The result has the specified value type.
6470 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6471                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6472   // Force LHS/RHS to be the right type.
6473   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6474   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6475
6476   int Ops[16];
6477   for (unsigned i = 0; i != 16; ++i)
6478     Ops[i] = i + Amt;
6479   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6480   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6481 }
6482
6483 // If this is a case we can't handle, return null and let the default
6484 // expansion code take care of it.  If we CAN select this case, and if it
6485 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6486 // this case more efficiently than a constant pool load, lower it to the
6487 // sequence of ops that should be used.
6488 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6489                                              SelectionDAG &DAG) const {
6490   SDLoc dl(Op);
6491   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6492   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6493
6494   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6495     // We first build an i32 vector, load it into a QPX register,
6496     // then convert it to a floating-point vector and compare it
6497     // to a zero vector to get the boolean result.
6498     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6499     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6500     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6501     EVT PtrVT = getPointerTy();
6502     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6503
6504     assert(BVN->getNumOperands() == 4 &&
6505       "BUILD_VECTOR for v4i1 does not have 4 operands");
6506
6507     bool IsConst = true;
6508     for (unsigned i = 0; i < 4; ++i) {
6509       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6510       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6511         IsConst = false;
6512         break;
6513       }
6514     }
6515
6516     if (IsConst) {
6517       Constant *One =
6518         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6519       Constant *NegOne =
6520         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6521
6522       SmallVector<Constant*, 4> CV(4, NegOne);
6523       for (unsigned i = 0; i < 4; ++i) {
6524         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6525           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6526         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6527                    getConstantIntValue()->isZero())
6528           continue;
6529         else
6530           CV[i] = One;
6531       }
6532
6533       Constant *CP = ConstantVector::get(CV);
6534       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6535                       16 /* alignment */);
6536  
6537       SmallVector<SDValue, 2> Ops;
6538       Ops.push_back(DAG.getEntryNode());
6539       Ops.push_back(CPIdx);
6540
6541       SmallVector<EVT, 2> ValueVTs;
6542       ValueVTs.push_back(MVT::v4i1);
6543       ValueVTs.push_back(MVT::Other); // chain
6544       SDVTList VTs = DAG.getVTList(ValueVTs);
6545
6546       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6547         dl, VTs, Ops, MVT::v4f32,
6548         MachinePointerInfo::getConstantPool());
6549     }
6550
6551     SmallVector<SDValue, 4> Stores;
6552     for (unsigned i = 0; i < 4; ++i) {
6553       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6554
6555       unsigned Offset = 4*i;
6556       SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6557       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6558
6559       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6560       if (StoreSize > 4) {
6561         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6562                                            BVN->getOperand(i), Idx,
6563                                            PtrInfo.getWithOffset(Offset),
6564                                            MVT::i32, false, false, 0));
6565       } else {
6566         SDValue StoreValue = BVN->getOperand(i);
6567         if (StoreSize < 4)
6568           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6569
6570         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6571                                       StoreValue, Idx,
6572                                       PtrInfo.getWithOffset(Offset),
6573                                       false, false, 0));
6574       }
6575     }
6576
6577     SDValue StoreChain;
6578     if (!Stores.empty())
6579       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6580     else
6581       StoreChain = DAG.getEntryNode();
6582
6583     // Now load from v4i32 into the QPX register; this will extend it to
6584     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6585     // is typed as v4f64 because the QPX register integer states are not
6586     // explicitly represented.
6587
6588     SmallVector<SDValue, 2> Ops;
6589     Ops.push_back(StoreChain);
6590     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6591     Ops.push_back(FIdx);
6592
6593     SmallVector<EVT, 2> ValueVTs;
6594     ValueVTs.push_back(MVT::v4f64);
6595     ValueVTs.push_back(MVT::Other); // chain
6596     SDVTList VTs = DAG.getVTList(ValueVTs);
6597
6598     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6599       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6600     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6601       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6602       LoadedVect);
6603
6604     SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6605     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6606                           FPZeros, FPZeros, FPZeros, FPZeros);
6607
6608     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6609   }
6610
6611   // All other QPX vectors are handled by generic code.
6612   if (Subtarget.hasQPX())
6613     return SDValue();
6614
6615   // Check if this is a splat of a constant value.
6616   APInt APSplatBits, APSplatUndef;
6617   unsigned SplatBitSize;
6618   bool HasAnyUndefs;
6619   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6620                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6621     return SDValue();
6622
6623   unsigned SplatBits = APSplatBits.getZExtValue();
6624   unsigned SplatUndef = APSplatUndef.getZExtValue();
6625   unsigned SplatSize = SplatBitSize / 8;
6626
6627   // First, handle single instruction cases.
6628
6629   // All zeros?
6630   if (SplatBits == 0) {
6631     // Canonicalize all zero vectors to be v4i32.
6632     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6633       SDValue Z = DAG.getConstant(0, MVT::i32);
6634       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6635       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6636     }
6637     return Op;
6638   }
6639
6640   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6641   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6642                     (32-SplatBitSize));
6643   if (SextVal >= -16 && SextVal <= 15)
6644     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6645
6646
6647   // Two instruction sequences.
6648
6649   // If this value is in the range [-32,30] and is even, use:
6650   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6651   // If this value is in the range [17,31] and is odd, use:
6652   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6653   // If this value is in the range [-31,-17] and is odd, use:
6654   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6655   // Note the last two are three-instruction sequences.
6656   if (SextVal >= -32 && SextVal <= 31) {
6657     // To avoid having these optimizations undone by constant folding,
6658     // we convert to a pseudo that will be expanded later into one of
6659     // the above forms.
6660     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6661     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6662               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6663     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6664     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6665     if (VT == Op.getValueType())
6666       return RetVal;
6667     else
6668       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6669   }
6670
6671   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6672   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6673   // for fneg/fabs.
6674   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6675     // Make -1 and vspltisw -1:
6676     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6677
6678     // Make the VSLW intrinsic, computing 0x8000_0000.
6679     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6680                                    OnesV, DAG, dl);
6681
6682     // xor by OnesV to invert it.
6683     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6684     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6685   }
6686
6687   // The remaining cases assume either big endian element order or
6688   // a splat-size that equates to the element size of the vector
6689   // to be built.  An example that doesn't work for little endian is
6690   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6691   // and a vector element size of 16 bits.  The code below will
6692   // produce the vector in big endian element order, which for little
6693   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6694
6695   // For now, just avoid these optimizations in that case.
6696   // FIXME: Develop correct optimizations for LE with mismatched
6697   // splat and element sizes.
6698
6699   if (Subtarget.isLittleEndian() &&
6700       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6701     return SDValue();
6702
6703   // Check to see if this is a wide variety of vsplti*, binop self cases.
6704   static const signed char SplatCsts[] = {
6705     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6706     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6707   };
6708
6709   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6710     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6711     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6712     int i = SplatCsts[idx];
6713
6714     // Figure out what shift amount will be used by altivec if shifted by i in
6715     // this splat size.
6716     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6717
6718     // vsplti + shl self.
6719     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6720       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6721       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6722         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6723         Intrinsic::ppc_altivec_vslw
6724       };
6725       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6726       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6727     }
6728
6729     // vsplti + srl self.
6730     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6731       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6732       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6733         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6734         Intrinsic::ppc_altivec_vsrw
6735       };
6736       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6737       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6738     }
6739
6740     // vsplti + sra self.
6741     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6742       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6743       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6744         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6745         Intrinsic::ppc_altivec_vsraw
6746       };
6747       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6748       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6749     }
6750
6751     // vsplti + rol self.
6752     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6753                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6754       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6755       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6756         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6757         Intrinsic::ppc_altivec_vrlw
6758       };
6759       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6760       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6761     }
6762
6763     // t = vsplti c, result = vsldoi t, t, 1
6764     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6765       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6766       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6767     }
6768     // t = vsplti c, result = vsldoi t, t, 2
6769     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6770       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6771       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6772     }
6773     // t = vsplti c, result = vsldoi t, t, 3
6774     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6775       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6776       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6777     }
6778   }
6779
6780   return SDValue();
6781 }
6782
6783 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6784 /// the specified operations to build the shuffle.
6785 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6786                                       SDValue RHS, SelectionDAG &DAG,
6787                                       SDLoc dl) {
6788   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6789   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6790   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6791
6792   enum {
6793     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6794     OP_VMRGHW,
6795     OP_VMRGLW,
6796     OP_VSPLTISW0,
6797     OP_VSPLTISW1,
6798     OP_VSPLTISW2,
6799     OP_VSPLTISW3,
6800     OP_VSLDOI4,
6801     OP_VSLDOI8,
6802     OP_VSLDOI12
6803   };
6804
6805   if (OpNum == OP_COPY) {
6806     if (LHSID == (1*9+2)*9+3) return LHS;
6807     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6808     return RHS;
6809   }
6810
6811   SDValue OpLHS, OpRHS;
6812   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6813   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6814
6815   int ShufIdxs[16];
6816   switch (OpNum) {
6817   default: llvm_unreachable("Unknown i32 permute!");
6818   case OP_VMRGHW:
6819     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6820     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6821     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6822     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6823     break;
6824   case OP_VMRGLW:
6825     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6826     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6827     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6828     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6829     break;
6830   case OP_VSPLTISW0:
6831     for (unsigned i = 0; i != 16; ++i)
6832       ShufIdxs[i] = (i&3)+0;
6833     break;
6834   case OP_VSPLTISW1:
6835     for (unsigned i = 0; i != 16; ++i)
6836       ShufIdxs[i] = (i&3)+4;
6837     break;
6838   case OP_VSPLTISW2:
6839     for (unsigned i = 0; i != 16; ++i)
6840       ShufIdxs[i] = (i&3)+8;
6841     break;
6842   case OP_VSPLTISW3:
6843     for (unsigned i = 0; i != 16; ++i)
6844       ShufIdxs[i] = (i&3)+12;
6845     break;
6846   case OP_VSLDOI4:
6847     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6848   case OP_VSLDOI8:
6849     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6850   case OP_VSLDOI12:
6851     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6852   }
6853   EVT VT = OpLHS.getValueType();
6854   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6855   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6856   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6857   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6858 }
6859
6860 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6861 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6862 /// return the code it can be lowered into.  Worst case, it can always be
6863 /// lowered into a vperm.
6864 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6865                                                SelectionDAG &DAG) const {
6866   SDLoc dl(Op);
6867   SDValue V1 = Op.getOperand(0);
6868   SDValue V2 = Op.getOperand(1);
6869   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6870   EVT VT = Op.getValueType();
6871   bool isLittleEndian = Subtarget.isLittleEndian();
6872
6873   if (Subtarget.hasQPX()) {
6874     if (VT.getVectorNumElements() != 4)
6875       return SDValue();
6876
6877     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6878
6879     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6880     if (AlignIdx != -1) {
6881       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6882                          DAG.getConstant(AlignIdx, MVT::i32));
6883     } else if (SVOp->isSplat()) {
6884       int SplatIdx = SVOp->getSplatIndex();
6885       if (SplatIdx >= 4) {
6886         std::swap(V1, V2);
6887         SplatIdx -= 4;
6888       }
6889
6890       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6891       // nothing to do.
6892
6893       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6894                          DAG.getConstant(SplatIdx, MVT::i32));
6895     }
6896
6897     // Lower this into a qvgpci/qvfperm pair.
6898
6899     // Compute the qvgpci literal
6900     unsigned idx = 0;
6901     for (unsigned i = 0; i < 4; ++i) {
6902       int m = SVOp->getMaskElt(i);
6903       unsigned mm = m >= 0 ? (unsigned) m : i;
6904       idx |= mm << (3-i)*3;
6905     }
6906
6907     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6908                              DAG.getConstant(idx, MVT::i32));
6909     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6910   }
6911
6912   // Cases that are handled by instructions that take permute immediates
6913   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6914   // selected by the instruction selector.
6915   if (V2.getOpcode() == ISD::UNDEF) {
6916     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6917         PPC::isSplatShuffleMask(SVOp, 2) ||
6918         PPC::isSplatShuffleMask(SVOp, 4) ||
6919         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6920         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6921         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6922         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6923         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6924         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6925         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6926         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6927         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6928       return Op;
6929     }
6930   }
6931
6932   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6933   // and produce a fixed permutation.  If any of these match, do not lower to
6934   // VPERM.
6935   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6936   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6937       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6938       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6939       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6940       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6941       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6942       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6943       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6944       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6945     return Op;
6946
6947   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6948   // perfect shuffle table to emit an optimal matching sequence.
6949   ArrayRef<int> PermMask = SVOp->getMask();
6950
6951   unsigned PFIndexes[4];
6952   bool isFourElementShuffle = true;
6953   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6954     unsigned EltNo = 8;   // Start out undef.
6955     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6956       if (PermMask[i*4+j] < 0)
6957         continue;   // Undef, ignore it.
6958
6959       unsigned ByteSource = PermMask[i*4+j];
6960       if ((ByteSource & 3) != j) {
6961         isFourElementShuffle = false;
6962         break;
6963       }
6964
6965       if (EltNo == 8) {
6966         EltNo = ByteSource/4;
6967       } else if (EltNo != ByteSource/4) {
6968         isFourElementShuffle = false;
6969         break;
6970       }
6971     }
6972     PFIndexes[i] = EltNo;
6973   }
6974
6975   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6976   // perfect shuffle vector to determine if it is cost effective to do this as
6977   // discrete instructions, or whether we should use a vperm.
6978   // For now, we skip this for little endian until such time as we have a
6979   // little-endian perfect shuffle table.
6980   if (isFourElementShuffle && !isLittleEndian) {
6981     // Compute the index in the perfect shuffle table.
6982     unsigned PFTableIndex =
6983       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6984
6985     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6986     unsigned Cost  = (PFEntry >> 30);
6987
6988     // Determining when to avoid vperm is tricky.  Many things affect the cost
6989     // of vperm, particularly how many times the perm mask needs to be computed.
6990     // For example, if the perm mask can be hoisted out of a loop or is already
6991     // used (perhaps because there are multiple permutes with the same shuffle
6992     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6993     // the loop requires an extra register.
6994     //
6995     // As a compromise, we only emit discrete instructions if the shuffle can be
6996     // generated in 3 or fewer operations.  When we have loop information
6997     // available, if this block is within a loop, we should avoid using vperm
6998     // for 3-operation perms and use a constant pool load instead.
6999     if (Cost < 3)
7000       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7001   }
7002
7003   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7004   // vector that will get spilled to the constant pool.
7005   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7006
7007   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7008   // that it is in input element units, not in bytes.  Convert now.
7009
7010   // For little endian, the order of the input vectors is reversed, and
7011   // the permutation mask is complemented with respect to 31.  This is
7012   // necessary to produce proper semantics with the big-endian-biased vperm
7013   // instruction.
7014   EVT EltVT = V1.getValueType().getVectorElementType();
7015   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7016
7017   SmallVector<SDValue, 16> ResultMask;
7018   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7019     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7020
7021     for (unsigned j = 0; j != BytesPerElement; ++j)
7022       if (isLittleEndian)
7023         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7024                                              MVT::i32));
7025       else
7026         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7027                                              MVT::i32));
7028   }
7029
7030   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7031                                   ResultMask);
7032   if (isLittleEndian)
7033     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7034                        V2, V1, VPermMask);
7035   else
7036     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7037                        V1, V2, VPermMask);
7038 }
7039
7040 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7041 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7042 /// information about the intrinsic.
7043 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7044                                   bool &isDot, const PPCSubtarget &Subtarget) {
7045   unsigned IntrinsicID =
7046     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7047   CompareOpc = -1;
7048   isDot = false;
7049   switch (IntrinsicID) {
7050   default: return false;
7051     // Comparison predicates.
7052   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7053   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7054   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7055   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7056   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7057   case Intrinsic::ppc_altivec_vcmpequd_p: 
7058     if (Subtarget.hasP8Altivec()) {
7059       CompareOpc = 199; 
7060       isDot = 1; 
7061     }
7062     else 
7063       return false;
7064
7065     break;
7066   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7067   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7068   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7069   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7070   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7071   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7072     if (Subtarget.hasP8Altivec()) {
7073       CompareOpc = 967; 
7074       isDot = 1; 
7075     }
7076     else 
7077       return false;
7078
7079     break;
7080   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7081   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7082   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7083   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7084     if (Subtarget.hasP8Altivec()) {
7085       CompareOpc = 711; 
7086       isDot = 1; 
7087     }
7088     else 
7089       return false;
7090
7091     break;
7092       
7093     // Normal Comparisons.
7094   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7095   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7096   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7097   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7098   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7099   case Intrinsic::ppc_altivec_vcmpequd:
7100     if (Subtarget.hasP8Altivec()) {
7101       CompareOpc = 199; 
7102       isDot = 0; 
7103     }
7104     else
7105       return false;
7106
7107     break;
7108   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7109   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7110   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7111   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7112   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7113   case Intrinsic::ppc_altivec_vcmpgtsd:   
7114     if (Subtarget.hasP8Altivec()) {
7115       CompareOpc = 967; 
7116       isDot = 0; 
7117     }
7118     else
7119       return false;
7120
7121     break;
7122   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7123   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7124   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7125   case Intrinsic::ppc_altivec_vcmpgtud:   
7126     if (Subtarget.hasP8Altivec()) {
7127       CompareOpc = 711; 
7128       isDot = 0; 
7129     }
7130     else
7131       return false;
7132
7133     break;
7134   }
7135   return true;
7136 }
7137
7138 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7139 /// lower, do it, otherwise return null.
7140 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7141                                                    SelectionDAG &DAG) const {
7142   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7143   // opcode number of the comparison.
7144   SDLoc dl(Op);
7145   int CompareOpc;
7146   bool isDot;
7147   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7148     return SDValue();    // Don't custom lower most intrinsics.
7149
7150   // If this is a non-dot comparison, make the VCMP node and we are done.
7151   if (!isDot) {
7152     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7153                               Op.getOperand(1), Op.getOperand(2),
7154                               DAG.getConstant(CompareOpc, MVT::i32));
7155     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7156   }
7157
7158   // Create the PPCISD altivec 'dot' comparison node.
7159   SDValue Ops[] = {
7160     Op.getOperand(2),  // LHS
7161     Op.getOperand(3),  // RHS
7162     DAG.getConstant(CompareOpc, MVT::i32)
7163   };
7164   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7165   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7166
7167   // Now that we have the comparison, emit a copy from the CR to a GPR.
7168   // This is flagged to the above dot comparison.
7169   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7170                                 DAG.getRegister(PPC::CR6, MVT::i32),
7171                                 CompNode.getValue(1));
7172
7173   // Unpack the result based on how the target uses it.
7174   unsigned BitNo;   // Bit # of CR6.
7175   bool InvertBit;   // Invert result?
7176   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7177   default:  // Can't happen, don't crash on invalid number though.
7178   case 0:   // Return the value of the EQ bit of CR6.
7179     BitNo = 0; InvertBit = false;
7180     break;
7181   case 1:   // Return the inverted value of the EQ bit of CR6.
7182     BitNo = 0; InvertBit = true;
7183     break;
7184   case 2:   // Return the value of the LT bit of CR6.
7185     BitNo = 2; InvertBit = false;
7186     break;
7187   case 3:   // Return the inverted value of the LT bit of CR6.
7188     BitNo = 2; InvertBit = true;
7189     break;
7190   }
7191
7192   // Shift the bit into the low position.
7193   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7194                       DAG.getConstant(8-(3-BitNo), MVT::i32));
7195   // Isolate the bit.
7196   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7197                       DAG.getConstant(1, MVT::i32));
7198
7199   // If we are supposed to, toggle the bit.
7200   if (InvertBit)
7201     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7202                         DAG.getConstant(1, MVT::i32));
7203   return Flags;
7204 }
7205
7206 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7207                                                   SelectionDAG &DAG) const {
7208   SDLoc dl(Op);
7209   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7210   // instructions), but for smaller types, we need to first extend up to v2i32
7211   // before doing going farther.
7212   if (Op.getValueType() == MVT::v2i64) {
7213     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7214     if (ExtVT != MVT::v2i32) {
7215       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7216       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7217                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7218                                         ExtVT.getVectorElementType(), 4)));
7219       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7220       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7221                        DAG.getValueType(MVT::v2i32));
7222     }
7223
7224     return Op;
7225   }
7226
7227   return SDValue();
7228 }
7229
7230 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7231                                                    SelectionDAG &DAG) const {
7232   SDLoc dl(Op);
7233   // Create a stack slot that is 16-byte aligned.
7234   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7235   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7236   EVT PtrVT = getPointerTy();
7237   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7238
7239   // Store the input value into Value#0 of the stack slot.
7240   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7241                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7242                                false, false, 0);
7243   // Load it out.
7244   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7245                      false, false, false, 0);
7246 }
7247
7248 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7249                                                    SelectionDAG &DAG) const {
7250   SDLoc dl(Op);
7251   SDNode *N = Op.getNode();
7252
7253   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7254          "Unknown extract_vector_elt type");
7255
7256   SDValue Value = N->getOperand(0);
7257
7258   // The first part of this is like the store lowering except that we don't
7259   // need to track the chain.
7260
7261   // The values are now known to be -1 (false) or 1 (true). To convert this
7262   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7263   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7264   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7265
7266   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7267   // understand how to form the extending load.
7268   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7269   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7270                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7271
7272   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7273
7274   // Now convert to an integer and store.
7275   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7276     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7277     Value);
7278
7279   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7280   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7281   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7282   EVT PtrVT = getPointerTy();
7283   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7284
7285   SDValue StoreChain = DAG.getEntryNode();
7286   SmallVector<SDValue, 2> Ops;
7287   Ops.push_back(StoreChain);
7288   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7289   Ops.push_back(Value);
7290   Ops.push_back(FIdx);
7291
7292   SmallVector<EVT, 2> ValueVTs;
7293   ValueVTs.push_back(MVT::Other); // chain
7294   SDVTList VTs = DAG.getVTList(ValueVTs);
7295
7296   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7297     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7298
7299   // Extract the value requested.
7300   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7301   SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7302   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7303
7304   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7305                                PtrInfo.getWithOffset(Offset),
7306                                false, false, false, 0);
7307
7308   if (!Subtarget.useCRBits())
7309     return IntVal;
7310
7311   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7312 }
7313
7314 /// Lowering for QPX v4i1 loads
7315 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7316                                            SelectionDAG &DAG) const {
7317   SDLoc dl(Op);
7318   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7319   SDValue LoadChain = LN->getChain();
7320   SDValue BasePtr = LN->getBasePtr();
7321
7322   if (Op.getValueType() == MVT::v4f64 ||
7323       Op.getValueType() == MVT::v4f32) {
7324     EVT MemVT = LN->getMemoryVT();
7325     unsigned Alignment = LN->getAlignment();
7326
7327     // If this load is properly aligned, then it is legal.
7328     if (Alignment >= MemVT.getStoreSize())
7329       return Op;
7330
7331     EVT ScalarVT = Op.getValueType().getScalarType(),
7332         ScalarMemVT = MemVT.getScalarType();
7333     unsigned Stride = ScalarMemVT.getStoreSize();
7334
7335     SmallVector<SDValue, 8> Vals, LoadChains;
7336     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7337       SDValue Load;
7338       if (ScalarVT != ScalarMemVT)
7339         Load =
7340           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7341                          BasePtr,
7342                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7343                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7344                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7345                          LN->getAAInfo());
7346       else
7347         Load =
7348           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7349                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7350                        LN->isVolatile(), LN->isNonTemporal(),
7351                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7352                        LN->getAAInfo());
7353
7354       if (Idx == 0 && LN->isIndexed()) {
7355         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7356                "Unknown addressing mode on vector load");
7357         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7358                                   LN->getAddressingMode());
7359       }
7360
7361       Vals.push_back(Load);
7362       LoadChains.push_back(Load.getValue(1));
7363
7364       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7365                             DAG.getConstant(Stride, BasePtr.getValueType()));
7366     }
7367
7368     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7369     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7370                                    Op.getValueType(), Vals);
7371
7372     if (LN->isIndexed()) {
7373       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7374       return DAG.getMergeValues(RetOps, dl);
7375     }
7376
7377     SDValue RetOps[] = { Value, TF };
7378     return DAG.getMergeValues(RetOps, dl);
7379   }
7380
7381   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7382   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7383
7384   // To lower v4i1 from a byte array, we load the byte elements of the
7385   // vector and then reuse the BUILD_VECTOR logic.
7386
7387   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7388   for (unsigned i = 0; i < 4; ++i) {
7389     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7390     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7391
7392     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7393                         dl, MVT::i32, LoadChain, Idx,
7394                         LN->getPointerInfo().getWithOffset(i),
7395                         MVT::i8 /* memory type */,
7396                         LN->isVolatile(), LN->isNonTemporal(),
7397                         LN->isInvariant(),
7398                         1 /* alignment */, LN->getAAInfo()));
7399     VectElmtChains.push_back(VectElmts[i].getValue(1));
7400   }
7401
7402   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7403   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7404
7405   SDValue RVals[] = { Value, LoadChain };
7406   return DAG.getMergeValues(RVals, dl);
7407 }
7408
7409 /// Lowering for QPX v4i1 stores
7410 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7411                                             SelectionDAG &DAG) const {
7412   SDLoc dl(Op);
7413   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7414   SDValue StoreChain = SN->getChain();
7415   SDValue BasePtr = SN->getBasePtr();
7416   SDValue Value = SN->getValue();
7417
7418   if (Value.getValueType() == MVT::v4f64 ||
7419       Value.getValueType() == MVT::v4f32) {
7420     EVT MemVT = SN->getMemoryVT();
7421     unsigned Alignment = SN->getAlignment();
7422
7423     // If this store is properly aligned, then it is legal.
7424     if (Alignment >= MemVT.getStoreSize())
7425       return Op;
7426
7427     EVT ScalarVT = Value.getValueType().getScalarType(),
7428         ScalarMemVT = MemVT.getScalarType();
7429     unsigned Stride = ScalarMemVT.getStoreSize();
7430
7431     SmallVector<SDValue, 8> Stores;
7432     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7433       SDValue Ex =
7434         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7435                     DAG.getConstant(Idx, getVectorIdxTy()));
7436       SDValue Store;
7437       if (ScalarVT != ScalarMemVT)
7438         Store =
7439           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7440                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7441                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7442                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7443       else
7444         Store =
7445           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7446                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7447                        SN->isVolatile(), SN->isNonTemporal(),
7448                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7449
7450       if (Idx == 0 && SN->isIndexed()) {
7451         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7452                "Unknown addressing mode on vector store");
7453         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7454                                     SN->getAddressingMode());
7455       }
7456
7457       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7458                             DAG.getConstant(Stride, BasePtr.getValueType()));
7459       Stores.push_back(Store);
7460     }
7461
7462     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7463
7464     if (SN->isIndexed()) {
7465       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7466       return DAG.getMergeValues(RetOps, dl);
7467     }
7468
7469     return TF;
7470   }
7471
7472   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7473   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7474
7475   // The values are now known to be -1 (false) or 1 (true). To convert this
7476   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7477   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7478   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7479
7480   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7481   // understand how to form the extending load.
7482   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7483   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7484                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7485
7486   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7487
7488   // Now convert to an integer and store.
7489   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7490     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7491     Value);
7492
7493   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7494   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7495   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7496   EVT PtrVT = getPointerTy();
7497   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7498
7499   SmallVector<SDValue, 2> Ops;
7500   Ops.push_back(StoreChain);
7501   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7502   Ops.push_back(Value);
7503   Ops.push_back(FIdx);
7504
7505   SmallVector<EVT, 2> ValueVTs;
7506   ValueVTs.push_back(MVT::Other); // chain
7507   SDVTList VTs = DAG.getVTList(ValueVTs);
7508
7509   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7510     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7511
7512   // Move data into the byte array.
7513   SmallVector<SDValue, 4> Loads, LoadChains;
7514   for (unsigned i = 0; i < 4; ++i) {
7515     unsigned Offset = 4*i;
7516     SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7517     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7518
7519     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7520                                    PtrInfo.getWithOffset(Offset),
7521                                    false, false, false, 0));
7522     LoadChains.push_back(Loads[i].getValue(1));
7523   }
7524
7525   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7526
7527   SmallVector<SDValue, 4> Stores;
7528   for (unsigned i = 0; i < 4; ++i) {
7529     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7530     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7531
7532     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7533                                        SN->getPointerInfo().getWithOffset(i),
7534                                        MVT::i8 /* memory type */,
7535                                        SN->isNonTemporal(), SN->isVolatile(), 
7536                                        1 /* alignment */, SN->getAAInfo()));
7537   }
7538
7539   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7540
7541   return StoreChain;
7542 }
7543
7544 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7545   SDLoc dl(Op);
7546   if (Op.getValueType() == MVT::v4i32) {
7547     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7548
7549     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7550     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7551
7552     SDValue RHSSwap =   // = vrlw RHS, 16
7553       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7554
7555     // Shrinkify inputs to v8i16.
7556     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7557     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7558     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7559
7560     // Low parts multiplied together, generating 32-bit results (we ignore the
7561     // top parts).
7562     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7563                                         LHS, RHS, DAG, dl, MVT::v4i32);
7564
7565     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7566                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7567     // Shift the high parts up 16 bits.
7568     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7569                               Neg16, DAG, dl);
7570     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7571   } else if (Op.getValueType() == MVT::v8i16) {
7572     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7573
7574     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7575
7576     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7577                             LHS, RHS, Zero, DAG, dl);
7578   } else if (Op.getValueType() == MVT::v16i8) {
7579     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7580     bool isLittleEndian = Subtarget.isLittleEndian();
7581
7582     // Multiply the even 8-bit parts, producing 16-bit sums.
7583     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7584                                            LHS, RHS, DAG, dl, MVT::v8i16);
7585     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7586
7587     // Multiply the odd 8-bit parts, producing 16-bit sums.
7588     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7589                                           LHS, RHS, DAG, dl, MVT::v8i16);
7590     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7591
7592     // Merge the results together.  Because vmuleub and vmuloub are
7593     // instructions with a big-endian bias, we must reverse the
7594     // element numbering and reverse the meaning of "odd" and "even"
7595     // when generating little endian code.
7596     int Ops[16];
7597     for (unsigned i = 0; i != 8; ++i) {
7598       if (isLittleEndian) {
7599         Ops[i*2  ] = 2*i;
7600         Ops[i*2+1] = 2*i+16;
7601       } else {
7602         Ops[i*2  ] = 2*i+1;
7603         Ops[i*2+1] = 2*i+1+16;
7604       }
7605     }
7606     if (isLittleEndian)
7607       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7608     else
7609       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7610   } else {
7611     llvm_unreachable("Unknown mul to lower!");
7612   }
7613 }
7614
7615 /// LowerOperation - Provide custom lowering hooks for some operations.
7616 ///
7617 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7618   switch (Op.getOpcode()) {
7619   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7620   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7621   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7622   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7623   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7624   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7625   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7626   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7627   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7628   case ISD::VASTART:
7629     return LowerVASTART(Op, DAG, Subtarget);
7630
7631   case ISD::VAARG:
7632     return LowerVAARG(Op, DAG, Subtarget);
7633
7634   case ISD::VACOPY:
7635     return LowerVACOPY(Op, DAG, Subtarget);
7636
7637   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7638   case ISD::DYNAMIC_STACKALLOC:
7639     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7640
7641   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7642   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7643
7644   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7645   case ISD::STORE:              return LowerSTORE(Op, DAG);
7646   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7647   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7648   case ISD::FP_TO_UINT:
7649   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7650                                                       SDLoc(Op));
7651   case ISD::UINT_TO_FP:
7652   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7653   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7654
7655   // Lower 64-bit shifts.
7656   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7657   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7658   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7659
7660   // Vector-related lowering.
7661   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7662   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7663   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7664   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7665   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7666   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7667   case ISD::MUL:                return LowerMUL(Op, DAG);
7668
7669   // For counter-based loop handling.
7670   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7671
7672   // Frame & Return address.
7673   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7674   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7675   }
7676 }
7677
7678 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7679                                            SmallVectorImpl<SDValue>&Results,
7680                                            SelectionDAG &DAG) const {
7681   SDLoc dl(N);
7682   switch (N->getOpcode()) {
7683   default:
7684     llvm_unreachable("Do not know how to custom type legalize this operation!");
7685   case ISD::READCYCLECOUNTER: {
7686     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7687     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7688
7689     Results.push_back(RTB);
7690     Results.push_back(RTB.getValue(1));
7691     Results.push_back(RTB.getValue(2));
7692     break;
7693   }
7694   case ISD::INTRINSIC_W_CHAIN: {
7695     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7696         Intrinsic::ppc_is_decremented_ctr_nonzero)
7697       break;
7698
7699     assert(N->getValueType(0) == MVT::i1 &&
7700            "Unexpected result type for CTR decrement intrinsic");
7701     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7702     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7703     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7704                                  N->getOperand(1)); 
7705
7706     Results.push_back(NewInt);
7707     Results.push_back(NewInt.getValue(1));
7708     break;
7709   }
7710   case ISD::VAARG: {
7711     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7712       return;
7713
7714     EVT VT = N->getValueType(0);
7715
7716     if (VT == MVT::i64) {
7717       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7718
7719       Results.push_back(NewNode);
7720       Results.push_back(NewNode.getValue(1));
7721     }
7722     return;
7723   }
7724   case ISD::FP_ROUND_INREG: {
7725     assert(N->getValueType(0) == MVT::ppcf128);
7726     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7727     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7728                              MVT::f64, N->getOperand(0),
7729                              DAG.getIntPtrConstant(0));
7730     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7731                              MVT::f64, N->getOperand(0),
7732                              DAG.getIntPtrConstant(1));
7733
7734     // Add the two halves of the long double in round-to-zero mode.
7735     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7736
7737     // We know the low half is about to be thrown away, so just use something
7738     // convenient.
7739     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7740                                 FPreg, FPreg));
7741     return;
7742   }
7743   case ISD::FP_TO_SINT:
7744     // LowerFP_TO_INT() can only handle f32 and f64.
7745     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7746       return;
7747     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7748     return;
7749   }
7750 }
7751
7752
7753 //===----------------------------------------------------------------------===//
7754 //  Other Lowering Code
7755 //===----------------------------------------------------------------------===//
7756
7757 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7758   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7759   Function *Func = Intrinsic::getDeclaration(M, Id);
7760   return Builder.CreateCall(Func);
7761 }
7762
7763 // The mappings for emitLeading/TrailingFence is taken from
7764 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7765 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7766                                          AtomicOrdering Ord, bool IsStore,
7767                                          bool IsLoad) const {
7768   if (Ord == SequentiallyConsistent)
7769     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7770   else if (isAtLeastRelease(Ord))
7771     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7772   else
7773     return nullptr;
7774 }
7775
7776 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7777                                           AtomicOrdering Ord, bool IsStore,
7778                                           bool IsLoad) const {
7779   if (IsLoad && isAtLeastAcquire(Ord))
7780     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7781   // FIXME: this is too conservative, a dependent branch + isync is enough.
7782   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7783   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7784   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7785   else
7786     return nullptr;
7787 }
7788
7789 MachineBasicBlock *
7790 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7791                                     bool is64bit, unsigned BinOpcode) const {
7792   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7793   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7794
7795   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7796   MachineFunction *F = BB->getParent();
7797   MachineFunction::iterator It = BB;
7798   ++It;
7799
7800   unsigned dest = MI->getOperand(0).getReg();
7801   unsigned ptrA = MI->getOperand(1).getReg();
7802   unsigned ptrB = MI->getOperand(2).getReg();
7803   unsigned incr = MI->getOperand(3).getReg();
7804   DebugLoc dl = MI->getDebugLoc();
7805
7806   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7807   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7808   F->insert(It, loopMBB);
7809   F->insert(It, exitMBB);
7810   exitMBB->splice(exitMBB->begin(), BB,
7811                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7812   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7813
7814   MachineRegisterInfo &RegInfo = F->getRegInfo();
7815   unsigned TmpReg = (!BinOpcode) ? incr :
7816     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
7817                                            : &PPC::GPRCRegClass);
7818
7819   //  thisMBB:
7820   //   ...
7821   //   fallthrough --> loopMBB
7822   BB->addSuccessor(loopMBB);
7823
7824   //  loopMBB:
7825   //   l[wd]arx dest, ptr
7826   //   add r0, dest, incr
7827   //   st[wd]cx. r0, ptr
7828   //   bne- loopMBB
7829   //   fallthrough --> exitMBB
7830   BB = loopMBB;
7831   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7832     .addReg(ptrA).addReg(ptrB);
7833   if (BinOpcode)
7834     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7835   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7836     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7837   BuildMI(BB, dl, TII->get(PPC::BCC))
7838     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7839   BB->addSuccessor(loopMBB);
7840   BB->addSuccessor(exitMBB);
7841
7842   //  exitMBB:
7843   //   ...
7844   BB = exitMBB;
7845   return BB;
7846 }
7847
7848 MachineBasicBlock *
7849 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7850                                             MachineBasicBlock *BB,
7851                                             bool is8bit,    // operation
7852                                             unsigned BinOpcode) const {
7853   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7854   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7855   // In 64 bit mode we have to use 64 bits for addresses, even though the
7856   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
7857   // registers without caring whether they're 32 or 64, but here we're
7858   // doing actual arithmetic on the addresses.
7859   bool is64bit = Subtarget.isPPC64();
7860   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7861
7862   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7863   MachineFunction *F = BB->getParent();
7864   MachineFunction::iterator It = BB;
7865   ++It;
7866
7867   unsigned dest = MI->getOperand(0).getReg();
7868   unsigned ptrA = MI->getOperand(1).getReg();
7869   unsigned ptrB = MI->getOperand(2).getReg();
7870   unsigned incr = MI->getOperand(3).getReg();
7871   DebugLoc dl = MI->getDebugLoc();
7872
7873   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7874   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7875   F->insert(It, loopMBB);
7876   F->insert(It, exitMBB);
7877   exitMBB->splice(exitMBB->begin(), BB,
7878                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7879   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7880
7881   MachineRegisterInfo &RegInfo = F->getRegInfo();
7882   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7883                                           : &PPC::GPRCRegClass;
7884   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7885   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7886   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7887   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7888   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7889   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7890   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7891   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7892   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7893   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7894   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7895   unsigned Ptr1Reg;
7896   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7897
7898   //  thisMBB:
7899   //   ...
7900   //   fallthrough --> loopMBB
7901   BB->addSuccessor(loopMBB);
7902
7903   // The 4-byte load must be aligned, while a char or short may be
7904   // anywhere in the word.  Hence all this nasty bookkeeping code.
7905   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7906   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7907   //   xori shift, shift1, 24 [16]
7908   //   rlwinm ptr, ptr1, 0, 0, 29
7909   //   slw incr2, incr, shift
7910   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7911   //   slw mask, mask2, shift
7912   //  loopMBB:
7913   //   lwarx tmpDest, ptr
7914   //   add tmp, tmpDest, incr2
7915   //   andc tmp2, tmpDest, mask
7916   //   and tmp3, tmp, mask
7917   //   or tmp4, tmp3, tmp2
7918   //   stwcx. tmp4, ptr
7919   //   bne- loopMBB
7920   //   fallthrough --> exitMBB
7921   //   srw dest, tmpDest, shift
7922   if (ptrA != ZeroReg) {
7923     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7924     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7925       .addReg(ptrA).addReg(ptrB);
7926   } else {
7927     Ptr1Reg = ptrB;
7928   }
7929   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7930       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7931   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7932       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7933   if (is64bit)
7934     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7935       .addReg(Ptr1Reg).addImm(0).addImm(61);
7936   else
7937     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7938       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7939   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7940       .addReg(incr).addReg(ShiftReg);
7941   if (is8bit)
7942     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7943   else {
7944     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7945     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7946   }
7947   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7948       .addReg(Mask2Reg).addReg(ShiftReg);
7949
7950   BB = loopMBB;
7951   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7952     .addReg(ZeroReg).addReg(PtrReg);
7953   if (BinOpcode)
7954     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7955       .addReg(Incr2Reg).addReg(TmpDestReg);
7956   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7957     .addReg(TmpDestReg).addReg(MaskReg);
7958   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7959     .addReg(TmpReg).addReg(MaskReg);
7960   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7961     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7962   BuildMI(BB, dl, TII->get(PPC::STWCX))
7963     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7964   BuildMI(BB, dl, TII->get(PPC::BCC))
7965     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7966   BB->addSuccessor(loopMBB);
7967   BB->addSuccessor(exitMBB);
7968
7969   //  exitMBB:
7970   //   ...
7971   BB = exitMBB;
7972   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7973     .addReg(ShiftReg);
7974   return BB;
7975 }
7976
7977 llvm::MachineBasicBlock*
7978 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
7979                                     MachineBasicBlock *MBB) const {
7980   DebugLoc DL = MI->getDebugLoc();
7981   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7982
7983   MachineFunction *MF = MBB->getParent();
7984   MachineRegisterInfo &MRI = MF->getRegInfo();
7985
7986   const BasicBlock *BB = MBB->getBasicBlock();
7987   MachineFunction::iterator I = MBB;
7988   ++I;
7989
7990   // Memory Reference
7991   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7992   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7993
7994   unsigned DstReg = MI->getOperand(0).getReg();
7995   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7996   assert(RC->hasType(MVT::i32) && "Invalid destination!");
7997   unsigned mainDstReg = MRI.createVirtualRegister(RC);
7998   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7999
8000   MVT PVT = getPointerTy();
8001   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8002          "Invalid Pointer Size!");
8003   // For v = setjmp(buf), we generate
8004   //
8005   // thisMBB:
8006   //  SjLjSetup mainMBB
8007   //  bl mainMBB
8008   //  v_restore = 1
8009   //  b sinkMBB
8010   //
8011   // mainMBB:
8012   //  buf[LabelOffset] = LR
8013   //  v_main = 0
8014   //
8015   // sinkMBB:
8016   //  v = phi(main, restore)
8017   //
8018
8019   MachineBasicBlock *thisMBB = MBB;
8020   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8021   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8022   MF->insert(I, mainMBB);
8023   MF->insert(I, sinkMBB);
8024
8025   MachineInstrBuilder MIB;
8026
8027   // Transfer the remainder of BB and its successor edges to sinkMBB.
8028   sinkMBB->splice(sinkMBB->begin(), MBB,
8029                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8030   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8031
8032   // Note that the structure of the jmp_buf used here is not compatible
8033   // with that used by libc, and is not designed to be. Specifically, it
8034   // stores only those 'reserved' registers that LLVM does not otherwise
8035   // understand how to spill. Also, by convention, by the time this
8036   // intrinsic is called, Clang has already stored the frame address in the
8037   // first slot of the buffer and stack address in the third. Following the
8038   // X86 target code, we'll store the jump address in the second slot. We also
8039   // need to save the TOC pointer (R2) to handle jumps between shared
8040   // libraries, and that will be stored in the fourth slot. The thread
8041   // identifier (R13) is not affected.
8042
8043   // thisMBB:
8044   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8045   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8046   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8047
8048   // Prepare IP either in reg.
8049   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8050   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8051   unsigned BufReg = MI->getOperand(1).getReg();
8052
8053   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8054     setUsesTOCBasePtr(*MBB->getParent());
8055     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8056             .addReg(PPC::X2)
8057             .addImm(TOCOffset)
8058             .addReg(BufReg);
8059     MIB.setMemRefs(MMOBegin, MMOEnd);
8060   }
8061
8062   // Naked functions never have a base pointer, and so we use r1. For all
8063   // other functions, this decision must be delayed until during PEI.
8064   unsigned BaseReg;
8065   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8066     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8067   else
8068     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8069
8070   MIB = BuildMI(*thisMBB, MI, DL,
8071                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8072             .addReg(BaseReg)
8073             .addImm(BPOffset)
8074             .addReg(BufReg);
8075   MIB.setMemRefs(MMOBegin, MMOEnd);
8076
8077   // Setup
8078   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8079   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8080   MIB.addRegMask(TRI->getNoPreservedMask());
8081
8082   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8083
8084   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8085           .addMBB(mainMBB);
8086   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8087
8088   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8089   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8090
8091   // mainMBB:
8092   //  mainDstReg = 0
8093   MIB =
8094       BuildMI(mainMBB, DL,
8095               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8096
8097   // Store IP
8098   if (Subtarget.isPPC64()) {
8099     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8100             .addReg(LabelReg)
8101             .addImm(LabelOffset)
8102             .addReg(BufReg);
8103   } else {
8104     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8105             .addReg(LabelReg)
8106             .addImm(LabelOffset)
8107             .addReg(BufReg);
8108   }
8109
8110   MIB.setMemRefs(MMOBegin, MMOEnd);
8111
8112   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8113   mainMBB->addSuccessor(sinkMBB);
8114
8115   // sinkMBB:
8116   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8117           TII->get(PPC::PHI), DstReg)
8118     .addReg(mainDstReg).addMBB(mainMBB)
8119     .addReg(restoreDstReg).addMBB(thisMBB);
8120
8121   MI->eraseFromParent();
8122   return sinkMBB;
8123 }
8124
8125 MachineBasicBlock *
8126 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8127                                      MachineBasicBlock *MBB) const {
8128   DebugLoc DL = MI->getDebugLoc();
8129   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8130
8131   MachineFunction *MF = MBB->getParent();
8132   MachineRegisterInfo &MRI = MF->getRegInfo();
8133
8134   // Memory Reference
8135   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8136   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8137
8138   MVT PVT = getPointerTy();
8139   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8140          "Invalid Pointer Size!");
8141
8142   const TargetRegisterClass *RC =
8143     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8144   unsigned Tmp = MRI.createVirtualRegister(RC);
8145   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8146   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8147   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8148   unsigned BP =
8149       (PVT == MVT::i64)
8150           ? PPC::X30
8151           : (Subtarget.isSVR4ABI() &&
8152                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8153                  ? PPC::R29
8154                  : PPC::R30);
8155
8156   MachineInstrBuilder MIB;
8157
8158   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8159   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8160   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8161   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8162
8163   unsigned BufReg = MI->getOperand(0).getReg();
8164
8165   // Reload FP (the jumped-to function may not have had a
8166   // frame pointer, and if so, then its r31 will be restored
8167   // as necessary).
8168   if (PVT == MVT::i64) {
8169     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8170             .addImm(0)
8171             .addReg(BufReg);
8172   } else {
8173     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8174             .addImm(0)
8175             .addReg(BufReg);
8176   }
8177   MIB.setMemRefs(MMOBegin, MMOEnd);
8178
8179   // Reload IP
8180   if (PVT == MVT::i64) {
8181     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8182             .addImm(LabelOffset)
8183             .addReg(BufReg);
8184   } else {
8185     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8186             .addImm(LabelOffset)
8187             .addReg(BufReg);
8188   }
8189   MIB.setMemRefs(MMOBegin, MMOEnd);
8190
8191   // Reload SP
8192   if (PVT == MVT::i64) {
8193     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8194             .addImm(SPOffset)
8195             .addReg(BufReg);
8196   } else {
8197     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8198             .addImm(SPOffset)
8199             .addReg(BufReg);
8200   }
8201   MIB.setMemRefs(MMOBegin, MMOEnd);
8202
8203   // Reload BP
8204   if (PVT == MVT::i64) {
8205     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8206             .addImm(BPOffset)
8207             .addReg(BufReg);
8208   } else {
8209     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8210             .addImm(BPOffset)
8211             .addReg(BufReg);
8212   }
8213   MIB.setMemRefs(MMOBegin, MMOEnd);
8214
8215   // Reload TOC
8216   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8217     setUsesTOCBasePtr(*MBB->getParent());
8218     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8219             .addImm(TOCOffset)
8220             .addReg(BufReg);
8221
8222     MIB.setMemRefs(MMOBegin, MMOEnd);
8223   }
8224
8225   // Jump
8226   BuildMI(*MBB, MI, DL,
8227           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8228   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8229
8230   MI->eraseFromParent();
8231   return MBB;
8232 }
8233
8234 MachineBasicBlock *
8235 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8236                                                MachineBasicBlock *BB) const {
8237   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8238       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8239     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8240         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8241       // Call lowering should have added an r2 operand to indicate a dependence
8242       // on the TOC base pointer value. It can't however, because there is no
8243       // way to mark the dependence as implicit there, and so the stackmap code
8244       // will confuse it with a regular operand. Instead, add the dependence
8245       // here.
8246       setUsesTOCBasePtr(*BB->getParent());
8247       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8248     }
8249
8250     return emitPatchPoint(MI, BB);
8251   }
8252
8253   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8254       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8255     return emitEHSjLjSetJmp(MI, BB);
8256   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8257              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8258     return emitEHSjLjLongJmp(MI, BB);
8259   }
8260
8261   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8262
8263   // To "insert" these instructions we actually have to insert their
8264   // control-flow patterns.
8265   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8266   MachineFunction::iterator It = BB;
8267   ++It;
8268
8269   MachineFunction *F = BB->getParent();
8270
8271   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8272                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8273                               MI->getOpcode() == PPC::SELECT_I4 ||
8274                               MI->getOpcode() == PPC::SELECT_I8)) {
8275     SmallVector<MachineOperand, 2> Cond;
8276     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8277         MI->getOpcode() == PPC::SELECT_CC_I8)
8278       Cond.push_back(MI->getOperand(4));
8279     else
8280       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8281     Cond.push_back(MI->getOperand(1));
8282
8283     DebugLoc dl = MI->getDebugLoc();
8284     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8285                       Cond, MI->getOperand(2).getReg(),
8286                       MI->getOperand(3).getReg());
8287   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8288              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8289              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8290              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8291              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8292              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8293              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8294              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8295              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8296              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8297              MI->getOpcode() == PPC::SELECT_I4 ||
8298              MI->getOpcode() == PPC::SELECT_I8 ||
8299              MI->getOpcode() == PPC::SELECT_F4 ||
8300              MI->getOpcode() == PPC::SELECT_F8 ||
8301              MI->getOpcode() == PPC::SELECT_QFRC ||
8302              MI->getOpcode() == PPC::SELECT_QSRC ||
8303              MI->getOpcode() == PPC::SELECT_QBRC ||
8304              MI->getOpcode() == PPC::SELECT_VRRC ||
8305              MI->getOpcode() == PPC::SELECT_VSFRC ||
8306              MI->getOpcode() == PPC::SELECT_VSRC) {
8307     // The incoming instruction knows the destination vreg to set, the
8308     // condition code register to branch on, the true/false values to
8309     // select between, and a branch opcode to use.
8310
8311     //  thisMBB:
8312     //  ...
8313     //   TrueVal = ...
8314     //   cmpTY ccX, r1, r2
8315     //   bCC copy1MBB
8316     //   fallthrough --> copy0MBB
8317     MachineBasicBlock *thisMBB = BB;
8318     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8319     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8320     DebugLoc dl = MI->getDebugLoc();
8321     F->insert(It, copy0MBB);
8322     F->insert(It, sinkMBB);
8323
8324     // Transfer the remainder of BB and its successor edges to sinkMBB.
8325     sinkMBB->splice(sinkMBB->begin(), BB,
8326                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8327     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8328
8329     // Next, add the true and fallthrough blocks as its successors.
8330     BB->addSuccessor(copy0MBB);
8331     BB->addSuccessor(sinkMBB);
8332
8333     if (MI->getOpcode() == PPC::SELECT_I4 ||
8334         MI->getOpcode() == PPC::SELECT_I8 ||
8335         MI->getOpcode() == PPC::SELECT_F4 ||
8336         MI->getOpcode() == PPC::SELECT_F8 ||
8337         MI->getOpcode() == PPC::SELECT_QFRC ||
8338         MI->getOpcode() == PPC::SELECT_QSRC ||
8339         MI->getOpcode() == PPC::SELECT_QBRC ||
8340         MI->getOpcode() == PPC::SELECT_VRRC ||
8341         MI->getOpcode() == PPC::SELECT_VSFRC ||
8342         MI->getOpcode() == PPC::SELECT_VSRC) {
8343       BuildMI(BB, dl, TII->get(PPC::BC))
8344         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8345     } else {
8346       unsigned SelectPred = MI->getOperand(4).getImm();
8347       BuildMI(BB, dl, TII->get(PPC::BCC))
8348         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8349     }
8350
8351     //  copy0MBB:
8352     //   %FalseValue = ...
8353     //   # fallthrough to sinkMBB
8354     BB = copy0MBB;
8355
8356     // Update machine-CFG edges
8357     BB->addSuccessor(sinkMBB);
8358
8359     //  sinkMBB:
8360     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8361     //  ...
8362     BB = sinkMBB;
8363     BuildMI(*BB, BB->begin(), dl,
8364             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8365       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8366       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8367   } else if (MI->getOpcode() == PPC::ReadTB) {
8368     // To read the 64-bit time-base register on a 32-bit target, we read the
8369     // two halves. Should the counter have wrapped while it was being read, we
8370     // need to try again.
8371     // ...
8372     // readLoop:
8373     // mfspr Rx,TBU # load from TBU
8374     // mfspr Ry,TB  # load from TB
8375     // mfspr Rz,TBU # load from TBU
8376     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8377     // bne readLoop   # branch if they're not equal
8378     // ...
8379
8380     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8381     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8382     DebugLoc dl = MI->getDebugLoc();
8383     F->insert(It, readMBB);
8384     F->insert(It, sinkMBB);
8385
8386     // Transfer the remainder of BB and its successor edges to sinkMBB.
8387     sinkMBB->splice(sinkMBB->begin(), BB,
8388                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8389     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8390
8391     BB->addSuccessor(readMBB);
8392     BB = readMBB;
8393
8394     MachineRegisterInfo &RegInfo = F->getRegInfo();
8395     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8396     unsigned LoReg = MI->getOperand(0).getReg();
8397     unsigned HiReg = MI->getOperand(1).getReg();
8398
8399     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8400     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8401     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8402
8403     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8404
8405     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8406       .addReg(HiReg).addReg(ReadAgainReg);
8407     BuildMI(BB, dl, TII->get(PPC::BCC))
8408       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8409
8410     BB->addSuccessor(readMBB);
8411     BB->addSuccessor(sinkMBB);
8412   }
8413   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8414     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8415   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8416     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8417   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8418     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
8419   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8420     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
8421
8422   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8423     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8424   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8425     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8426   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8427     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
8428   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8429     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
8430
8431   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8432     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8433   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8434     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8435   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8436     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
8437   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8438     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
8439
8440   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8441     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8442   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8443     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8444   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8445     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
8446   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8447     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
8448
8449   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8450     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8451   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8452     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8453   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8454     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
8455   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8456     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
8457
8458   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8459     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8460   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8461     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8462   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8463     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
8464   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8465     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
8466
8467   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8468     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8469   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8470     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8471   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8472     BB = EmitAtomicBinary(MI, BB, false, 0);
8473   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8474     BB = EmitAtomicBinary(MI, BB, true, 0);
8475
8476   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8477            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
8478     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8479
8480     unsigned dest   = MI->getOperand(0).getReg();
8481     unsigned ptrA   = MI->getOperand(1).getReg();
8482     unsigned ptrB   = MI->getOperand(2).getReg();
8483     unsigned oldval = MI->getOperand(3).getReg();
8484     unsigned newval = MI->getOperand(4).getReg();
8485     DebugLoc dl     = MI->getDebugLoc();
8486
8487     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8488     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8489     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8490     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8491     F->insert(It, loop1MBB);
8492     F->insert(It, loop2MBB);
8493     F->insert(It, midMBB);
8494     F->insert(It, exitMBB);
8495     exitMBB->splice(exitMBB->begin(), BB,
8496                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8497     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8498
8499     //  thisMBB:
8500     //   ...
8501     //   fallthrough --> loopMBB
8502     BB->addSuccessor(loop1MBB);
8503
8504     // loop1MBB:
8505     //   l[wd]arx dest, ptr
8506     //   cmp[wd] dest, oldval
8507     //   bne- midMBB
8508     // loop2MBB:
8509     //   st[wd]cx. newval, ptr
8510     //   bne- loopMBB
8511     //   b exitBB
8512     // midMBB:
8513     //   st[wd]cx. dest, ptr
8514     // exitBB:
8515     BB = loop1MBB;
8516     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
8517       .addReg(ptrA).addReg(ptrB);
8518     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8519       .addReg(oldval).addReg(dest);
8520     BuildMI(BB, dl, TII->get(PPC::BCC))
8521       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8522     BB->addSuccessor(loop2MBB);
8523     BB->addSuccessor(midMBB);
8524
8525     BB = loop2MBB;
8526     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8527       .addReg(newval).addReg(ptrA).addReg(ptrB);
8528     BuildMI(BB, dl, TII->get(PPC::BCC))
8529       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8530     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8531     BB->addSuccessor(loop1MBB);
8532     BB->addSuccessor(exitMBB);
8533
8534     BB = midMBB;
8535     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
8536       .addReg(dest).addReg(ptrA).addReg(ptrB);
8537     BB->addSuccessor(exitMBB);
8538
8539     //  exitMBB:
8540     //   ...
8541     BB = exitMBB;
8542   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8543              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8544     // We must use 64-bit registers for addresses when targeting 64-bit,
8545     // since we're actually doing arithmetic on them.  Other registers
8546     // can be 32-bit.
8547     bool is64bit = Subtarget.isPPC64();
8548     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8549
8550     unsigned dest   = MI->getOperand(0).getReg();
8551     unsigned ptrA   = MI->getOperand(1).getReg();
8552     unsigned ptrB   = MI->getOperand(2).getReg();
8553     unsigned oldval = MI->getOperand(3).getReg();
8554     unsigned newval = MI->getOperand(4).getReg();
8555     DebugLoc dl     = MI->getDebugLoc();
8556
8557     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8558     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8559     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8560     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8561     F->insert(It, loop1MBB);
8562     F->insert(It, loop2MBB);
8563     F->insert(It, midMBB);
8564     F->insert(It, exitMBB);
8565     exitMBB->splice(exitMBB->begin(), BB,
8566                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8567     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8568
8569     MachineRegisterInfo &RegInfo = F->getRegInfo();
8570     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8571                                             : &PPC::GPRCRegClass;
8572     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8573     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8574     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8575     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8576     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8577     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8578     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8579     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8580     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8581     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8582     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8583     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8584     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8585     unsigned Ptr1Reg;
8586     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8587     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8588     //  thisMBB:
8589     //   ...
8590     //   fallthrough --> loopMBB
8591     BB->addSuccessor(loop1MBB);
8592
8593     // The 4-byte load must be aligned, while a char or short may be
8594     // anywhere in the word.  Hence all this nasty bookkeeping code.
8595     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8596     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8597     //   xori shift, shift1, 24 [16]
8598     //   rlwinm ptr, ptr1, 0, 0, 29
8599     //   slw newval2, newval, shift
8600     //   slw oldval2, oldval,shift
8601     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8602     //   slw mask, mask2, shift
8603     //   and newval3, newval2, mask
8604     //   and oldval3, oldval2, mask
8605     // loop1MBB:
8606     //   lwarx tmpDest, ptr
8607     //   and tmp, tmpDest, mask
8608     //   cmpw tmp, oldval3
8609     //   bne- midMBB
8610     // loop2MBB:
8611     //   andc tmp2, tmpDest, mask
8612     //   or tmp4, tmp2, newval3
8613     //   stwcx. tmp4, ptr
8614     //   bne- loop1MBB
8615     //   b exitBB
8616     // midMBB:
8617     //   stwcx. tmpDest, ptr
8618     // exitBB:
8619     //   srw dest, tmpDest, shift
8620     if (ptrA != ZeroReg) {
8621       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8622       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8623         .addReg(ptrA).addReg(ptrB);
8624     } else {
8625       Ptr1Reg = ptrB;
8626     }
8627     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8628         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8629     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8630         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8631     if (is64bit)
8632       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8633         .addReg(Ptr1Reg).addImm(0).addImm(61);
8634     else
8635       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8636         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8637     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8638         .addReg(newval).addReg(ShiftReg);
8639     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8640         .addReg(oldval).addReg(ShiftReg);
8641     if (is8bit)
8642       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8643     else {
8644       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8645       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8646         .addReg(Mask3Reg).addImm(65535);
8647     }
8648     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8649         .addReg(Mask2Reg).addReg(ShiftReg);
8650     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8651         .addReg(NewVal2Reg).addReg(MaskReg);
8652     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8653         .addReg(OldVal2Reg).addReg(MaskReg);
8654
8655     BB = loop1MBB;
8656     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8657         .addReg(ZeroReg).addReg(PtrReg);
8658     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8659         .addReg(TmpDestReg).addReg(MaskReg);
8660     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8661         .addReg(TmpReg).addReg(OldVal3Reg);
8662     BuildMI(BB, dl, TII->get(PPC::BCC))
8663         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8664     BB->addSuccessor(loop2MBB);
8665     BB->addSuccessor(midMBB);
8666
8667     BB = loop2MBB;
8668     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8669         .addReg(TmpDestReg).addReg(MaskReg);
8670     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8671         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8672     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8673         .addReg(ZeroReg).addReg(PtrReg);
8674     BuildMI(BB, dl, TII->get(PPC::BCC))
8675       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8676     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8677     BB->addSuccessor(loop1MBB);
8678     BB->addSuccessor(exitMBB);
8679
8680     BB = midMBB;
8681     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8682       .addReg(ZeroReg).addReg(PtrReg);
8683     BB->addSuccessor(exitMBB);
8684
8685     //  exitMBB:
8686     //   ...
8687     BB = exitMBB;
8688     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8689       .addReg(ShiftReg);
8690   } else if (MI->getOpcode() == PPC::FADDrtz) {
8691     // This pseudo performs an FADD with rounding mode temporarily forced
8692     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8693     // is not modeled at the SelectionDAG level.
8694     unsigned Dest = MI->getOperand(0).getReg();
8695     unsigned Src1 = MI->getOperand(1).getReg();
8696     unsigned Src2 = MI->getOperand(2).getReg();
8697     DebugLoc dl   = MI->getDebugLoc();
8698
8699     MachineRegisterInfo &RegInfo = F->getRegInfo();
8700     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8701
8702     // Save FPSCR value.
8703     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8704
8705     // Set rounding mode to round-to-zero.
8706     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8707     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8708
8709     // Perform addition.
8710     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8711
8712     // Restore FPSCR value.
8713     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8714   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8715              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8716              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8717              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8718     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8719                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8720                       PPC::ANDIo8 : PPC::ANDIo;
8721     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8722                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8723
8724     MachineRegisterInfo &RegInfo = F->getRegInfo();
8725     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8726                                                   &PPC::GPRCRegClass :
8727                                                   &PPC::G8RCRegClass);
8728
8729     DebugLoc dl   = MI->getDebugLoc();
8730     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8731       .addReg(MI->getOperand(1).getReg()).addImm(1);
8732     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8733             MI->getOperand(0).getReg())
8734       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8735   } else {
8736     llvm_unreachable("Unexpected instr type to insert");
8737   }
8738
8739   MI->eraseFromParent();   // The pseudo instruction is gone now.
8740   return BB;
8741 }
8742
8743 //===----------------------------------------------------------------------===//
8744 // Target Optimization Hooks
8745 //===----------------------------------------------------------------------===//
8746
8747 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8748                                             DAGCombinerInfo &DCI,
8749                                             unsigned &RefinementSteps,
8750                                             bool &UseOneConstNR) const {
8751   EVT VT = Operand.getValueType();
8752   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8753       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8754       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8755       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8756       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8757       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8758     // Convergence is quadratic, so we essentially double the number of digits
8759     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8760     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8761     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8762     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8763     if (VT.getScalarType() == MVT::f64)
8764       ++RefinementSteps;
8765     UseOneConstNR = true;
8766     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8767   }
8768   return SDValue();
8769 }
8770
8771 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8772                                             DAGCombinerInfo &DCI,
8773                                             unsigned &RefinementSteps) const {
8774   EVT VT = Operand.getValueType();
8775   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8776       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8777       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8778       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8779       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8780       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8781     // Convergence is quadratic, so we essentially double the number of digits
8782     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8783     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8784     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8785     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8786     if (VT.getScalarType() == MVT::f64)
8787       ++RefinementSteps;
8788     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8789   }
8790   return SDValue();
8791 }
8792
8793 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8794   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8795   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8796   // enabled for division), this functionality is redundant with the default
8797   // combiner logic (once the division -> reciprocal/multiply transformation
8798   // has taken place). As a result, this matters more for older cores than for
8799   // newer ones.
8800
8801   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8802   // reciprocal if there are two or more FDIVs (for embedded cores with only
8803   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8804   switch (Subtarget.getDarwinDirective()) {
8805   default:
8806     return NumUsers > 2;
8807   case PPC::DIR_440:
8808   case PPC::DIR_A2:
8809   case PPC::DIR_E500mc:
8810   case PPC::DIR_E5500:
8811     return NumUsers > 1;
8812   }
8813 }
8814
8815 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8816                             unsigned Bytes, int Dist,
8817                             SelectionDAG &DAG) {
8818   if (VT.getSizeInBits() / 8 != Bytes)
8819     return false;
8820
8821   SDValue BaseLoc = Base->getBasePtr();
8822   if (Loc.getOpcode() == ISD::FrameIndex) {
8823     if (BaseLoc.getOpcode() != ISD::FrameIndex)
8824       return false;
8825     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8826     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
8827     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8828     int FS  = MFI->getObjectSize(FI);
8829     int BFS = MFI->getObjectSize(BFI);
8830     if (FS != BFS || FS != (int)Bytes) return false;
8831     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8832   }
8833
8834   // Handle X+C
8835   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8836       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8837     return true;
8838
8839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8840   const GlobalValue *GV1 = nullptr;
8841   const GlobalValue *GV2 = nullptr;
8842   int64_t Offset1 = 0;
8843   int64_t Offset2 = 0;
8844   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8845   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8846   if (isGA1 && isGA2 && GV1 == GV2)
8847     return Offset1 == (Offset2 + Dist*Bytes);
8848   return false;
8849 }
8850
8851 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8852 // not enforce equality of the chain operands.
8853 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8854                             unsigned Bytes, int Dist,
8855                             SelectionDAG &DAG) {
8856   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8857     EVT VT = LS->getMemoryVT();
8858     SDValue Loc = LS->getBasePtr();
8859     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8860   }
8861
8862   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8863     EVT VT;
8864     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8865     default: return false;
8866     case Intrinsic::ppc_qpx_qvlfd:
8867     case Intrinsic::ppc_qpx_qvlfda:
8868       VT = MVT::v4f64;
8869       break;
8870     case Intrinsic::ppc_qpx_qvlfs:
8871     case Intrinsic::ppc_qpx_qvlfsa:
8872       VT = MVT::v4f32;
8873       break;
8874     case Intrinsic::ppc_qpx_qvlfcd:
8875     case Intrinsic::ppc_qpx_qvlfcda:
8876       VT = MVT::v2f64;
8877       break;
8878     case Intrinsic::ppc_qpx_qvlfcs:
8879     case Intrinsic::ppc_qpx_qvlfcsa:
8880       VT = MVT::v2f32;
8881       break;
8882     case Intrinsic::ppc_qpx_qvlfiwa:
8883     case Intrinsic::ppc_qpx_qvlfiwz:
8884     case Intrinsic::ppc_altivec_lvx:
8885     case Intrinsic::ppc_altivec_lvxl:
8886     case Intrinsic::ppc_vsx_lxvw4x:
8887       VT = MVT::v4i32;
8888       break;
8889     case Intrinsic::ppc_vsx_lxvd2x:
8890       VT = MVT::v2f64;
8891       break;
8892     case Intrinsic::ppc_altivec_lvebx:
8893       VT = MVT::i8;
8894       break;
8895     case Intrinsic::ppc_altivec_lvehx:
8896       VT = MVT::i16;
8897       break;
8898     case Intrinsic::ppc_altivec_lvewx:
8899       VT = MVT::i32;
8900       break;
8901     }
8902
8903     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8904   }
8905
8906   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8907     EVT VT;
8908     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8909     default: return false;
8910     case Intrinsic::ppc_qpx_qvstfd:
8911     case Intrinsic::ppc_qpx_qvstfda:
8912       VT = MVT::v4f64;
8913       break;
8914     case Intrinsic::ppc_qpx_qvstfs:
8915     case Intrinsic::ppc_qpx_qvstfsa:
8916       VT = MVT::v4f32;
8917       break;
8918     case Intrinsic::ppc_qpx_qvstfcd:
8919     case Intrinsic::ppc_qpx_qvstfcda:
8920       VT = MVT::v2f64;
8921       break;
8922     case Intrinsic::ppc_qpx_qvstfcs:
8923     case Intrinsic::ppc_qpx_qvstfcsa:
8924       VT = MVT::v2f32;
8925       break;
8926     case Intrinsic::ppc_qpx_qvstfiw:
8927     case Intrinsic::ppc_qpx_qvstfiwa:
8928     case Intrinsic::ppc_altivec_stvx:
8929     case Intrinsic::ppc_altivec_stvxl:
8930     case Intrinsic::ppc_vsx_stxvw4x:
8931       VT = MVT::v4i32;
8932       break;
8933     case Intrinsic::ppc_vsx_stxvd2x:
8934       VT = MVT::v2f64;
8935       break;
8936     case Intrinsic::ppc_altivec_stvebx:
8937       VT = MVT::i8;
8938       break;
8939     case Intrinsic::ppc_altivec_stvehx:
8940       VT = MVT::i16;
8941       break;
8942     case Intrinsic::ppc_altivec_stvewx:
8943       VT = MVT::i32;
8944       break;
8945     }
8946
8947     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8948   }
8949
8950   return false;
8951 }
8952
8953 // Return true is there is a nearyby consecutive load to the one provided
8954 // (regardless of alignment). We search up and down the chain, looking though
8955 // token factors and other loads (but nothing else). As a result, a true result
8956 // indicates that it is safe to create a new consecutive load adjacent to the
8957 // load provided.
8958 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
8959   SDValue Chain = LD->getChain();
8960   EVT VT = LD->getMemoryVT();
8961
8962   SmallSet<SDNode *, 16> LoadRoots;
8963   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
8964   SmallSet<SDNode *, 16> Visited;
8965
8966   // First, search up the chain, branching to follow all token-factor operands.
8967   // If we find a consecutive load, then we're done, otherwise, record all
8968   // nodes just above the top-level loads and token factors.
8969   while (!Queue.empty()) {
8970     SDNode *ChainNext = Queue.pop_back_val();
8971     if (!Visited.insert(ChainNext).second)
8972       continue;
8973
8974     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
8975       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
8976         return true;
8977
8978       if (!Visited.count(ChainLD->getChain().getNode()))
8979         Queue.push_back(ChainLD->getChain().getNode());
8980     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
8981       for (const SDUse &O : ChainNext->ops())
8982         if (!Visited.count(O.getNode()))
8983           Queue.push_back(O.getNode());
8984     } else
8985       LoadRoots.insert(ChainNext);
8986   }
8987
8988   // Second, search down the chain, starting from the top-level nodes recorded
8989   // in the first phase. These top-level nodes are the nodes just above all
8990   // loads and token factors. Starting with their uses, recursively look though
8991   // all loads (just the chain uses) and token factors to find a consecutive
8992   // load.
8993   Visited.clear();
8994   Queue.clear();
8995
8996   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
8997        IE = LoadRoots.end(); I != IE; ++I) {
8998     Queue.push_back(*I);
8999        
9000     while (!Queue.empty()) {
9001       SDNode *LoadRoot = Queue.pop_back_val();
9002       if (!Visited.insert(LoadRoot).second)
9003         continue;
9004
9005       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9006         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9007           return true;
9008
9009       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9010            UE = LoadRoot->use_end(); UI != UE; ++UI)
9011         if (((isa<MemSDNode>(*UI) &&
9012             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9013             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9014           Queue.push_back(*UI);
9015     }
9016   }
9017
9018   return false;
9019 }
9020
9021 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9022                                                   DAGCombinerInfo &DCI) const {
9023   SelectionDAG &DAG = DCI.DAG;
9024   SDLoc dl(N);
9025
9026   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9027   // If we're tracking CR bits, we need to be careful that we don't have:
9028   //   trunc(binary-ops(zext(x), zext(y)))
9029   // or
9030   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9031   // such that we're unnecessarily moving things into GPRs when it would be
9032   // better to keep them in CR bits.
9033
9034   // Note that trunc here can be an actual i1 trunc, or can be the effective
9035   // truncation that comes from a setcc or select_cc.
9036   if (N->getOpcode() == ISD::TRUNCATE &&
9037       N->getValueType(0) != MVT::i1)
9038     return SDValue();
9039
9040   if (N->getOperand(0).getValueType() != MVT::i32 &&
9041       N->getOperand(0).getValueType() != MVT::i64)
9042     return SDValue();
9043
9044   if (N->getOpcode() == ISD::SETCC ||
9045       N->getOpcode() == ISD::SELECT_CC) {
9046     // If we're looking at a comparison, then we need to make sure that the
9047     // high bits (all except for the first) don't matter the result.
9048     ISD::CondCode CC =
9049       cast<CondCodeSDNode>(N->getOperand(
9050         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9051     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9052
9053     if (ISD::isSignedIntSetCC(CC)) {
9054       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9055           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9056         return SDValue();
9057     } else if (ISD::isUnsignedIntSetCC(CC)) {
9058       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9059                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9060           !DAG.MaskedValueIsZero(N->getOperand(1),
9061                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9062         return SDValue();
9063     } else {
9064       // This is neither a signed nor an unsigned comparison, just make sure
9065       // that the high bits are equal.
9066       APInt Op1Zero, Op1One;
9067       APInt Op2Zero, Op2One;
9068       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9069       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9070
9071       // We don't really care about what is known about the first bit (if
9072       // anything), so clear it in all masks prior to comparing them.
9073       Op1Zero.clearBit(0); Op1One.clearBit(0);
9074       Op2Zero.clearBit(0); Op2One.clearBit(0);
9075
9076       if (Op1Zero != Op2Zero || Op1One != Op2One)
9077         return SDValue();
9078     }
9079   }
9080
9081   // We now know that the higher-order bits are irrelevant, we just need to
9082   // make sure that all of the intermediate operations are bit operations, and
9083   // all inputs are extensions.
9084   if (N->getOperand(0).getOpcode() != ISD::AND &&
9085       N->getOperand(0).getOpcode() != ISD::OR  &&
9086       N->getOperand(0).getOpcode() != ISD::XOR &&
9087       N->getOperand(0).getOpcode() != ISD::SELECT &&
9088       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9089       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9090       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9091       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9092       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9093     return SDValue();
9094
9095   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9096       N->getOperand(1).getOpcode() != ISD::AND &&
9097       N->getOperand(1).getOpcode() != ISD::OR  &&
9098       N->getOperand(1).getOpcode() != ISD::XOR &&
9099       N->getOperand(1).getOpcode() != ISD::SELECT &&
9100       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9101       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9102       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9103       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9104       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9105     return SDValue();
9106
9107   SmallVector<SDValue, 4> Inputs;
9108   SmallVector<SDValue, 8> BinOps, PromOps;
9109   SmallPtrSet<SDNode *, 16> Visited;
9110
9111   for (unsigned i = 0; i < 2; ++i) {
9112     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9113           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9114           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9115           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9116         isa<ConstantSDNode>(N->getOperand(i)))
9117       Inputs.push_back(N->getOperand(i));
9118     else
9119       BinOps.push_back(N->getOperand(i));
9120
9121     if (N->getOpcode() == ISD::TRUNCATE)
9122       break;
9123   }
9124
9125   // Visit all inputs, collect all binary operations (and, or, xor and
9126   // select) that are all fed by extensions. 
9127   while (!BinOps.empty()) {
9128     SDValue BinOp = BinOps.back();
9129     BinOps.pop_back();
9130
9131     if (!Visited.insert(BinOp.getNode()).second)
9132       continue;
9133
9134     PromOps.push_back(BinOp);
9135
9136     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9137       // The condition of the select is not promoted.
9138       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9139         continue;
9140       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9141         continue;
9142
9143       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9144             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9145             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9146            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9147           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9148         Inputs.push_back(BinOp.getOperand(i)); 
9149       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9150                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9151                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9152                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9153                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9154                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9155                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9156                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9157                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9158         BinOps.push_back(BinOp.getOperand(i));
9159       } else {
9160         // We have an input that is not an extension or another binary
9161         // operation; we'll abort this transformation.
9162         return SDValue();
9163       }
9164     }
9165   }
9166
9167   // Make sure that this is a self-contained cluster of operations (which
9168   // is not quite the same thing as saying that everything has only one
9169   // use).
9170   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9171     if (isa<ConstantSDNode>(Inputs[i]))
9172       continue;
9173
9174     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9175                               UE = Inputs[i].getNode()->use_end();
9176          UI != UE; ++UI) {
9177       SDNode *User = *UI;
9178       if (User != N && !Visited.count(User))
9179         return SDValue();
9180
9181       // Make sure that we're not going to promote the non-output-value
9182       // operand(s) or SELECT or SELECT_CC.
9183       // FIXME: Although we could sometimes handle this, and it does occur in
9184       // practice that one of the condition inputs to the select is also one of
9185       // the outputs, we currently can't deal with this.
9186       if (User->getOpcode() == ISD::SELECT) {
9187         if (User->getOperand(0) == Inputs[i])
9188           return SDValue();
9189       } else if (User->getOpcode() == ISD::SELECT_CC) {
9190         if (User->getOperand(0) == Inputs[i] ||
9191             User->getOperand(1) == Inputs[i])
9192           return SDValue();
9193       }
9194     }
9195   }
9196
9197   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9198     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9199                               UE = PromOps[i].getNode()->use_end();
9200          UI != UE; ++UI) {
9201       SDNode *User = *UI;
9202       if (User != N && !Visited.count(User))
9203         return SDValue();
9204
9205       // Make sure that we're not going to promote the non-output-value
9206       // operand(s) or SELECT or SELECT_CC.
9207       // FIXME: Although we could sometimes handle this, and it does occur in
9208       // practice that one of the condition inputs to the select is also one of
9209       // the outputs, we currently can't deal with this.
9210       if (User->getOpcode() == ISD::SELECT) {
9211         if (User->getOperand(0) == PromOps[i])
9212           return SDValue();
9213       } else if (User->getOpcode() == ISD::SELECT_CC) {
9214         if (User->getOperand(0) == PromOps[i] ||
9215             User->getOperand(1) == PromOps[i])
9216           return SDValue();
9217       }
9218     }
9219   }
9220
9221   // Replace all inputs with the extension operand.
9222   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9223     // Constants may have users outside the cluster of to-be-promoted nodes,
9224     // and so we need to replace those as we do the promotions.
9225     if (isa<ConstantSDNode>(Inputs[i]))
9226       continue;
9227     else
9228       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9229   }
9230
9231   // Replace all operations (these are all the same, but have a different
9232   // (i1) return type). DAG.getNode will validate that the types of
9233   // a binary operator match, so go through the list in reverse so that
9234   // we've likely promoted both operands first. Any intermediate truncations or
9235   // extensions disappear.
9236   while (!PromOps.empty()) {
9237     SDValue PromOp = PromOps.back();
9238     PromOps.pop_back();
9239
9240     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9241         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9242         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9243         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9244       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9245           PromOp.getOperand(0).getValueType() != MVT::i1) {
9246         // The operand is not yet ready (see comment below).
9247         PromOps.insert(PromOps.begin(), PromOp);
9248         continue;
9249       }
9250
9251       SDValue RepValue = PromOp.getOperand(0);
9252       if (isa<ConstantSDNode>(RepValue))
9253         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9254
9255       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9256       continue;
9257     }
9258
9259     unsigned C;
9260     switch (PromOp.getOpcode()) {
9261     default:             C = 0; break;
9262     case ISD::SELECT:    C = 1; break;
9263     case ISD::SELECT_CC: C = 2; break;
9264     }
9265
9266     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9267          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9268         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9269          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9270       // The to-be-promoted operands of this node have not yet been
9271       // promoted (this should be rare because we're going through the
9272       // list backward, but if one of the operands has several users in
9273       // this cluster of to-be-promoted nodes, it is possible).
9274       PromOps.insert(PromOps.begin(), PromOp);
9275       continue;
9276     }
9277
9278     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9279                                 PromOp.getNode()->op_end());
9280
9281     // If there are any constant inputs, make sure they're replaced now.
9282     for (unsigned i = 0; i < 2; ++i)
9283       if (isa<ConstantSDNode>(Ops[C+i]))
9284         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9285
9286     DAG.ReplaceAllUsesOfValueWith(PromOp,
9287       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9288   }
9289
9290   // Now we're left with the initial truncation itself.
9291   if (N->getOpcode() == ISD::TRUNCATE)
9292     return N->getOperand(0);
9293
9294   // Otherwise, this is a comparison. The operands to be compared have just
9295   // changed type (to i1), but everything else is the same.
9296   return SDValue(N, 0);
9297 }
9298
9299 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9300                                                   DAGCombinerInfo &DCI) const {
9301   SelectionDAG &DAG = DCI.DAG;
9302   SDLoc dl(N);
9303
9304   // If we're tracking CR bits, we need to be careful that we don't have:
9305   //   zext(binary-ops(trunc(x), trunc(y)))
9306   // or
9307   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9308   // such that we're unnecessarily moving things into CR bits that can more
9309   // efficiently stay in GPRs. Note that if we're not certain that the high
9310   // bits are set as required by the final extension, we still may need to do
9311   // some masking to get the proper behavior.
9312
9313   // This same functionality is important on PPC64 when dealing with
9314   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9315   // the return values of functions. Because it is so similar, it is handled
9316   // here as well.
9317
9318   if (N->getValueType(0) != MVT::i32 &&
9319       N->getValueType(0) != MVT::i64)
9320     return SDValue();
9321
9322   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9323         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9324     return SDValue();
9325
9326   if (N->getOperand(0).getOpcode() != ISD::AND &&
9327       N->getOperand(0).getOpcode() != ISD::OR  &&
9328       N->getOperand(0).getOpcode() != ISD::XOR &&
9329       N->getOperand(0).getOpcode() != ISD::SELECT &&
9330       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9331     return SDValue();
9332
9333   SmallVector<SDValue, 4> Inputs;
9334   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9335   SmallPtrSet<SDNode *, 16> Visited;
9336
9337   // Visit all inputs, collect all binary operations (and, or, xor and
9338   // select) that are all fed by truncations. 
9339   while (!BinOps.empty()) {
9340     SDValue BinOp = BinOps.back();
9341     BinOps.pop_back();
9342
9343     if (!Visited.insert(BinOp.getNode()).second)
9344       continue;
9345
9346     PromOps.push_back(BinOp);
9347
9348     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9349       // The condition of the select is not promoted.
9350       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9351         continue;
9352       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9353         continue;
9354
9355       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9356           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9357         Inputs.push_back(BinOp.getOperand(i)); 
9358       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9359                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9360                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9361                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9362                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9363         BinOps.push_back(BinOp.getOperand(i));
9364       } else {
9365         // We have an input that is not a truncation or another binary
9366         // operation; we'll abort this transformation.
9367         return SDValue();
9368       }
9369     }
9370   }
9371
9372   // The operands of a select that must be truncated when the select is
9373   // promoted because the operand is actually part of the to-be-promoted set.
9374   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9375
9376   // Make sure that this is a self-contained cluster of operations (which
9377   // is not quite the same thing as saying that everything has only one
9378   // use).
9379   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9380     if (isa<ConstantSDNode>(Inputs[i]))
9381       continue;
9382
9383     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9384                               UE = Inputs[i].getNode()->use_end();
9385          UI != UE; ++UI) {
9386       SDNode *User = *UI;
9387       if (User != N && !Visited.count(User))
9388         return SDValue();
9389
9390       // If we're going to promote the non-output-value operand(s) or SELECT or
9391       // SELECT_CC, record them for truncation.
9392       if (User->getOpcode() == ISD::SELECT) {
9393         if (User->getOperand(0) == Inputs[i])
9394           SelectTruncOp[0].insert(std::make_pair(User,
9395                                     User->getOperand(0).getValueType()));
9396       } else if (User->getOpcode() == ISD::SELECT_CC) {
9397         if (User->getOperand(0) == Inputs[i])
9398           SelectTruncOp[0].insert(std::make_pair(User,
9399                                     User->getOperand(0).getValueType()));
9400         if (User->getOperand(1) == Inputs[i])
9401           SelectTruncOp[1].insert(std::make_pair(User,
9402                                     User->getOperand(1).getValueType()));
9403       }
9404     }
9405   }
9406
9407   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9408     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9409                               UE = PromOps[i].getNode()->use_end();
9410          UI != UE; ++UI) {
9411       SDNode *User = *UI;
9412       if (User != N && !Visited.count(User))
9413         return SDValue();
9414
9415       // If we're going to promote the non-output-value operand(s) or SELECT or
9416       // SELECT_CC, record them for truncation.
9417       if (User->getOpcode() == ISD::SELECT) {
9418         if (User->getOperand(0) == PromOps[i])
9419           SelectTruncOp[0].insert(std::make_pair(User,
9420                                     User->getOperand(0).getValueType()));
9421       } else if (User->getOpcode() == ISD::SELECT_CC) {
9422         if (User->getOperand(0) == PromOps[i])
9423           SelectTruncOp[0].insert(std::make_pair(User,
9424                                     User->getOperand(0).getValueType()));
9425         if (User->getOperand(1) == PromOps[i])
9426           SelectTruncOp[1].insert(std::make_pair(User,
9427                                     User->getOperand(1).getValueType()));
9428       }
9429     }
9430   }
9431
9432   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9433   bool ReallyNeedsExt = false;
9434   if (N->getOpcode() != ISD::ANY_EXTEND) {
9435     // If all of the inputs are not already sign/zero extended, then
9436     // we'll still need to do that at the end.
9437     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9438       if (isa<ConstantSDNode>(Inputs[i]))
9439         continue;
9440
9441       unsigned OpBits =
9442         Inputs[i].getOperand(0).getValueSizeInBits();
9443       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9444
9445       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9446            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9447                                   APInt::getHighBitsSet(OpBits,
9448                                                         OpBits-PromBits))) ||
9449           (N->getOpcode() == ISD::SIGN_EXTEND &&
9450            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9451              (OpBits-(PromBits-1)))) {
9452         ReallyNeedsExt = true;
9453         break;
9454       }
9455     }
9456   }
9457
9458   // Replace all inputs, either with the truncation operand, or a
9459   // truncation or extension to the final output type.
9460   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9461     // Constant inputs need to be replaced with the to-be-promoted nodes that
9462     // use them because they might have users outside of the cluster of
9463     // promoted nodes.
9464     if (isa<ConstantSDNode>(Inputs[i]))
9465       continue;
9466
9467     SDValue InSrc = Inputs[i].getOperand(0);
9468     if (Inputs[i].getValueType() == N->getValueType(0))
9469       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9470     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9471       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9472         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9473     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9474       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9475         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9476     else
9477       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9478         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9479   }
9480
9481   // Replace all operations (these are all the same, but have a different
9482   // (promoted) return type). DAG.getNode will validate that the types of
9483   // a binary operator match, so go through the list in reverse so that
9484   // we've likely promoted both operands first.
9485   while (!PromOps.empty()) {
9486     SDValue PromOp = PromOps.back();
9487     PromOps.pop_back();
9488
9489     unsigned C;
9490     switch (PromOp.getOpcode()) {
9491     default:             C = 0; break;
9492     case ISD::SELECT:    C = 1; break;
9493     case ISD::SELECT_CC: C = 2; break;
9494     }
9495
9496     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9497          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9498         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9499          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9500       // The to-be-promoted operands of this node have not yet been
9501       // promoted (this should be rare because we're going through the
9502       // list backward, but if one of the operands has several users in
9503       // this cluster of to-be-promoted nodes, it is possible).
9504       PromOps.insert(PromOps.begin(), PromOp);
9505       continue;
9506     }
9507
9508     // For SELECT and SELECT_CC nodes, we do a similar check for any
9509     // to-be-promoted comparison inputs.
9510     if (PromOp.getOpcode() == ISD::SELECT ||
9511         PromOp.getOpcode() == ISD::SELECT_CC) {
9512       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9513            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9514           (SelectTruncOp[1].count(PromOp.getNode()) &&
9515            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9516         PromOps.insert(PromOps.begin(), PromOp);
9517         continue;
9518       }
9519     }
9520
9521     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9522                                 PromOp.getNode()->op_end());
9523
9524     // If this node has constant inputs, then they'll need to be promoted here.
9525     for (unsigned i = 0; i < 2; ++i) {
9526       if (!isa<ConstantSDNode>(Ops[C+i]))
9527         continue;
9528       if (Ops[C+i].getValueType() == N->getValueType(0))
9529         continue;
9530
9531       if (N->getOpcode() == ISD::SIGN_EXTEND)
9532         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9533       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9534         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9535       else
9536         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9537     }
9538
9539     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9540     // truncate them again to the original value type.
9541     if (PromOp.getOpcode() == ISD::SELECT ||
9542         PromOp.getOpcode() == ISD::SELECT_CC) {
9543       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9544       if (SI0 != SelectTruncOp[0].end())
9545         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9546       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9547       if (SI1 != SelectTruncOp[1].end())
9548         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9549     }
9550
9551     DAG.ReplaceAllUsesOfValueWith(PromOp,
9552       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9553   }
9554
9555   // Now we're left with the initial extension itself.
9556   if (!ReallyNeedsExt)
9557     return N->getOperand(0);
9558
9559   // To zero extend, just mask off everything except for the first bit (in the
9560   // i1 case).
9561   if (N->getOpcode() == ISD::ZERO_EXTEND)
9562     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9563                        DAG.getConstant(APInt::getLowBitsSet(
9564                                          N->getValueSizeInBits(0), PromBits),
9565                                        N->getValueType(0)));
9566
9567   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9568          "Invalid extension type");
9569   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9570   SDValue ShiftCst =
9571     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9572   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9573                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9574                                  N->getOperand(0), ShiftCst), ShiftCst);
9575 }
9576
9577 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9578                                               DAGCombinerInfo &DCI) const {
9579   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9580           N->getOpcode() == ISD::UINT_TO_FP) &&
9581          "Need an int -> FP conversion node here");
9582
9583   if (!Subtarget.has64BitSupport())
9584     return SDValue();
9585
9586   SelectionDAG &DAG = DCI.DAG;
9587   SDLoc dl(N);
9588   SDValue Op(N, 0);
9589
9590   // Don't handle ppc_fp128 here or i1 conversions.
9591   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9592     return SDValue();
9593   if (Op.getOperand(0).getValueType() == MVT::i1)
9594     return SDValue();
9595
9596   // For i32 intermediate values, unfortunately, the conversion functions
9597   // leave the upper 32 bits of the value are undefined. Within the set of
9598   // scalar instructions, we have no method for zero- or sign-extending the
9599   // value. Thus, we cannot handle i32 intermediate values here.
9600   if (Op.getOperand(0).getValueType() == MVT::i32)
9601     return SDValue();
9602
9603   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9604          "UINT_TO_FP is supported only with FPCVT");
9605
9606   // If we have FCFIDS, then use it when converting to single-precision.
9607   // Otherwise, convert to double-precision and then round.
9608   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9609                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9610                                                             : PPCISD::FCFIDS)
9611                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9612                                                             : PPCISD::FCFID);
9613   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9614                   ? MVT::f32
9615                   : MVT::f64;
9616
9617   // If we're converting from a float, to an int, and back to a float again,
9618   // then we don't need the store/load pair at all.
9619   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9620        Subtarget.hasFPCVT()) ||
9621       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9622     SDValue Src = Op.getOperand(0).getOperand(0);
9623     if (Src.getValueType() == MVT::f32) {
9624       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9625       DCI.AddToWorklist(Src.getNode());
9626     }
9627
9628     unsigned FCTOp =
9629       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9630                                                         PPCISD::FCTIDUZ;
9631
9632     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9633     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9634
9635     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9636       FP = DAG.getNode(ISD::FP_ROUND, dl,
9637                        MVT::f32, FP, DAG.getIntPtrConstant(0));
9638       DCI.AddToWorklist(FP.getNode());
9639     }
9640
9641     return FP;
9642   }
9643
9644   return SDValue();
9645 }
9646
9647 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9648 // builtins) into loads with swaps.
9649 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9650                                               DAGCombinerInfo &DCI) const {
9651   SelectionDAG &DAG = DCI.DAG;
9652   SDLoc dl(N);
9653   SDValue Chain;
9654   SDValue Base;
9655   MachineMemOperand *MMO;
9656
9657   switch (N->getOpcode()) {
9658   default:
9659     llvm_unreachable("Unexpected opcode for little endian VSX load");
9660   case ISD::LOAD: {
9661     LoadSDNode *LD = cast<LoadSDNode>(N);
9662     Chain = LD->getChain();
9663     Base = LD->getBasePtr();
9664     MMO = LD->getMemOperand();
9665     // If the MMO suggests this isn't a load of a full vector, leave
9666     // things alone.  For a built-in, we have to make the change for
9667     // correctness, so if there is a size problem that will be a bug.
9668     if (MMO->getSize() < 16)
9669       return SDValue();
9670     break;
9671   }
9672   case ISD::INTRINSIC_W_CHAIN: {
9673     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9674     Chain = Intrin->getChain();
9675     Base = Intrin->getBasePtr();
9676     MMO = Intrin->getMemOperand();
9677     break;
9678   }
9679   }
9680
9681   MVT VecTy = N->getValueType(0).getSimpleVT();
9682   SDValue LoadOps[] = { Chain, Base };
9683   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9684                                          DAG.getVTList(VecTy, MVT::Other),
9685                                          LoadOps, VecTy, MMO);
9686   DCI.AddToWorklist(Load.getNode());
9687   Chain = Load.getValue(1);
9688   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9689                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9690   DCI.AddToWorklist(Swap.getNode());
9691   return Swap;
9692 }
9693
9694 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9695 // builtins) into stores with swaps.
9696 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9697                                                DAGCombinerInfo &DCI) const {
9698   SelectionDAG &DAG = DCI.DAG;
9699   SDLoc dl(N);
9700   SDValue Chain;
9701   SDValue Base;
9702   unsigned SrcOpnd;
9703   MachineMemOperand *MMO;
9704
9705   switch (N->getOpcode()) {
9706   default:
9707     llvm_unreachable("Unexpected opcode for little endian VSX store");
9708   case ISD::STORE: {
9709     StoreSDNode *ST = cast<StoreSDNode>(N);
9710     Chain = ST->getChain();
9711     Base = ST->getBasePtr();
9712     MMO = ST->getMemOperand();
9713     SrcOpnd = 1;
9714     // If the MMO suggests this isn't a store of a full vector, leave
9715     // things alone.  For a built-in, we have to make the change for
9716     // correctness, so if there is a size problem that will be a bug.
9717     if (MMO->getSize() < 16)
9718       return SDValue();
9719     break;
9720   }
9721   case ISD::INTRINSIC_VOID: {
9722     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9723     Chain = Intrin->getChain();
9724     // Intrin->getBasePtr() oddly does not get what we want.
9725     Base = Intrin->getOperand(3);
9726     MMO = Intrin->getMemOperand();
9727     SrcOpnd = 2;
9728     break;
9729   }
9730   }
9731
9732   SDValue Src = N->getOperand(SrcOpnd);
9733   MVT VecTy = Src.getValueType().getSimpleVT();
9734   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9735                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9736   DCI.AddToWorklist(Swap.getNode());
9737   Chain = Swap.getValue(1);
9738   SDValue StoreOps[] = { Chain, Swap, Base };
9739   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9740                                           DAG.getVTList(MVT::Other),
9741                                           StoreOps, VecTy, MMO);
9742   DCI.AddToWorklist(Store.getNode());
9743   return Store;
9744 }
9745
9746 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9747                                              DAGCombinerInfo &DCI) const {
9748   SelectionDAG &DAG = DCI.DAG;
9749   SDLoc dl(N);
9750   switch (N->getOpcode()) {
9751   default: break;
9752   case PPCISD::SHL:
9753     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9754       if (C->isNullValue())   // 0 << V -> 0.
9755         return N->getOperand(0);
9756     }
9757     break;
9758   case PPCISD::SRL:
9759     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9760       if (C->isNullValue())   // 0 >>u V -> 0.
9761         return N->getOperand(0);
9762     }
9763     break;
9764   case PPCISD::SRA:
9765     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9766       if (C->isNullValue() ||   //  0 >>s V -> 0.
9767           C->isAllOnesValue())    // -1 >>s V -> -1.
9768         return N->getOperand(0);
9769     }
9770     break;
9771   case ISD::SIGN_EXTEND:
9772   case ISD::ZERO_EXTEND:
9773   case ISD::ANY_EXTEND: 
9774     return DAGCombineExtBoolTrunc(N, DCI);
9775   case ISD::TRUNCATE:
9776   case ISD::SETCC:
9777   case ISD::SELECT_CC:
9778     return DAGCombineTruncBoolExt(N, DCI);
9779   case ISD::SINT_TO_FP:
9780   case ISD::UINT_TO_FP:
9781     return combineFPToIntToFP(N, DCI);
9782   case ISD::STORE: {
9783     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9784     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9785         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9786         N->getOperand(1).getValueType() == MVT::i32 &&
9787         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9788       SDValue Val = N->getOperand(1).getOperand(0);
9789       if (Val.getValueType() == MVT::f32) {
9790         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9791         DCI.AddToWorklist(Val.getNode());
9792       }
9793       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9794       DCI.AddToWorklist(Val.getNode());
9795
9796       SDValue Ops[] = {
9797         N->getOperand(0), Val, N->getOperand(2),
9798         DAG.getValueType(N->getOperand(1).getValueType())
9799       };
9800
9801       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9802               DAG.getVTList(MVT::Other), Ops,
9803               cast<StoreSDNode>(N)->getMemoryVT(),
9804               cast<StoreSDNode>(N)->getMemOperand());
9805       DCI.AddToWorklist(Val.getNode());
9806       return Val;
9807     }
9808
9809     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9810     if (cast<StoreSDNode>(N)->isUnindexed() &&
9811         N->getOperand(1).getOpcode() == ISD::BSWAP &&
9812         N->getOperand(1).getNode()->hasOneUse() &&
9813         (N->getOperand(1).getValueType() == MVT::i32 ||
9814          N->getOperand(1).getValueType() == MVT::i16 ||
9815          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9816           N->getOperand(1).getValueType() == MVT::i64))) {
9817       SDValue BSwapOp = N->getOperand(1).getOperand(0);
9818       // Do an any-extend to 32-bits if this is a half-word input.
9819       if (BSwapOp.getValueType() == MVT::i16)
9820         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9821
9822       SDValue Ops[] = {
9823         N->getOperand(0), BSwapOp, N->getOperand(2),
9824         DAG.getValueType(N->getOperand(1).getValueType())
9825       };
9826       return
9827         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9828                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9829                                 cast<StoreSDNode>(N)->getMemOperand());
9830     }
9831
9832     // For little endian, VSX stores require generating xxswapd/lxvd2x.
9833     EVT VT = N->getOperand(1).getValueType();
9834     if (VT.isSimple()) {
9835       MVT StoreVT = VT.getSimpleVT();
9836       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9837           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9838            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9839         return expandVSXStoreForLE(N, DCI);
9840     }
9841     break;
9842   }
9843   case ISD::LOAD: {
9844     LoadSDNode *LD = cast<LoadSDNode>(N);
9845     EVT VT = LD->getValueType(0);
9846
9847     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9848     if (VT.isSimple()) {
9849       MVT LoadVT = VT.getSimpleVT();
9850       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9851           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9852            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9853         return expandVSXLoadForLE(N, DCI);
9854     }
9855
9856     EVT MemVT = LD->getMemoryVT();
9857     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9858     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9859     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9860     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9861     if (LD->isUnindexed() && VT.isVector() &&
9862         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9863           // P8 and later hardware should just use LOAD.
9864           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9865                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9866          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9867           LD->getAlignment() >= ScalarABIAlignment)) &&
9868         LD->getAlignment() < ABIAlignment) {
9869       // This is a type-legal unaligned Altivec or QPX load.
9870       SDValue Chain = LD->getChain();
9871       SDValue Ptr = LD->getBasePtr();
9872       bool isLittleEndian = Subtarget.isLittleEndian();
9873
9874       // This implements the loading of unaligned vectors as described in
9875       // the venerable Apple Velocity Engine overview. Specifically:
9876       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9877       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9878       //
9879       // The general idea is to expand a sequence of one or more unaligned
9880       // loads into an alignment-based permutation-control instruction (lvsl
9881       // or lvsr), a series of regular vector loads (which always truncate
9882       // their input address to an aligned address), and a series of
9883       // permutations.  The results of these permutations are the requested
9884       // loaded values.  The trick is that the last "extra" load is not taken
9885       // from the address you might suspect (sizeof(vector) bytes after the
9886       // last requested load), but rather sizeof(vector) - 1 bytes after the
9887       // last requested vector. The point of this is to avoid a page fault if
9888       // the base address happened to be aligned. This works because if the
9889       // base address is aligned, then adding less than a full vector length
9890       // will cause the last vector in the sequence to be (re)loaded.
9891       // Otherwise, the next vector will be fetched as you might suspect was
9892       // necessary.
9893
9894       // We might be able to reuse the permutation generation from
9895       // a different base address offset from this one by an aligned amount.
9896       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9897       // optimization later.
9898       Intrinsic::ID Intr, IntrLD, IntrPerm;
9899       MVT PermCntlTy, PermTy, LDTy;
9900       if (Subtarget.hasAltivec()) {
9901         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
9902                                  Intrinsic::ppc_altivec_lvsl;
9903         IntrLD = Intrinsic::ppc_altivec_lvx;
9904         IntrPerm = Intrinsic::ppc_altivec_vperm;
9905         PermCntlTy = MVT::v16i8;
9906         PermTy = MVT::v4i32;
9907         LDTy = MVT::v4i32;
9908       } else {
9909         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9910                                        Intrinsic::ppc_qpx_qvlpcls;
9911         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9912                                        Intrinsic::ppc_qpx_qvlfs;
9913         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9914         PermCntlTy = MVT::v4f64;
9915         PermTy = MVT::v4f64;
9916         LDTy = MemVT.getSimpleVT();
9917       }
9918
9919       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9920
9921       // Create the new MMO for the new base load. It is like the original MMO,
9922       // but represents an area in memory almost twice the vector size centered
9923       // on the original address. If the address is unaligned, we might start
9924       // reading up to (sizeof(vector)-1) bytes below the address of the
9925       // original unaligned load.
9926       MachineFunction &MF = DAG.getMachineFunction();
9927       MachineMemOperand *BaseMMO =
9928         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9929                                 2*MemVT.getStoreSize()-1);
9930
9931       // Create the new base load.
9932       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9933       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9934       SDValue BaseLoad =
9935         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9936                                 DAG.getVTList(PermTy, MVT::Other),
9937                                 BaseLoadOps, LDTy, BaseMMO);
9938
9939       // Note that the value of IncOffset (which is provided to the next
9940       // load's pointer info offset value, and thus used to calculate the
9941       // alignment), and the value of IncValue (which is actually used to
9942       // increment the pointer value) are different! This is because we
9943       // require the next load to appear to be aligned, even though it
9944       // is actually offset from the base pointer by a lesser amount.
9945       int IncOffset = VT.getSizeInBits() / 8;
9946       int IncValue = IncOffset;
9947
9948       // Walk (both up and down) the chain looking for another load at the real
9949       // (aligned) offset (the alignment of the other load does not matter in
9950       // this case). If found, then do not use the offset reduction trick, as
9951       // that will prevent the loads from being later combined (as they would
9952       // otherwise be duplicates).
9953       if (!findConsecutiveLoad(LD, DAG))
9954         --IncValue;
9955
9956       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
9957       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
9958
9959       MachineMemOperand *ExtraMMO =
9960         MF.getMachineMemOperand(LD->getMemOperand(),
9961                                 1, 2*MemVT.getStoreSize()-1);
9962       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
9963       SDValue ExtraLoad =
9964         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9965                                 DAG.getVTList(PermTy, MVT::Other),
9966                                 ExtraLoadOps, LDTy, ExtraMMO);
9967
9968       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9969         BaseLoad.getValue(1), ExtraLoad.getValue(1));
9970
9971       // Because vperm has a big-endian bias, we must reverse the order
9972       // of the input vectors and complement the permute control vector
9973       // when generating little endian code.  We have already handled the
9974       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
9975       // and ExtraLoad here.
9976       SDValue Perm;
9977       if (isLittleEndian)
9978         Perm = BuildIntrinsicOp(IntrPerm,
9979                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
9980       else
9981         Perm = BuildIntrinsicOp(IntrPerm,
9982                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
9983
9984       if (VT != PermTy)
9985         Perm = Subtarget.hasAltivec() ?
9986                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
9987                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
9988                                DAG.getTargetConstant(1, MVT::i64));
9989                                // second argument is 1 because this rounding
9990                                // is always exact.
9991
9992       // The output of the permutation is our loaded result, the TokenFactor is
9993       // our new chain.
9994       DCI.CombineTo(N, Perm, TF);
9995       return SDValue(N, 0);
9996     }
9997     }
9998     break;
9999     case ISD::INTRINSIC_WO_CHAIN: {
10000       bool isLittleEndian = Subtarget.isLittleEndian();
10001       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10002       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10003                                            : Intrinsic::ppc_altivec_lvsl);
10004       if ((IID == Intr ||
10005            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10006            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10007         N->getOperand(1)->getOpcode() == ISD::ADD) {
10008         SDValue Add = N->getOperand(1);
10009
10010         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10011                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10012
10013         if (DAG.MaskedValueIsZero(
10014                 Add->getOperand(1),
10015                 APInt::getAllOnesValue(Bits /* alignment */)
10016                     .zext(
10017                         Add.getValueType().getScalarType().getSizeInBits()))) {
10018           SDNode *BasePtr = Add->getOperand(0).getNode();
10019           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10020                                     UE = BasePtr->use_end();
10021                UI != UE; ++UI) {
10022             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10023                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10024               // We've found another LVSL/LVSR, and this address is an aligned
10025               // multiple of that one. The results will be the same, so use the
10026               // one we've just found instead.
10027
10028               return SDValue(*UI, 0);
10029             }
10030           }
10031         }
10032
10033         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10034           SDNode *BasePtr = Add->getOperand(0).getNode();
10035           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10036                UE = BasePtr->use_end(); UI != UE; ++UI) {
10037             if (UI->getOpcode() == ISD::ADD &&
10038                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10039                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10040                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10041                 (1ULL << Bits) == 0) {
10042               SDNode *OtherAdd = *UI;
10043               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10044                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10045                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10046                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10047                   return SDValue(*VI, 0);
10048                 }
10049               }
10050             }
10051           }
10052         }
10053       }
10054     }
10055
10056     break;
10057   case ISD::INTRINSIC_W_CHAIN: {
10058     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10059     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10060       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10061       default:
10062         break;
10063       case Intrinsic::ppc_vsx_lxvw4x:
10064       case Intrinsic::ppc_vsx_lxvd2x:
10065         return expandVSXLoadForLE(N, DCI);
10066       }
10067     }
10068     break;
10069   }
10070   case ISD::INTRINSIC_VOID: {
10071     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10072     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10073       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10074       default:
10075         break;
10076       case Intrinsic::ppc_vsx_stxvw4x:
10077       case Intrinsic::ppc_vsx_stxvd2x:
10078         return expandVSXStoreForLE(N, DCI);
10079       }
10080     }
10081     break;
10082   }
10083   case ISD::BSWAP:
10084     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10085     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10086         N->getOperand(0).hasOneUse() &&
10087         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10088          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10089           N->getValueType(0) == MVT::i64))) {
10090       SDValue Load = N->getOperand(0);
10091       LoadSDNode *LD = cast<LoadSDNode>(Load);
10092       // Create the byte-swapping load.
10093       SDValue Ops[] = {
10094         LD->getChain(),    // Chain
10095         LD->getBasePtr(),  // Ptr
10096         DAG.getValueType(N->getValueType(0)) // VT
10097       };
10098       SDValue BSLoad =
10099         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10100                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10101                                               MVT::i64 : MVT::i32, MVT::Other),
10102                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10103
10104       // If this is an i16 load, insert the truncate.
10105       SDValue ResVal = BSLoad;
10106       if (N->getValueType(0) == MVT::i16)
10107         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10108
10109       // First, combine the bswap away.  This makes the value produced by the
10110       // load dead.
10111       DCI.CombineTo(N, ResVal);
10112
10113       // Next, combine the load away, we give it a bogus result value but a real
10114       // chain result.  The result value is dead because the bswap is dead.
10115       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10116
10117       // Return N so it doesn't get rechecked!
10118       return SDValue(N, 0);
10119     }
10120
10121     break;
10122   case PPCISD::VCMP: {
10123     // If a VCMPo node already exists with exactly the same operands as this
10124     // node, use its result instead of this node (VCMPo computes both a CR6 and
10125     // a normal output).
10126     //
10127     if (!N->getOperand(0).hasOneUse() &&
10128         !N->getOperand(1).hasOneUse() &&
10129         !N->getOperand(2).hasOneUse()) {
10130
10131       // Scan all of the users of the LHS, looking for VCMPo's that match.
10132       SDNode *VCMPoNode = nullptr;
10133
10134       SDNode *LHSN = N->getOperand(0).getNode();
10135       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10136            UI != E; ++UI)
10137         if (UI->getOpcode() == PPCISD::VCMPo &&
10138             UI->getOperand(1) == N->getOperand(1) &&
10139             UI->getOperand(2) == N->getOperand(2) &&
10140             UI->getOperand(0) == N->getOperand(0)) {
10141           VCMPoNode = *UI;
10142           break;
10143         }
10144
10145       // If there is no VCMPo node, or if the flag value has a single use, don't
10146       // transform this.
10147       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10148         break;
10149
10150       // Look at the (necessarily single) use of the flag value.  If it has a
10151       // chain, this transformation is more complex.  Note that multiple things
10152       // could use the value result, which we should ignore.
10153       SDNode *FlagUser = nullptr;
10154       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10155            FlagUser == nullptr; ++UI) {
10156         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10157         SDNode *User = *UI;
10158         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10159           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10160             FlagUser = User;
10161             break;
10162           }
10163         }
10164       }
10165
10166       // If the user is a MFOCRF instruction, we know this is safe.
10167       // Otherwise we give up for right now.
10168       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10169         return SDValue(VCMPoNode, 0);
10170     }
10171     break;
10172   }
10173   case ISD::BRCOND: {
10174     SDValue Cond = N->getOperand(1);
10175     SDValue Target = N->getOperand(2);
10176  
10177     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10178         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10179           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10180
10181       // We now need to make the intrinsic dead (it cannot be instruction
10182       // selected).
10183       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10184       assert(Cond.getNode()->hasOneUse() &&
10185              "Counter decrement has more than one use");
10186
10187       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10188                          N->getOperand(0), Target);
10189     }
10190   }
10191   break;
10192   case ISD::BR_CC: {
10193     // If this is a branch on an altivec predicate comparison, lower this so
10194     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10195     // lowering is done pre-legalize, because the legalizer lowers the predicate
10196     // compare down to code that is difficult to reassemble.
10197     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10198     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10199
10200     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10201     // value. If so, pass-through the AND to get to the intrinsic.
10202     if (LHS.getOpcode() == ISD::AND &&
10203         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10204         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10205           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10206         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10207         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10208           isZero())
10209       LHS = LHS.getOperand(0);
10210
10211     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10212         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10213           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10214         isa<ConstantSDNode>(RHS)) {
10215       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10216              "Counter decrement comparison is not EQ or NE");
10217
10218       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10219       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10220                     (CC == ISD::SETNE && !Val);
10221
10222       // We now need to make the intrinsic dead (it cannot be instruction
10223       // selected).
10224       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10225       assert(LHS.getNode()->hasOneUse() &&
10226              "Counter decrement has more than one use");
10227
10228       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10229                          N->getOperand(0), N->getOperand(4));
10230     }
10231
10232     int CompareOpc;
10233     bool isDot;
10234
10235     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10236         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10237         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10238       assert(isDot && "Can't compare against a vector result!");
10239
10240       // If this is a comparison against something other than 0/1, then we know
10241       // that the condition is never/always true.
10242       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10243       if (Val != 0 && Val != 1) {
10244         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10245           return N->getOperand(0);
10246         // Always !=, turn it into an unconditional branch.
10247         return DAG.getNode(ISD::BR, dl, MVT::Other,
10248                            N->getOperand(0), N->getOperand(4));
10249       }
10250
10251       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10252
10253       // Create the PPCISD altivec 'dot' comparison node.
10254       SDValue Ops[] = {
10255         LHS.getOperand(2),  // LHS of compare
10256         LHS.getOperand(3),  // RHS of compare
10257         DAG.getConstant(CompareOpc, MVT::i32)
10258       };
10259       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10260       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10261
10262       // Unpack the result based on how the target uses it.
10263       PPC::Predicate CompOpc;
10264       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10265       default:  // Can't happen, don't crash on invalid number though.
10266       case 0:   // Branch on the value of the EQ bit of CR6.
10267         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10268         break;
10269       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10270         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10271         break;
10272       case 2:   // Branch on the value of the LT bit of CR6.
10273         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10274         break;
10275       case 3:   // Branch on the inverted value of the LT bit of CR6.
10276         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10277         break;
10278       }
10279
10280       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10281                          DAG.getConstant(CompOpc, MVT::i32),
10282                          DAG.getRegister(PPC::CR6, MVT::i32),
10283                          N->getOperand(4), CompNode.getValue(1));
10284     }
10285     break;
10286   }
10287   }
10288
10289   return SDValue();
10290 }
10291
10292 SDValue
10293 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10294                                   SelectionDAG &DAG,
10295                                   std::vector<SDNode *> *Created) const {
10296   // fold (sdiv X, pow2)
10297   EVT VT = N->getValueType(0);
10298   if (VT == MVT::i64 && !Subtarget.isPPC64())
10299     return SDValue();
10300   if ((VT != MVT::i32 && VT != MVT::i64) ||
10301       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10302     return SDValue();
10303
10304   SDLoc DL(N);
10305   SDValue N0 = N->getOperand(0);
10306
10307   bool IsNegPow2 = (-Divisor).isPowerOf2();
10308   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10309   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10310
10311   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10312   if (Created)
10313     Created->push_back(Op.getNode());
10314
10315   if (IsNegPow2) {
10316     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10317     if (Created)
10318       Created->push_back(Op.getNode());
10319   }
10320
10321   return Op;
10322 }
10323
10324 //===----------------------------------------------------------------------===//
10325 // Inline Assembly Support
10326 //===----------------------------------------------------------------------===//
10327
10328 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10329                                                       APInt &KnownZero,
10330                                                       APInt &KnownOne,
10331                                                       const SelectionDAG &DAG,
10332                                                       unsigned Depth) const {
10333   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10334   switch (Op.getOpcode()) {
10335   default: break;
10336   case PPCISD::LBRX: {
10337     // lhbrx is known to have the top bits cleared out.
10338     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10339       KnownZero = 0xFFFF0000;
10340     break;
10341   }
10342   case ISD::INTRINSIC_WO_CHAIN: {
10343     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10344     default: break;
10345     case Intrinsic::ppc_altivec_vcmpbfp_p:
10346     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10347     case Intrinsic::ppc_altivec_vcmpequb_p:
10348     case Intrinsic::ppc_altivec_vcmpequh_p:
10349     case Intrinsic::ppc_altivec_vcmpequw_p:
10350     case Intrinsic::ppc_altivec_vcmpequd_p:
10351     case Intrinsic::ppc_altivec_vcmpgefp_p:
10352     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10353     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10354     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10355     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10356     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10357     case Intrinsic::ppc_altivec_vcmpgtub_p:
10358     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10359     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10360     case Intrinsic::ppc_altivec_vcmpgtud_p:
10361       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10362       break;
10363     }
10364   }
10365   }
10366 }
10367
10368 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10369   switch (Subtarget.getDarwinDirective()) {
10370   default: break;
10371   case PPC::DIR_970:
10372   case PPC::DIR_PWR4:
10373   case PPC::DIR_PWR5:
10374   case PPC::DIR_PWR5X:
10375   case PPC::DIR_PWR6:
10376   case PPC::DIR_PWR6X:
10377   case PPC::DIR_PWR7:
10378   case PPC::DIR_PWR8: {
10379     if (!ML)
10380       break;
10381
10382     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10383
10384     // For small loops (between 5 and 8 instructions), align to a 32-byte
10385     // boundary so that the entire loop fits in one instruction-cache line.
10386     uint64_t LoopSize = 0;
10387     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10388       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10389         LoopSize += TII->GetInstSizeInBytes(J);
10390
10391     if (LoopSize > 16 && LoopSize <= 32)
10392       return 5;
10393
10394     break;
10395   }
10396   }
10397
10398   return TargetLowering::getPrefLoopAlignment(ML);
10399 }
10400
10401 /// getConstraintType - Given a constraint, return the type of
10402 /// constraint it is for this target.
10403 PPCTargetLowering::ConstraintType
10404 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10405   if (Constraint.size() == 1) {
10406     switch (Constraint[0]) {
10407     default: break;
10408     case 'b':
10409     case 'r':
10410     case 'f':
10411     case 'v':
10412     case 'y':
10413       return C_RegisterClass;
10414     case 'Z':
10415       // FIXME: While Z does indicate a memory constraint, it specifically
10416       // indicates an r+r address (used in conjunction with the 'y' modifier
10417       // in the replacement string). Currently, we're forcing the base
10418       // register to be r0 in the asm printer (which is interpreted as zero)
10419       // and forming the complete address in the second register. This is
10420       // suboptimal.
10421       return C_Memory;
10422     }
10423   } else if (Constraint == "wc") { // individual CR bits.
10424     return C_RegisterClass;
10425   } else if (Constraint == "wa" || Constraint == "wd" ||
10426              Constraint == "wf" || Constraint == "ws") {
10427     return C_RegisterClass; // VSX registers.
10428   }
10429   return TargetLowering::getConstraintType(Constraint);
10430 }
10431
10432 /// Examine constraint type and operand type and determine a weight value.
10433 /// This object must already have been set up with the operand type
10434 /// and the current alternative constraint selected.
10435 TargetLowering::ConstraintWeight
10436 PPCTargetLowering::getSingleConstraintMatchWeight(
10437     AsmOperandInfo &info, const char *constraint) const {
10438   ConstraintWeight weight = CW_Invalid;
10439   Value *CallOperandVal = info.CallOperandVal;
10440     // If we don't have a value, we can't do a match,
10441     // but allow it at the lowest weight.
10442   if (!CallOperandVal)
10443     return CW_Default;
10444   Type *type = CallOperandVal->getType();
10445
10446   // Look at the constraint type.
10447   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10448     return CW_Register; // an individual CR bit.
10449   else if ((StringRef(constraint) == "wa" ||
10450             StringRef(constraint) == "wd" ||
10451             StringRef(constraint) == "wf") &&
10452            type->isVectorTy())
10453     return CW_Register;
10454   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10455     return CW_Register;
10456
10457   switch (*constraint) {
10458   default:
10459     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10460     break;
10461   case 'b':
10462     if (type->isIntegerTy())
10463       weight = CW_Register;
10464     break;
10465   case 'f':
10466     if (type->isFloatTy())
10467       weight = CW_Register;
10468     break;
10469   case 'd':
10470     if (type->isDoubleTy())
10471       weight = CW_Register;
10472     break;
10473   case 'v':
10474     if (type->isVectorTy())
10475       weight = CW_Register;
10476     break;
10477   case 'y':
10478     weight = CW_Register;
10479     break;
10480   case 'Z':
10481     weight = CW_Memory;
10482     break;
10483   }
10484   return weight;
10485 }
10486
10487 std::pair<unsigned, const TargetRegisterClass *>
10488 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10489                                                 const std::string &Constraint,
10490                                                 MVT VT) const {
10491   if (Constraint.size() == 1) {
10492     // GCC RS6000 Constraint Letters
10493     switch (Constraint[0]) {
10494     case 'b':   // R1-R31
10495       if (VT == MVT::i64 && Subtarget.isPPC64())
10496         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10497       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10498     case 'r':   // R0-R31
10499       if (VT == MVT::i64 && Subtarget.isPPC64())
10500         return std::make_pair(0U, &PPC::G8RCRegClass);
10501       return std::make_pair(0U, &PPC::GPRCRegClass);
10502     case 'f':
10503       if (VT == MVT::f32 || VT == MVT::i32)
10504         return std::make_pair(0U, &PPC::F4RCRegClass);
10505       if (VT == MVT::f64 || VT == MVT::i64)
10506         return std::make_pair(0U, &PPC::F8RCRegClass);
10507       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10508         return std::make_pair(0U, &PPC::QFRCRegClass);
10509       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10510         return std::make_pair(0U, &PPC::QSRCRegClass);
10511       break;
10512     case 'v':
10513       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10514         return std::make_pair(0U, &PPC::QFRCRegClass);
10515       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10516         return std::make_pair(0U, &PPC::QSRCRegClass);
10517       return std::make_pair(0U, &PPC::VRRCRegClass);
10518     case 'y':   // crrc
10519       return std::make_pair(0U, &PPC::CRRCRegClass);
10520     }
10521   } else if (Constraint == "wc") { // an individual CR bit.
10522     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10523   } else if (Constraint == "wa" || Constraint == "wd" ||
10524              Constraint == "wf") {
10525     return std::make_pair(0U, &PPC::VSRCRegClass);
10526   } else if (Constraint == "ws") {
10527     return std::make_pair(0U, &PPC::VSFRCRegClass);
10528   }
10529
10530   std::pair<unsigned, const TargetRegisterClass *> R =
10531       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10532
10533   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10534   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10535   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10536   // register.
10537   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10538   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10539   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10540       PPC::GPRCRegClass.contains(R.first))
10541     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10542                             PPC::sub_32, &PPC::G8RCRegClass),
10543                           &PPC::G8RCRegClass);
10544
10545   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10546   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10547     R.first = PPC::CR0;
10548     R.second = &PPC::CRRCRegClass;
10549   }
10550
10551   return R;
10552 }
10553
10554
10555 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10556 /// vector.  If it is invalid, don't add anything to Ops.
10557 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10558                                                      std::string &Constraint,
10559                                                      std::vector<SDValue>&Ops,
10560                                                      SelectionDAG &DAG) const {
10561   SDValue Result;
10562
10563   // Only support length 1 constraints.
10564   if (Constraint.length() > 1) return;
10565
10566   char Letter = Constraint[0];
10567   switch (Letter) {
10568   default: break;
10569   case 'I':
10570   case 'J':
10571   case 'K':
10572   case 'L':
10573   case 'M':
10574   case 'N':
10575   case 'O':
10576   case 'P': {
10577     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10578     if (!CST) return; // Must be an immediate to match.
10579     int64_t Value = CST->getSExtValue();
10580     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10581                          // numbers are printed as such.
10582     switch (Letter) {
10583     default: llvm_unreachable("Unknown constraint letter!");
10584     case 'I':  // "I" is a signed 16-bit constant.
10585       if (isInt<16>(Value))
10586         Result = DAG.getTargetConstant(Value, TCVT);
10587       break;
10588     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10589       if (isShiftedUInt<16, 16>(Value))
10590         Result = DAG.getTargetConstant(Value, TCVT);
10591       break;
10592     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10593       if (isShiftedInt<16, 16>(Value))
10594         Result = DAG.getTargetConstant(Value, TCVT);
10595       break;
10596     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10597       if (isUInt<16>(Value))
10598         Result = DAG.getTargetConstant(Value, TCVT);
10599       break;
10600     case 'M':  // "M" is a constant that is greater than 31.
10601       if (Value > 31)
10602         Result = DAG.getTargetConstant(Value, TCVT);
10603       break;
10604     case 'N':  // "N" is a positive constant that is an exact power of two.
10605       if (Value > 0 && isPowerOf2_64(Value))
10606         Result = DAG.getTargetConstant(Value, TCVT);
10607       break;
10608     case 'O':  // "O" is the constant zero.
10609       if (Value == 0)
10610         Result = DAG.getTargetConstant(Value, TCVT);
10611       break;
10612     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10613       if (isInt<16>(-Value))
10614         Result = DAG.getTargetConstant(Value, TCVT);
10615       break;
10616     }
10617     break;
10618   }
10619   }
10620
10621   if (Result.getNode()) {
10622     Ops.push_back(Result);
10623     return;
10624   }
10625
10626   // Handle standard constraint letters.
10627   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10628 }
10629
10630 // isLegalAddressingMode - Return true if the addressing mode represented
10631 // by AM is legal for this target, for a load/store of the specified type.
10632 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10633                                               Type *Ty) const {
10634   // PPC does not allow r+i addressing modes for vectors!
10635   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10636     return false;
10637
10638   // PPC allows a sign-extended 16-bit immediate field.
10639   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10640     return false;
10641
10642   // No global is ever allowed as a base.
10643   if (AM.BaseGV)
10644     return false;
10645
10646   // PPC only support r+r,
10647   switch (AM.Scale) {
10648   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10649     break;
10650   case 1:
10651     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10652       return false;
10653     // Otherwise we have r+r or r+i.
10654     break;
10655   case 2:
10656     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10657       return false;
10658     // Allow 2*r as r+r.
10659     break;
10660   default:
10661     // No other scales are supported.
10662     return false;
10663   }
10664
10665   return true;
10666 }
10667
10668 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10669                                            SelectionDAG &DAG) const {
10670   MachineFunction &MF = DAG.getMachineFunction();
10671   MachineFrameInfo *MFI = MF.getFrameInfo();
10672   MFI->setReturnAddressIsTaken(true);
10673
10674   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10675     return SDValue();
10676
10677   SDLoc dl(Op);
10678   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10679
10680   // Make sure the function does not optimize away the store of the RA to
10681   // the stack.
10682   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10683   FuncInfo->setLRStoreRequired();
10684   bool isPPC64 = Subtarget.isPPC64();
10685
10686   if (Depth > 0) {
10687     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10688     SDValue Offset =
10689         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10690                         isPPC64 ? MVT::i64 : MVT::i32);
10691     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10692                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10693                                    FrameAddr, Offset),
10694                        MachinePointerInfo(), false, false, false, 0);
10695   }
10696
10697   // Just load the return address off the stack.
10698   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10699   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10700                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10701 }
10702
10703 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10704                                           SelectionDAG &DAG) const {
10705   SDLoc dl(Op);
10706   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10707
10708   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10709   bool isPPC64 = PtrVT == MVT::i64;
10710
10711   MachineFunction &MF = DAG.getMachineFunction();
10712   MachineFrameInfo *MFI = MF.getFrameInfo();
10713   MFI->setFrameAddressIsTaken(true);
10714
10715   // Naked functions never have a frame pointer, and so we use r1. For all
10716   // other functions, this decision must be delayed until during PEI.
10717   unsigned FrameReg;
10718   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10719     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10720   else
10721     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10722
10723   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10724                                          PtrVT);
10725   while (Depth--)
10726     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10727                             FrameAddr, MachinePointerInfo(), false, false,
10728                             false, 0);
10729   return FrameAddr;
10730 }
10731
10732 // FIXME? Maybe this could be a TableGen attribute on some registers and
10733 // this table could be generated automatically from RegInfo.
10734 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10735                                               EVT VT) const {
10736   bool isPPC64 = Subtarget.isPPC64();
10737   bool isDarwinABI = Subtarget.isDarwinABI();
10738
10739   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10740       (!isPPC64 && VT != MVT::i32))
10741     report_fatal_error("Invalid register global variable type");
10742
10743   bool is64Bit = isPPC64 && VT == MVT::i64;
10744   unsigned Reg = StringSwitch<unsigned>(RegName)
10745                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10746                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10747                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10748                                   (is64Bit ? PPC::X13 : PPC::R13))
10749                    .Default(0);
10750
10751   if (Reg)
10752     return Reg;
10753   report_fatal_error("Invalid register name global variable");
10754 }
10755
10756 bool
10757 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10758   // The PowerPC target isn't yet aware of offsets.
10759   return false;
10760 }
10761
10762 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10763                                            const CallInst &I,
10764                                            unsigned Intrinsic) const {
10765
10766   switch (Intrinsic) {
10767   case Intrinsic::ppc_qpx_qvlfd:
10768   case Intrinsic::ppc_qpx_qvlfs:
10769   case Intrinsic::ppc_qpx_qvlfcd:
10770   case Intrinsic::ppc_qpx_qvlfcs:
10771   case Intrinsic::ppc_qpx_qvlfiwa:
10772   case Intrinsic::ppc_qpx_qvlfiwz:
10773   case Intrinsic::ppc_altivec_lvx:
10774   case Intrinsic::ppc_altivec_lvxl:
10775   case Intrinsic::ppc_altivec_lvebx:
10776   case Intrinsic::ppc_altivec_lvehx:
10777   case Intrinsic::ppc_altivec_lvewx:
10778   case Intrinsic::ppc_vsx_lxvd2x:
10779   case Intrinsic::ppc_vsx_lxvw4x: {
10780     EVT VT;
10781     switch (Intrinsic) {
10782     case Intrinsic::ppc_altivec_lvebx:
10783       VT = MVT::i8;
10784       break;
10785     case Intrinsic::ppc_altivec_lvehx:
10786       VT = MVT::i16;
10787       break;
10788     case Intrinsic::ppc_altivec_lvewx:
10789       VT = MVT::i32;
10790       break;
10791     case Intrinsic::ppc_vsx_lxvd2x:
10792       VT = MVT::v2f64;
10793       break;
10794     case Intrinsic::ppc_qpx_qvlfd:
10795       VT = MVT::v4f64;
10796       break;
10797     case Intrinsic::ppc_qpx_qvlfs:
10798       VT = MVT::v4f32;
10799       break;
10800     case Intrinsic::ppc_qpx_qvlfcd:
10801       VT = MVT::v2f64;
10802       break;
10803     case Intrinsic::ppc_qpx_qvlfcs:
10804       VT = MVT::v2f32;
10805       break;
10806     default:
10807       VT = MVT::v4i32;
10808       break;
10809     }
10810
10811     Info.opc = ISD::INTRINSIC_W_CHAIN;
10812     Info.memVT = VT;
10813     Info.ptrVal = I.getArgOperand(0);
10814     Info.offset = -VT.getStoreSize()+1;
10815     Info.size = 2*VT.getStoreSize()-1;
10816     Info.align = 1;
10817     Info.vol = false;
10818     Info.readMem = true;
10819     Info.writeMem = false;
10820     return true;
10821   }
10822   case Intrinsic::ppc_qpx_qvlfda:
10823   case Intrinsic::ppc_qpx_qvlfsa:
10824   case Intrinsic::ppc_qpx_qvlfcda:
10825   case Intrinsic::ppc_qpx_qvlfcsa:
10826   case Intrinsic::ppc_qpx_qvlfiwaa:
10827   case Intrinsic::ppc_qpx_qvlfiwza: {
10828     EVT VT;
10829     switch (Intrinsic) {
10830     case Intrinsic::ppc_qpx_qvlfda:
10831       VT = MVT::v4f64;
10832       break;
10833     case Intrinsic::ppc_qpx_qvlfsa:
10834       VT = MVT::v4f32;
10835       break;
10836     case Intrinsic::ppc_qpx_qvlfcda:
10837       VT = MVT::v2f64;
10838       break;
10839     case Intrinsic::ppc_qpx_qvlfcsa:
10840       VT = MVT::v2f32;
10841       break;
10842     default:
10843       VT = MVT::v4i32;
10844       break;
10845     }
10846
10847     Info.opc = ISD::INTRINSIC_W_CHAIN;
10848     Info.memVT = VT;
10849     Info.ptrVal = I.getArgOperand(0);
10850     Info.offset = 0;
10851     Info.size = VT.getStoreSize();
10852     Info.align = 1;
10853     Info.vol = false;
10854     Info.readMem = true;
10855     Info.writeMem = false;
10856     return true;
10857   }
10858   case Intrinsic::ppc_qpx_qvstfd:
10859   case Intrinsic::ppc_qpx_qvstfs:
10860   case Intrinsic::ppc_qpx_qvstfcd:
10861   case Intrinsic::ppc_qpx_qvstfcs:
10862   case Intrinsic::ppc_qpx_qvstfiw:
10863   case Intrinsic::ppc_altivec_stvx:
10864   case Intrinsic::ppc_altivec_stvxl:
10865   case Intrinsic::ppc_altivec_stvebx:
10866   case Intrinsic::ppc_altivec_stvehx:
10867   case Intrinsic::ppc_altivec_stvewx:
10868   case Intrinsic::ppc_vsx_stxvd2x:
10869   case Intrinsic::ppc_vsx_stxvw4x: {
10870     EVT VT;
10871     switch (Intrinsic) {
10872     case Intrinsic::ppc_altivec_stvebx:
10873       VT = MVT::i8;
10874       break;
10875     case Intrinsic::ppc_altivec_stvehx:
10876       VT = MVT::i16;
10877       break;
10878     case Intrinsic::ppc_altivec_stvewx:
10879       VT = MVT::i32;
10880       break;
10881     case Intrinsic::ppc_vsx_stxvd2x:
10882       VT = MVT::v2f64;
10883       break;
10884     case Intrinsic::ppc_qpx_qvstfd:
10885       VT = MVT::v4f64;
10886       break;
10887     case Intrinsic::ppc_qpx_qvstfs:
10888       VT = MVT::v4f32;
10889       break;
10890     case Intrinsic::ppc_qpx_qvstfcd:
10891       VT = MVT::v2f64;
10892       break;
10893     case Intrinsic::ppc_qpx_qvstfcs:
10894       VT = MVT::v2f32;
10895       break;
10896     default:
10897       VT = MVT::v4i32;
10898       break;
10899     }
10900
10901     Info.opc = ISD::INTRINSIC_VOID;
10902     Info.memVT = VT;
10903     Info.ptrVal = I.getArgOperand(1);
10904     Info.offset = -VT.getStoreSize()+1;
10905     Info.size = 2*VT.getStoreSize()-1;
10906     Info.align = 1;
10907     Info.vol = false;
10908     Info.readMem = false;
10909     Info.writeMem = true;
10910     return true;
10911   }
10912   case Intrinsic::ppc_qpx_qvstfda:
10913   case Intrinsic::ppc_qpx_qvstfsa:
10914   case Intrinsic::ppc_qpx_qvstfcda:
10915   case Intrinsic::ppc_qpx_qvstfcsa:
10916   case Intrinsic::ppc_qpx_qvstfiwa: {
10917     EVT VT;
10918     switch (Intrinsic) {
10919     case Intrinsic::ppc_qpx_qvstfda:
10920       VT = MVT::v4f64;
10921       break;
10922     case Intrinsic::ppc_qpx_qvstfsa:
10923       VT = MVT::v4f32;
10924       break;
10925     case Intrinsic::ppc_qpx_qvstfcda:
10926       VT = MVT::v2f64;
10927       break;
10928     case Intrinsic::ppc_qpx_qvstfcsa:
10929       VT = MVT::v2f32;
10930       break;
10931     default:
10932       VT = MVT::v4i32;
10933       break;
10934     }
10935
10936     Info.opc = ISD::INTRINSIC_VOID;
10937     Info.memVT = VT;
10938     Info.ptrVal = I.getArgOperand(1);
10939     Info.offset = 0;
10940     Info.size = VT.getStoreSize();
10941     Info.align = 1;
10942     Info.vol = false;
10943     Info.readMem = false;
10944     Info.writeMem = true;
10945     return true;
10946   }
10947   default:
10948     break;
10949   }
10950
10951   return false;
10952 }
10953
10954 /// getOptimalMemOpType - Returns the target specific optimal type for load
10955 /// and store operations as a result of memset, memcpy, and memmove
10956 /// lowering. If DstAlign is zero that means it's safe to destination
10957 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
10958 /// means there isn't a need to check it against alignment requirement,
10959 /// probably because the source does not need to be loaded. If 'IsMemset' is
10960 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
10961 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
10962 /// source is constant so it does not need to be loaded.
10963 /// It returns EVT::Other if the type should be determined using generic
10964 /// target-independent logic.
10965 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
10966                                            unsigned DstAlign, unsigned SrcAlign,
10967                                            bool IsMemset, bool ZeroMemset,
10968                                            bool MemcpyStrSrc,
10969                                            MachineFunction &MF) const {
10970   const Function *F = MF.getFunction();
10971   // When expanding a memset, require at least two QPX instructions to cover
10972   // the cost of loading the value to be stored from the constant pool.
10973   if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
10974      (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
10975       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10976     return MVT::v4f64;
10977   }
10978
10979   // We should use Altivec/VSX loads and stores when available. For unaligned
10980   // addresses, unaligned VSX loads are only fast starting with the P8.
10981   if (Subtarget.hasAltivec() && Size >= 16 &&
10982       (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
10983        ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
10984     return MVT::v4i32;
10985
10986   if (Subtarget.isPPC64()) {
10987     return MVT::i64;
10988   }
10989
10990   return MVT::i32;
10991 }
10992
10993 /// \brief Returns true if it is beneficial to convert a load of a constant
10994 /// to just the constant itself.
10995 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10996                                                           Type *Ty) const {
10997   assert(Ty->isIntegerTy());
10998
10999   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11000   if (BitSize == 0 || BitSize > 64)
11001     return false;
11002   return true;
11003 }
11004
11005 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11006   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11007     return false;
11008   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11009   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11010   return NumBits1 == 64 && NumBits2 == 32;
11011 }
11012
11013 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11014   if (!VT1.isInteger() || !VT2.isInteger())
11015     return false;
11016   unsigned NumBits1 = VT1.getSizeInBits();
11017   unsigned NumBits2 = VT2.getSizeInBits();
11018   return NumBits1 == 64 && NumBits2 == 32;
11019 }
11020
11021 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11022   // Generally speaking, zexts are not free, but they are free when they can be
11023   // folded with other operations.
11024   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11025     EVT MemVT = LD->getMemoryVT();
11026     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11027          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11028         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11029          LD->getExtensionType() == ISD::ZEXTLOAD))
11030       return true;
11031   }
11032
11033   // FIXME: Add other cases...
11034   //  - 32-bit shifts with a zext to i64
11035   //  - zext after ctlz, bswap, etc.
11036   //  - zext after and by a constant mask
11037
11038   return TargetLowering::isZExtFree(Val, VT2);
11039 }
11040
11041 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11042   assert(VT.isFloatingPoint());
11043   return true;
11044 }
11045
11046 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11047   return isInt<16>(Imm) || isUInt<16>(Imm);
11048 }
11049
11050 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11051   return isInt<16>(Imm) || isUInt<16>(Imm);
11052 }
11053
11054 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11055                                                        unsigned,
11056                                                        unsigned,
11057                                                        bool *Fast) const {
11058   if (DisablePPCUnaligned)
11059     return false;
11060
11061   // PowerPC supports unaligned memory access for simple non-vector types.
11062   // Although accessing unaligned addresses is not as efficient as accessing
11063   // aligned addresses, it is generally more efficient than manual expansion,
11064   // and generally only traps for software emulation when crossing page
11065   // boundaries.
11066
11067   if (!VT.isSimple())
11068     return false;
11069
11070   if (VT.getSimpleVT().isVector()) {
11071     if (Subtarget.hasVSX()) {
11072       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11073           VT != MVT::v4f32 && VT != MVT::v4i32)
11074         return false;
11075     } else {
11076       return false;
11077     }
11078   }
11079
11080   if (VT == MVT::ppcf128)
11081     return false;
11082
11083   if (Fast)
11084     *Fast = true;
11085
11086   return true;
11087 }
11088
11089 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11090   VT = VT.getScalarType();
11091
11092   if (!VT.isSimple())
11093     return false;
11094
11095   switch (VT.getSimpleVT().SimpleTy) {
11096   case MVT::f32:
11097   case MVT::f64:
11098     return true;
11099   default:
11100     break;
11101   }
11102
11103   return false;
11104 }
11105
11106 const MCPhysReg *
11107 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11108   // LR is a callee-save register, but we must treat it as clobbered by any call
11109   // site. Hence we include LR in the scratch registers, which are in turn added
11110   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11111   // to CTR, which is used by any indirect call.
11112   static const MCPhysReg ScratchRegs[] = {
11113     PPC::X12, PPC::LR8, PPC::CTR8, 0
11114   };
11115
11116   return ScratchRegs;
11117 }
11118
11119 bool
11120 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11121                      EVT VT , unsigned DefinedValues) const {
11122   if (VT == MVT::v2i64)
11123     return false;
11124
11125   if (Subtarget.hasQPX()) {
11126     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11127       return true;
11128   }
11129
11130   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11131 }
11132
11133 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11134   if (DisableILPPref || Subtarget.enableMachineScheduler())
11135     return TargetLowering::getSchedulingPreference(N);
11136
11137   return Sched::ILP;
11138 }
11139
11140 // Create a fast isel object.
11141 FastISel *
11142 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11143                                   const TargetLibraryInfo *LibInfo) const {
11144   return PPC::createFastISel(FuncInfo, LibInfo);
11145 }