Add support for part-word atomics for PPC
[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::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1006   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1007   case PPCISD::BDZ:             return "PPCISD::BDZ";
1008   case PPCISD::MFFS:            return "PPCISD::MFFS";
1009   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1010   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1011   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1012   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1013   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1014   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1015   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1016   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1017   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1018   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1019   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1020   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1021   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1022   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1023   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1024   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1025   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1026   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1027   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1028   case PPCISD::SC:              return "PPCISD::SC";
1029   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1030   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1031   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1032   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1033   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1034   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1035   }
1036 }
1037
1038 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1039   if (!VT.isVector())
1040     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1041
1042   if (Subtarget.hasQPX())
1043     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1044
1045   return VT.changeVectorElementTypeToInteger();
1046 }
1047
1048 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1049   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1050   return true;
1051 }
1052
1053 //===----------------------------------------------------------------------===//
1054 // Node matching predicates, for use by the tblgen matching code.
1055 //===----------------------------------------------------------------------===//
1056
1057 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1058 static bool isFloatingPointZero(SDValue Op) {
1059   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1060     return CFP->getValueAPF().isZero();
1061   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1062     // Maybe this has already been legalized into the constant pool?
1063     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1064       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1065         return CFP->getValueAPF().isZero();
1066   }
1067   return false;
1068 }
1069
1070 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1071 /// true if Op is undef or if it matches the specified value.
1072 static bool isConstantOrUndef(int Op, int Val) {
1073   return Op < 0 || Op == Val;
1074 }
1075
1076 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1077 /// VPKUHUM instruction.
1078 /// The ShuffleKind distinguishes between big-endian operations with
1079 /// two different inputs (0), either-endian operations with two identical
1080 /// inputs (1), and little-endian operantion with two different inputs (2).
1081 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1082 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1083                                SelectionDAG &DAG) {
1084   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1085   if (ShuffleKind == 0) {
1086     if (IsLE)
1087       return false;
1088     for (unsigned i = 0; i != 16; ++i)
1089       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1090         return false;
1091   } else if (ShuffleKind == 2) {
1092     if (!IsLE)
1093       return false;
1094     for (unsigned i = 0; i != 16; ++i)
1095       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1096         return false;
1097   } else if (ShuffleKind == 1) {
1098     unsigned j = IsLE ? 0 : 1;
1099     for (unsigned i = 0; i != 8; ++i)
1100       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1101           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1102         return false;
1103   }
1104   return true;
1105 }
1106
1107 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1108 /// VPKUWUM instruction.
1109 /// The ShuffleKind distinguishes between big-endian operations with
1110 /// two different inputs (0), either-endian operations with two identical
1111 /// inputs (1), and little-endian operantion with two different inputs (2).
1112 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1113 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1114                                SelectionDAG &DAG) {
1115   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1116   if (ShuffleKind == 0) {
1117     if (IsLE)
1118       return false;
1119     for (unsigned i = 0; i != 16; i += 2)
1120       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1121           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1122         return false;
1123   } else if (ShuffleKind == 2) {
1124     if (!IsLE)
1125       return false;
1126     for (unsigned i = 0; i != 16; i += 2)
1127       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1128           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1129         return false;
1130   } else if (ShuffleKind == 1) {
1131     unsigned j = IsLE ? 0 : 2;
1132     for (unsigned i = 0; i != 8; i += 2)
1133       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1134           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1135           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1136           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1137         return false;
1138   }
1139   return true;
1140 }
1141
1142 /// isVMerge - Common function, used to match vmrg* shuffles.
1143 ///
1144 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1145                      unsigned LHSStart, unsigned RHSStart) {
1146   if (N->getValueType(0) != MVT::v16i8)
1147     return false;
1148   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1149          "Unsupported merge size!");
1150
1151   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1152     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1153       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1154                              LHSStart+j+i*UnitSize) ||
1155           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1156                              RHSStart+j+i*UnitSize))
1157         return false;
1158     }
1159   return true;
1160 }
1161
1162 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1163 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1164 /// The ShuffleKind distinguishes between big-endian merges with two 
1165 /// different inputs (0), either-endian merges with two identical inputs (1),
1166 /// and little-endian merges with two different inputs (2).  For the latter,
1167 /// the input operands are swapped (see PPCInstrAltivec.td).
1168 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1169                              unsigned ShuffleKind, SelectionDAG &DAG) {
1170   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1171     if (ShuffleKind == 1) // unary
1172       return isVMerge(N, UnitSize, 0, 0);
1173     else if (ShuffleKind == 2) // swapped
1174       return isVMerge(N, UnitSize, 0, 16);
1175     else
1176       return false;
1177   } else {
1178     if (ShuffleKind == 1) // unary
1179       return isVMerge(N, UnitSize, 8, 8);
1180     else if (ShuffleKind == 0) // normal
1181       return isVMerge(N, UnitSize, 8, 24);
1182     else
1183       return false;
1184   }
1185 }
1186
1187 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1188 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1189 /// The ShuffleKind distinguishes between big-endian merges with two 
1190 /// different inputs (0), either-endian merges with two identical inputs (1),
1191 /// and little-endian merges with two different inputs (2).  For the latter,
1192 /// the input operands are swapped (see PPCInstrAltivec.td).
1193 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1194                              unsigned ShuffleKind, SelectionDAG &DAG) {
1195   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1196     if (ShuffleKind == 1) // unary
1197       return isVMerge(N, UnitSize, 8, 8);
1198     else if (ShuffleKind == 2) // swapped
1199       return isVMerge(N, UnitSize, 8, 24);
1200     else
1201       return false;
1202   } else {
1203     if (ShuffleKind == 1) // unary
1204       return isVMerge(N, UnitSize, 0, 0);
1205     else if (ShuffleKind == 0) // normal
1206       return isVMerge(N, UnitSize, 0, 16);
1207     else
1208       return false;
1209   }
1210 }
1211
1212
1213 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1214 /// amount, otherwise return -1.
1215 /// The ShuffleKind distinguishes between big-endian operations with two 
1216 /// different inputs (0), either-endian operations with two identical inputs
1217 /// (1), and little-endian operations with two different inputs (2).  For the
1218 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1219 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1220                              SelectionDAG &DAG) {
1221   if (N->getValueType(0) != MVT::v16i8)
1222     return -1;
1223
1224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1225
1226   // Find the first non-undef value in the shuffle mask.
1227   unsigned i;
1228   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1229     /*search*/;
1230
1231   if (i == 16) return -1;  // all undef.
1232
1233   // Otherwise, check to see if the rest of the elements are consecutively
1234   // numbered from this value.
1235   unsigned ShiftAmt = SVOp->getMaskElt(i);
1236   if (ShiftAmt < i) return -1;
1237
1238   ShiftAmt -= i;
1239   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1240
1241   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1242     // Check the rest of the elements to see if they are consecutive.
1243     for (++i; i != 16; ++i)
1244       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1245         return -1;
1246   } else if (ShuffleKind == 1) {
1247     // Check the rest of the elements to see if they are consecutive.
1248     for (++i; i != 16; ++i)
1249       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1250         return -1;
1251   } else
1252     return -1;
1253
1254   if (ShuffleKind == 2 && isLE)
1255     ShiftAmt = 16 - ShiftAmt;
1256
1257   return ShiftAmt;
1258 }
1259
1260 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1261 /// specifies a splat of a single element that is suitable for input to
1262 /// VSPLTB/VSPLTH/VSPLTW.
1263 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1264   assert(N->getValueType(0) == MVT::v16i8 &&
1265          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1266
1267   // This is a splat operation if each element of the permute is the same, and
1268   // if the value doesn't reference the second vector.
1269   unsigned ElementBase = N->getMaskElt(0);
1270
1271   // FIXME: Handle UNDEF elements too!
1272   if (ElementBase >= 16)
1273     return false;
1274
1275   // Check that the indices are consecutive, in the case of a multi-byte element
1276   // splatted with a v16i8 mask.
1277   for (unsigned i = 1; i != EltSize; ++i)
1278     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1279       return false;
1280
1281   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1282     if (N->getMaskElt(i) < 0) continue;
1283     for (unsigned j = 0; j != EltSize; ++j)
1284       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1285         return false;
1286   }
1287   return true;
1288 }
1289
1290 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1291 /// are -0.0.
1292 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1293   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1294
1295   APInt APVal, APUndef;
1296   unsigned BitSize;
1297   bool HasAnyUndefs;
1298
1299   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1300     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1301       return CFP->getValueAPF().isNegZero();
1302
1303   return false;
1304 }
1305
1306 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1307 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1308 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1309                                 SelectionDAG &DAG) {
1310   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1311   assert(isSplatShuffleMask(SVOp, EltSize));
1312   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1313     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1314   else
1315     return SVOp->getMaskElt(0) / EltSize;
1316 }
1317
1318 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1319 /// by using a vspltis[bhw] instruction of the specified element size, return
1320 /// the constant being splatted.  The ByteSize field indicates the number of
1321 /// bytes of each element [124] -> [bhw].
1322 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1323   SDValue OpVal(nullptr, 0);
1324
1325   // If ByteSize of the splat is bigger than the element size of the
1326   // build_vector, then we have a case where we are checking for a splat where
1327   // multiple elements of the buildvector are folded together into a single
1328   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1329   unsigned EltSize = 16/N->getNumOperands();
1330   if (EltSize < ByteSize) {
1331     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1332     SDValue UniquedVals[4];
1333     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1334
1335     // See if all of the elements in the buildvector agree across.
1336     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1337       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1338       // If the element isn't a constant, bail fully out.
1339       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1340
1341
1342       if (!UniquedVals[i&(Multiple-1)].getNode())
1343         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1344       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1345         return SDValue();  // no match.
1346     }
1347
1348     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1349     // either constant or undef values that are identical for each chunk.  See
1350     // if these chunks can form into a larger vspltis*.
1351
1352     // Check to see if all of the leading entries are either 0 or -1.  If
1353     // neither, then this won't fit into the immediate field.
1354     bool LeadingZero = true;
1355     bool LeadingOnes = true;
1356     for (unsigned i = 0; i != Multiple-1; ++i) {
1357       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1358
1359       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1360       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1361     }
1362     // Finally, check the least significant entry.
1363     if (LeadingZero) {
1364       if (!UniquedVals[Multiple-1].getNode())
1365         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1366       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1367       if (Val < 16)
1368         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1369     }
1370     if (LeadingOnes) {
1371       if (!UniquedVals[Multiple-1].getNode())
1372         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1373       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1374       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1375         return DAG.getTargetConstant(Val, MVT::i32);
1376     }
1377
1378     return SDValue();
1379   }
1380
1381   // Check to see if this buildvec has a single non-undef value in its elements.
1382   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1383     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1384     if (!OpVal.getNode())
1385       OpVal = N->getOperand(i);
1386     else if (OpVal != N->getOperand(i))
1387       return SDValue();
1388   }
1389
1390   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1391
1392   unsigned ValSizeInBytes = EltSize;
1393   uint64_t Value = 0;
1394   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1395     Value = CN->getZExtValue();
1396   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1397     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1398     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1399   }
1400
1401   // If the splat value is larger than the element value, then we can never do
1402   // this splat.  The only case that we could fit the replicated bits into our
1403   // immediate field for would be zero, and we prefer to use vxor for it.
1404   if (ValSizeInBytes < ByteSize) return SDValue();
1405
1406   // If the element value is larger than the splat value, cut it in half and
1407   // check to see if the two halves are equal.  Continue doing this until we
1408   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1409   while (ValSizeInBytes > ByteSize) {
1410     ValSizeInBytes >>= 1;
1411
1412     // If the top half equals the bottom half, we're still ok.
1413     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1414          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1415       return SDValue();
1416   }
1417
1418   // Properly sign extend the value.
1419   int MaskVal = SignExtend32(Value, ByteSize * 8);
1420
1421   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1422   if (MaskVal == 0) return SDValue();
1423
1424   // Finally, if this value fits in a 5 bit sext field, return it
1425   if (SignExtend32<5>(MaskVal) == MaskVal)
1426     return DAG.getTargetConstant(MaskVal, MVT::i32);
1427   return SDValue();
1428 }
1429
1430 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1431 /// amount, otherwise return -1.
1432 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1433   EVT VT = N->getValueType(0);
1434   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1435     return -1;
1436
1437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1438
1439   // Find the first non-undef value in the shuffle mask.
1440   unsigned i;
1441   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1442     /*search*/;
1443
1444   if (i == 4) return -1;  // all undef.
1445
1446   // Otherwise, check to see if the rest of the elements are consecutively
1447   // numbered from this value.
1448   unsigned ShiftAmt = SVOp->getMaskElt(i);
1449   if (ShiftAmt < i) return -1;
1450   ShiftAmt -= i;
1451
1452   // Check the rest of the elements to see if they are consecutive.
1453   for (++i; i != 4; ++i)
1454     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1455       return -1;
1456
1457   return ShiftAmt;
1458 }
1459
1460 //===----------------------------------------------------------------------===//
1461 //  Addressing Mode Selection
1462 //===----------------------------------------------------------------------===//
1463
1464 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1465 /// or 64-bit immediate, and if the value can be accurately represented as a
1466 /// sign extension from a 16-bit value.  If so, this returns true and the
1467 /// immediate.
1468 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1469   if (!isa<ConstantSDNode>(N))
1470     return false;
1471
1472   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1473   if (N->getValueType(0) == MVT::i32)
1474     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1475   else
1476     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1477 }
1478 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1479   return isIntS16Immediate(Op.getNode(), Imm);
1480 }
1481
1482
1483 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1484 /// can be represented as an indexed [r+r] operation.  Returns false if it
1485 /// can be more efficiently represented with [r+imm].
1486 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1487                                             SDValue &Index,
1488                                             SelectionDAG &DAG) const {
1489   short imm = 0;
1490   if (N.getOpcode() == ISD::ADD) {
1491     if (isIntS16Immediate(N.getOperand(1), imm))
1492       return false;    // r+i
1493     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1494       return false;    // r+i
1495
1496     Base = N.getOperand(0);
1497     Index = N.getOperand(1);
1498     return true;
1499   } else if (N.getOpcode() == ISD::OR) {
1500     if (isIntS16Immediate(N.getOperand(1), imm))
1501       return false;    // r+i can fold it if we can.
1502
1503     // If this is an or of disjoint bitfields, we can codegen this as an add
1504     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1505     // disjoint.
1506     APInt LHSKnownZero, LHSKnownOne;
1507     APInt RHSKnownZero, RHSKnownOne;
1508     DAG.computeKnownBits(N.getOperand(0),
1509                          LHSKnownZero, LHSKnownOne);
1510
1511     if (LHSKnownZero.getBoolValue()) {
1512       DAG.computeKnownBits(N.getOperand(1),
1513                            RHSKnownZero, RHSKnownOne);
1514       // If all of the bits are known zero on the LHS or RHS, the add won't
1515       // carry.
1516       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1517         Base = N.getOperand(0);
1518         Index = N.getOperand(1);
1519         return true;
1520       }
1521     }
1522   }
1523
1524   return false;
1525 }
1526
1527 // If we happen to be doing an i64 load or store into a stack slot that has
1528 // less than a 4-byte alignment, then the frame-index elimination may need to
1529 // use an indexed load or store instruction (because the offset may not be a
1530 // multiple of 4). The extra register needed to hold the offset comes from the
1531 // register scavenger, and it is possible that the scavenger will need to use
1532 // an emergency spill slot. As a result, we need to make sure that a spill slot
1533 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1534 // stack slot.
1535 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1536   // FIXME: This does not handle the LWA case.
1537   if (VT != MVT::i64)
1538     return;
1539
1540   // NOTE: We'll exclude negative FIs here, which come from argument
1541   // lowering, because there are no known test cases triggering this problem
1542   // using packed structures (or similar). We can remove this exclusion if
1543   // we find such a test case. The reason why this is so test-case driven is
1544   // because this entire 'fixup' is only to prevent crashes (from the
1545   // register scavenger) on not-really-valid inputs. For example, if we have:
1546   //   %a = alloca i1
1547   //   %b = bitcast i1* %a to i64*
1548   //   store i64* a, i64 b
1549   // then the store should really be marked as 'align 1', but is not. If it
1550   // were marked as 'align 1' then the indexed form would have been
1551   // instruction-selected initially, and the problem this 'fixup' is preventing
1552   // won't happen regardless.
1553   if (FrameIdx < 0)
1554     return;
1555
1556   MachineFunction &MF = DAG.getMachineFunction();
1557   MachineFrameInfo *MFI = MF.getFrameInfo();
1558
1559   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1560   if (Align >= 4)
1561     return;
1562
1563   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1564   FuncInfo->setHasNonRISpills();
1565 }
1566
1567 /// Returns true if the address N can be represented by a base register plus
1568 /// a signed 16-bit displacement [r+imm], and if it is not better
1569 /// represented as reg+reg.  If Aligned is true, only accept displacements
1570 /// suitable for STD and friends, i.e. multiples of 4.
1571 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1572                                             SDValue &Base,
1573                                             SelectionDAG &DAG,
1574                                             bool Aligned) const {
1575   // FIXME dl should come from parent load or store, not from address
1576   SDLoc dl(N);
1577   // If this can be more profitably realized as r+r, fail.
1578   if (SelectAddressRegReg(N, Disp, Base, DAG))
1579     return false;
1580
1581   if (N.getOpcode() == ISD::ADD) {
1582     short imm = 0;
1583     if (isIntS16Immediate(N.getOperand(1), imm) &&
1584         (!Aligned || (imm & 3) == 0)) {
1585       Disp = DAG.getTargetConstant(imm, N.getValueType());
1586       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1587         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1588         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1589       } else {
1590         Base = N.getOperand(0);
1591       }
1592       return true; // [r+i]
1593     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1594       // Match LOAD (ADD (X, Lo(G))).
1595       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1596              && "Cannot handle constant offsets yet!");
1597       Disp = N.getOperand(1).getOperand(0);  // The global address.
1598       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1599              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1600              Disp.getOpcode() == ISD::TargetConstantPool ||
1601              Disp.getOpcode() == ISD::TargetJumpTable);
1602       Base = N.getOperand(0);
1603       return true;  // [&g+r]
1604     }
1605   } else if (N.getOpcode() == ISD::OR) {
1606     short imm = 0;
1607     if (isIntS16Immediate(N.getOperand(1), imm) &&
1608         (!Aligned || (imm & 3) == 0)) {
1609       // If this is an or of disjoint bitfields, we can codegen this as an add
1610       // (for better address arithmetic) if the LHS and RHS of the OR are
1611       // provably disjoint.
1612       APInt LHSKnownZero, LHSKnownOne;
1613       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1614
1615       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1616         // If all of the bits are known zero on the LHS or RHS, the add won't
1617         // carry.
1618         if (FrameIndexSDNode *FI =
1619               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1620           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1621           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1622         } else {
1623           Base = N.getOperand(0);
1624         }
1625         Disp = DAG.getTargetConstant(imm, N.getValueType());
1626         return true;
1627       }
1628     }
1629   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1630     // Loading from a constant address.
1631
1632     // If this address fits entirely in a 16-bit sext immediate field, codegen
1633     // this as "d, 0"
1634     short Imm;
1635     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1636       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1637       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1638                              CN->getValueType(0));
1639       return true;
1640     }
1641
1642     // Handle 32-bit sext immediates with LIS + addr mode.
1643     if ((CN->getValueType(0) == MVT::i32 ||
1644          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1645         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1646       int Addr = (int)CN->getZExtValue();
1647
1648       // Otherwise, break this down into an LIS + disp.
1649       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1650
1651       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1652       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1653       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1654       return true;
1655     }
1656   }
1657
1658   Disp = DAG.getTargetConstant(0, getPointerTy());
1659   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1660     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1661     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1662   } else
1663     Base = N;
1664   return true;      // [r+0]
1665 }
1666
1667 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1668 /// represented as an indexed [r+r] operation.
1669 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1670                                                 SDValue &Index,
1671                                                 SelectionDAG &DAG) const {
1672   // Check to see if we can easily represent this as an [r+r] address.  This
1673   // will fail if it thinks that the address is more profitably represented as
1674   // reg+imm, e.g. where imm = 0.
1675   if (SelectAddressRegReg(N, Base, Index, DAG))
1676     return true;
1677
1678   // If the operand is an addition, always emit this as [r+r], since this is
1679   // better (for code size, and execution, as the memop does the add for free)
1680   // than emitting an explicit add.
1681   if (N.getOpcode() == ISD::ADD) {
1682     Base = N.getOperand(0);
1683     Index = N.getOperand(1);
1684     return true;
1685   }
1686
1687   // Otherwise, do it the hard way, using R0 as the base register.
1688   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1689                          N.getValueType());
1690   Index = N;
1691   return true;
1692 }
1693
1694 /// getPreIndexedAddressParts - returns true by value, base pointer and
1695 /// offset pointer and addressing mode by reference if the node's address
1696 /// can be legally represented as pre-indexed load / store address.
1697 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1698                                                   SDValue &Offset,
1699                                                   ISD::MemIndexedMode &AM,
1700                                                   SelectionDAG &DAG) const {
1701   if (DisablePPCPreinc) return false;
1702
1703   bool isLoad = true;
1704   SDValue Ptr;
1705   EVT VT;
1706   unsigned Alignment;
1707   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1708     Ptr = LD->getBasePtr();
1709     VT = LD->getMemoryVT();
1710     Alignment = LD->getAlignment();
1711   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1712     Ptr = ST->getBasePtr();
1713     VT  = ST->getMemoryVT();
1714     Alignment = ST->getAlignment();
1715     isLoad = false;
1716   } else
1717     return false;
1718
1719   // PowerPC doesn't have preinc load/store instructions for vectors (except
1720   // for QPX, which does have preinc r+r forms).
1721   if (VT.isVector()) {
1722     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1723       return false;
1724     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1725       AM = ISD::PRE_INC;
1726       return true;
1727     }
1728   }
1729
1730   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1731
1732     // Common code will reject creating a pre-inc form if the base pointer
1733     // is a frame index, or if N is a store and the base pointer is either
1734     // the same as or a predecessor of the value being stored.  Check for
1735     // those situations here, and try with swapped Base/Offset instead.
1736     bool Swap = false;
1737
1738     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1739       Swap = true;
1740     else if (!isLoad) {
1741       SDValue Val = cast<StoreSDNode>(N)->getValue();
1742       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1743         Swap = true;
1744     }
1745
1746     if (Swap)
1747       std::swap(Base, Offset);
1748
1749     AM = ISD::PRE_INC;
1750     return true;
1751   }
1752
1753   // LDU/STU can only handle immediates that are a multiple of 4.
1754   if (VT != MVT::i64) {
1755     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1756       return false;
1757   } else {
1758     // LDU/STU need an address with at least 4-byte alignment.
1759     if (Alignment < 4)
1760       return false;
1761
1762     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1763       return false;
1764   }
1765
1766   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1767     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1768     // sext i32 to i64 when addr mode is r+i.
1769     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1770         LD->getExtensionType() == ISD::SEXTLOAD &&
1771         isa<ConstantSDNode>(Offset))
1772       return false;
1773   }
1774
1775   AM = ISD::PRE_INC;
1776   return true;
1777 }
1778
1779 //===----------------------------------------------------------------------===//
1780 //  LowerOperation implementation
1781 //===----------------------------------------------------------------------===//
1782
1783 /// GetLabelAccessInfo - Return true if we should reference labels using a
1784 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1785 static bool GetLabelAccessInfo(const TargetMachine &TM,
1786                                const PPCSubtarget &Subtarget,
1787                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1788                                const GlobalValue *GV = nullptr) {
1789   HiOpFlags = PPCII::MO_HA;
1790   LoOpFlags = PPCII::MO_LO;
1791
1792   // Don't use the pic base if not in PIC relocation model.
1793   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1794
1795   if (isPIC) {
1796     HiOpFlags |= PPCII::MO_PIC_FLAG;
1797     LoOpFlags |= PPCII::MO_PIC_FLAG;
1798   }
1799
1800   // If this is a reference to a global value that requires a non-lazy-ptr, make
1801   // sure that instruction lowering adds it.
1802   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1803     HiOpFlags |= PPCII::MO_NLP_FLAG;
1804     LoOpFlags |= PPCII::MO_NLP_FLAG;
1805
1806     if (GV->hasHiddenVisibility()) {
1807       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1808       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1809     }
1810   }
1811
1812   return isPIC;
1813 }
1814
1815 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1816                              SelectionDAG &DAG) {
1817   EVT PtrVT = HiPart.getValueType();
1818   SDValue Zero = DAG.getConstant(0, PtrVT);
1819   SDLoc DL(HiPart);
1820
1821   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1822   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1823
1824   // With PIC, the first instruction is actually "GR+hi(&G)".
1825   if (isPIC)
1826     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1827                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1828
1829   // Generate non-pic code that has direct accesses to the constant pool.
1830   // The address of the global is just (hi(&g)+lo(&g)).
1831   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1832 }
1833
1834 static void setUsesTOCBasePtr(MachineFunction &MF) {
1835   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1836   FuncInfo->setUsesTOCBasePtr();
1837 }
1838
1839 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1840   setUsesTOCBasePtr(DAG.getMachineFunction());
1841 }
1842
1843 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1844                            SDValue GA) {
1845   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1846   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1847                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1848
1849   SDValue Ops[] = { GA, Reg };
1850   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1851                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1852                                  MachinePointerInfo::getGOT(), 0, false, true,
1853                                  false, 0);
1854 }
1855
1856 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1857                                              SelectionDAG &DAG) const {
1858   EVT PtrVT = Op.getValueType();
1859   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1860   const Constant *C = CP->getConstVal();
1861
1862   // 64-bit SVR4 ABI code is always position-independent.
1863   // The actual address of the GlobalValue is stored in the TOC.
1864   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1865     setUsesTOCBasePtr(DAG);
1866     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1867     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1868   }
1869
1870   unsigned MOHiFlag, MOLoFlag;
1871   bool isPIC =
1872       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1873
1874   if (isPIC && Subtarget.isSVR4ABI()) {
1875     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1876                                            PPCII::MO_PIC_FLAG);
1877     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1878   }
1879
1880   SDValue CPIHi =
1881     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1882   SDValue CPILo =
1883     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1884   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1885 }
1886
1887 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1888   EVT PtrVT = Op.getValueType();
1889   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1890
1891   // 64-bit SVR4 ABI code is always position-independent.
1892   // The actual address of the GlobalValue is stored in the TOC.
1893   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1894     setUsesTOCBasePtr(DAG);
1895     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1896     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1897   }
1898
1899   unsigned MOHiFlag, MOLoFlag;
1900   bool isPIC =
1901       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1902
1903   if (isPIC && Subtarget.isSVR4ABI()) {
1904     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1905                                         PPCII::MO_PIC_FLAG);
1906     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1907   }
1908
1909   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1910   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1911   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1912 }
1913
1914 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1915                                              SelectionDAG &DAG) const {
1916   EVT PtrVT = Op.getValueType();
1917   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1918   const BlockAddress *BA = BASDN->getBlockAddress();
1919
1920   // 64-bit SVR4 ABI code is always position-independent.
1921   // The actual BlockAddress is stored in the TOC.
1922   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1923     setUsesTOCBasePtr(DAG);
1924     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1925     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1926   }
1927
1928   unsigned MOHiFlag, MOLoFlag;
1929   bool isPIC =
1930       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1931   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1932   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1933   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1934 }
1935
1936 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1937                                               SelectionDAG &DAG) const {
1938
1939   // FIXME: TLS addresses currently use medium model code sequences,
1940   // which is the most useful form.  Eventually support for small and
1941   // large models could be added if users need it, at the cost of
1942   // additional complexity.
1943   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1944   SDLoc dl(GA);
1945   const GlobalValue *GV = GA->getGlobal();
1946   EVT PtrVT = getPointerTy();
1947   bool is64bit = Subtarget.isPPC64();
1948   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1949   PICLevel::Level picLevel = M->getPICLevel();
1950
1951   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1952
1953   if (Model == TLSModel::LocalExec) {
1954     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1955                                                PPCII::MO_TPREL_HA);
1956     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1957                                                PPCII::MO_TPREL_LO);
1958     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1959                                      is64bit ? MVT::i64 : MVT::i32);
1960     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1961     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1962   }
1963
1964   if (Model == TLSModel::InitialExec) {
1965     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1966     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1967                                                 PPCII::MO_TLS);
1968     SDValue GOTPtr;
1969     if (is64bit) {
1970       setUsesTOCBasePtr(DAG);
1971       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1972       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1973                            PtrVT, GOTReg, TGA);
1974     } else
1975       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1976     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1977                                    PtrVT, TGA, GOTPtr);
1978     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1979   }
1980
1981   if (Model == TLSModel::GeneralDynamic) {
1982     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1983     SDValue GOTPtr;
1984     if (is64bit) {
1985       setUsesTOCBasePtr(DAG);
1986       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1987       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1988                                    GOTReg, TGA);
1989     } else {
1990       if (picLevel == PICLevel::Small)
1991         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1992       else
1993         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1994     }
1995     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1996                        GOTPtr, TGA, TGA);
1997   }
1998
1999   if (Model == TLSModel::LocalDynamic) {
2000     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2001     SDValue GOTPtr;
2002     if (is64bit) {
2003       setUsesTOCBasePtr(DAG);
2004       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2005       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2006                            GOTReg, TGA);
2007     } else {
2008       if (picLevel == PICLevel::Small)
2009         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2010       else
2011         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2012     }
2013     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2014                                   PtrVT, GOTPtr, TGA, TGA);
2015     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2016                                       PtrVT, TLSAddr, TGA);
2017     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2018   }
2019
2020   llvm_unreachable("Unknown TLS model!");
2021 }
2022
2023 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2024                                               SelectionDAG &DAG) const {
2025   EVT PtrVT = Op.getValueType();
2026   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2027   SDLoc DL(GSDN);
2028   const GlobalValue *GV = GSDN->getGlobal();
2029
2030   // 64-bit SVR4 ABI code is always position-independent.
2031   // The actual address of the GlobalValue is stored in the TOC.
2032   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2033     setUsesTOCBasePtr(DAG);
2034     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2035     return getTOCEntry(DAG, DL, true, GA);
2036   }
2037
2038   unsigned MOHiFlag, MOLoFlag;
2039   bool isPIC =
2040       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2041
2042   if (isPIC && Subtarget.isSVR4ABI()) {
2043     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2044                                             GSDN->getOffset(),
2045                                             PPCII::MO_PIC_FLAG);
2046     return getTOCEntry(DAG, DL, false, GA);
2047   }
2048
2049   SDValue GAHi =
2050     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2051   SDValue GALo =
2052     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2053
2054   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2055
2056   // If the global reference is actually to a non-lazy-pointer, we have to do an
2057   // extra load to get the address of the global.
2058   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2059     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2060                       false, false, false, 0);
2061   return Ptr;
2062 }
2063
2064 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2065   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2066   SDLoc dl(Op);
2067
2068   if (Op.getValueType() == MVT::v2i64) {
2069     // When the operands themselves are v2i64 values, we need to do something
2070     // special because VSX has no underlying comparison operations for these.
2071     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2072       // Equality can be handled by casting to the legal type for Altivec
2073       // comparisons, everything else needs to be expanded.
2074       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2075         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2076                  DAG.getSetCC(dl, MVT::v4i32,
2077                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2078                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2079                    CC));
2080       }
2081
2082       return SDValue();
2083     }
2084
2085     // We handle most of these in the usual way.
2086     return Op;
2087   }
2088
2089   // If we're comparing for equality to zero, expose the fact that this is
2090   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2091   // fold the new nodes.
2092   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2093     if (C->isNullValue() && CC == ISD::SETEQ) {
2094       EVT VT = Op.getOperand(0).getValueType();
2095       SDValue Zext = Op.getOperand(0);
2096       if (VT.bitsLT(MVT::i32)) {
2097         VT = MVT::i32;
2098         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2099       }
2100       unsigned Log2b = Log2_32(VT.getSizeInBits());
2101       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2102       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2103                                 DAG.getConstant(Log2b, MVT::i32));
2104       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2105     }
2106     // Leave comparisons against 0 and -1 alone for now, since they're usually
2107     // optimized.  FIXME: revisit this when we can custom lower all setcc
2108     // optimizations.
2109     if (C->isAllOnesValue() || C->isNullValue())
2110       return SDValue();
2111   }
2112
2113   // If we have an integer seteq/setne, turn it into a compare against zero
2114   // by xor'ing the rhs with the lhs, which is faster than setting a
2115   // condition register, reading it back out, and masking the correct bit.  The
2116   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2117   // the result to other bit-twiddling opportunities.
2118   EVT LHSVT = Op.getOperand(0).getValueType();
2119   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2120     EVT VT = Op.getValueType();
2121     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2122                                 Op.getOperand(1));
2123     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2124   }
2125   return SDValue();
2126 }
2127
2128 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2129                                       const PPCSubtarget &Subtarget) const {
2130   SDNode *Node = Op.getNode();
2131   EVT VT = Node->getValueType(0);
2132   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2133   SDValue InChain = Node->getOperand(0);
2134   SDValue VAListPtr = Node->getOperand(1);
2135   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2136   SDLoc dl(Node);
2137
2138   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2139
2140   // gpr_index
2141   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2142                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2143                                     false, false, false, 0);
2144   InChain = GprIndex.getValue(1);
2145
2146   if (VT == MVT::i64) {
2147     // Check if GprIndex is even
2148     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2149                                  DAG.getConstant(1, MVT::i32));
2150     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2151                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2152     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2153                                           DAG.getConstant(1, MVT::i32));
2154     // Align GprIndex to be even if it isn't
2155     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2156                            GprIndex);
2157   }
2158
2159   // fpr index is 1 byte after gpr
2160   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2161                                DAG.getConstant(1, MVT::i32));
2162
2163   // fpr
2164   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2165                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2166                                     false, false, false, 0);
2167   InChain = FprIndex.getValue(1);
2168
2169   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2170                                        DAG.getConstant(8, MVT::i32));
2171
2172   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2173                                         DAG.getConstant(4, MVT::i32));
2174
2175   // areas
2176   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2177                                      MachinePointerInfo(), false, false,
2178                                      false, 0);
2179   InChain = OverflowArea.getValue(1);
2180
2181   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2182                                     MachinePointerInfo(), false, false,
2183                                     false, 0);
2184   InChain = RegSaveArea.getValue(1);
2185
2186   // select overflow_area if index > 8
2187   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2188                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
2189
2190   // adjustment constant gpr_index * 4/8
2191   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2192                                     VT.isInteger() ? GprIndex : FprIndex,
2193                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
2194                                                     MVT::i32));
2195
2196   // OurReg = RegSaveArea + RegConstant
2197   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2198                                RegConstant);
2199
2200   // Floating types are 32 bytes into RegSaveArea
2201   if (VT.isFloatingPoint())
2202     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2203                          DAG.getConstant(32, MVT::i32));
2204
2205   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2206   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2207                                    VT.isInteger() ? GprIndex : FprIndex,
2208                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2209                                                    MVT::i32));
2210
2211   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2212                               VT.isInteger() ? VAListPtr : FprPtr,
2213                               MachinePointerInfo(SV),
2214                               MVT::i8, false, false, 0);
2215
2216   // determine if we should load from reg_save_area or overflow_area
2217   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2218
2219   // increase overflow_area by 4/8 if gpr/fpr > 8
2220   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2221                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2222                                           MVT::i32));
2223
2224   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2225                              OverflowAreaPlusN);
2226
2227   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2228                               OverflowAreaPtr,
2229                               MachinePointerInfo(),
2230                               MVT::i32, false, false, 0);
2231
2232   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2233                      false, false, false, 0);
2234 }
2235
2236 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2237                                        const PPCSubtarget &Subtarget) const {
2238   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2239
2240   // We have to copy the entire va_list struct:
2241   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2242   return DAG.getMemcpy(Op.getOperand(0), Op,
2243                        Op.getOperand(1), Op.getOperand(2),
2244                        DAG.getConstant(12, MVT::i32), 8, false, true,
2245                        MachinePointerInfo(), MachinePointerInfo());
2246 }
2247
2248 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2249                                                   SelectionDAG &DAG) const {
2250   return Op.getOperand(0);
2251 }
2252
2253 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2254                                                 SelectionDAG &DAG) const {
2255   SDValue Chain = Op.getOperand(0);
2256   SDValue Trmp = Op.getOperand(1); // trampoline
2257   SDValue FPtr = Op.getOperand(2); // nested function
2258   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2259   SDLoc dl(Op);
2260
2261   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2262   bool isPPC64 = (PtrVT == MVT::i64);
2263   Type *IntPtrTy =
2264     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2265                                                              *DAG.getContext());
2266
2267   TargetLowering::ArgListTy Args;
2268   TargetLowering::ArgListEntry Entry;
2269
2270   Entry.Ty = IntPtrTy;
2271   Entry.Node = Trmp; Args.push_back(Entry);
2272
2273   // TrampSize == (isPPC64 ? 48 : 40);
2274   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2275                                isPPC64 ? MVT::i64 : MVT::i32);
2276   Args.push_back(Entry);
2277
2278   Entry.Node = FPtr; Args.push_back(Entry);
2279   Entry.Node = Nest; Args.push_back(Entry);
2280
2281   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2282   TargetLowering::CallLoweringInfo CLI(DAG);
2283   CLI.setDebugLoc(dl).setChain(Chain)
2284     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2285                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2286                std::move(Args), 0);
2287
2288   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2289   return CallResult.second;
2290 }
2291
2292 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2293                                         const PPCSubtarget &Subtarget) const {
2294   MachineFunction &MF = DAG.getMachineFunction();
2295   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2296
2297   SDLoc dl(Op);
2298
2299   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2300     // vastart just stores the address of the VarArgsFrameIndex slot into the
2301     // memory location argument.
2302     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2303     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2304     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2305     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2306                         MachinePointerInfo(SV),
2307                         false, false, 0);
2308   }
2309
2310   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2311   // We suppose the given va_list is already allocated.
2312   //
2313   // typedef struct {
2314   //  char gpr;     /* index into the array of 8 GPRs
2315   //                 * stored in the register save area
2316   //                 * gpr=0 corresponds to r3,
2317   //                 * gpr=1 to r4, etc.
2318   //                 */
2319   //  char fpr;     /* index into the array of 8 FPRs
2320   //                 * stored in the register save area
2321   //                 * fpr=0 corresponds to f1,
2322   //                 * fpr=1 to f2, etc.
2323   //                 */
2324   //  char *overflow_arg_area;
2325   //                /* location on stack that holds
2326   //                 * the next overflow argument
2327   //                 */
2328   //  char *reg_save_area;
2329   //               /* where r3:r10 and f1:f8 (if saved)
2330   //                * are stored
2331   //                */
2332   // } va_list[1];
2333
2334
2335   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2336   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2337
2338
2339   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2340
2341   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2342                                             PtrVT);
2343   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2344                                  PtrVT);
2345
2346   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2347   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2348
2349   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2350   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2351
2352   uint64_t FPROffset = 1;
2353   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2354
2355   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2356
2357   // Store first byte : number of int regs
2358   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2359                                          Op.getOperand(1),
2360                                          MachinePointerInfo(SV),
2361                                          MVT::i8, false, false, 0);
2362   uint64_t nextOffset = FPROffset;
2363   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2364                                   ConstFPROffset);
2365
2366   // Store second byte : number of float regs
2367   SDValue secondStore =
2368     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2369                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2370                       false, false, 0);
2371   nextOffset += StackOffset;
2372   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2373
2374   // Store second word : arguments given on stack
2375   SDValue thirdStore =
2376     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2377                  MachinePointerInfo(SV, nextOffset),
2378                  false, false, 0);
2379   nextOffset += FrameOffset;
2380   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2381
2382   // Store third word : arguments given in registers
2383   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2384                       MachinePointerInfo(SV, nextOffset),
2385                       false, false, 0);
2386
2387 }
2388
2389 #include "PPCGenCallingConv.inc"
2390
2391 // Function whose sole purpose is to kill compiler warnings 
2392 // stemming from unused functions included from PPCGenCallingConv.inc.
2393 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2394   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2395 }
2396
2397 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2398                                       CCValAssign::LocInfo &LocInfo,
2399                                       ISD::ArgFlagsTy &ArgFlags,
2400                                       CCState &State) {
2401   return true;
2402 }
2403
2404 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2405                                              MVT &LocVT,
2406                                              CCValAssign::LocInfo &LocInfo,
2407                                              ISD::ArgFlagsTy &ArgFlags,
2408                                              CCState &State) {
2409   static const MCPhysReg ArgRegs[] = {
2410     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2411     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2412   };
2413   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2414
2415   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2416
2417   // Skip one register if the first unallocated register has an even register
2418   // number and there are still argument registers available which have not been
2419   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2420   // need to skip a register if RegNum is odd.
2421   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2422     State.AllocateReg(ArgRegs[RegNum]);
2423   }
2424
2425   // Always return false here, as this function only makes sure that the first
2426   // unallocated register has an odd register number and does not actually
2427   // allocate a register for the current argument.
2428   return false;
2429 }
2430
2431 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2432                                                MVT &LocVT,
2433                                                CCValAssign::LocInfo &LocInfo,
2434                                                ISD::ArgFlagsTy &ArgFlags,
2435                                                CCState &State) {
2436   static const MCPhysReg ArgRegs[] = {
2437     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2438     PPC::F8
2439   };
2440
2441   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2442
2443   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2444
2445   // If there is only one Floating-point register left we need to put both f64
2446   // values of a split ppc_fp128 value on the stack.
2447   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2448     State.AllocateReg(ArgRegs[RegNum]);
2449   }
2450
2451   // Always return false here, as this function only makes sure that the two f64
2452   // values a ppc_fp128 value is split into are both passed in registers or both
2453   // passed on the stack and does not actually allocate a register for the
2454   // current argument.
2455   return false;
2456 }
2457
2458 /// FPR - The set of FP registers that should be allocated for arguments,
2459 /// on Darwin.
2460 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2461                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2462                                 PPC::F11, PPC::F12, PPC::F13};
2463
2464 /// QFPR - The set of QPX registers that should be allocated for arguments.
2465 static const MCPhysReg QFPR[] = {
2466     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2467     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2468
2469 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2470 /// the stack.
2471 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2472                                        unsigned PtrByteSize) {
2473   unsigned ArgSize = ArgVT.getStoreSize();
2474   if (Flags.isByVal())
2475     ArgSize = Flags.getByValSize();
2476
2477   // Round up to multiples of the pointer size, except for array members,
2478   // which are always packed.
2479   if (!Flags.isInConsecutiveRegs())
2480     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2481
2482   return ArgSize;
2483 }
2484
2485 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2486 /// on the stack.
2487 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2488                                             ISD::ArgFlagsTy Flags,
2489                                             unsigned PtrByteSize) {
2490   unsigned Align = PtrByteSize;
2491
2492   // Altivec parameters are padded to a 16 byte boundary.
2493   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2494       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2495       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2496     Align = 16;
2497   // QPX vector types stored in double-precision are padded to a 32 byte
2498   // boundary.
2499   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2500     Align = 32;
2501
2502   // ByVal parameters are aligned as requested.
2503   if (Flags.isByVal()) {
2504     unsigned BVAlign = Flags.getByValAlign();
2505     if (BVAlign > PtrByteSize) {
2506       if (BVAlign % PtrByteSize != 0)
2507           llvm_unreachable(
2508             "ByVal alignment is not a multiple of the pointer size");
2509
2510       Align = BVAlign;
2511     }
2512   }
2513
2514   // Array members are always packed to their original alignment.
2515   if (Flags.isInConsecutiveRegs()) {
2516     // If the array member was split into multiple registers, the first
2517     // needs to be aligned to the size of the full type.  (Except for
2518     // ppcf128, which is only aligned as its f64 components.)
2519     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2520       Align = OrigVT.getStoreSize();
2521     else
2522       Align = ArgVT.getStoreSize();
2523   }
2524
2525   return Align;
2526 }
2527
2528 /// CalculateStackSlotUsed - Return whether this argument will use its
2529 /// stack slot (instead of being passed in registers).  ArgOffset,
2530 /// AvailableFPRs, and AvailableVRs must hold the current argument
2531 /// position, and will be updated to account for this argument.
2532 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2533                                    ISD::ArgFlagsTy Flags,
2534                                    unsigned PtrByteSize,
2535                                    unsigned LinkageSize,
2536                                    unsigned ParamAreaSize,
2537                                    unsigned &ArgOffset,
2538                                    unsigned &AvailableFPRs,
2539                                    unsigned &AvailableVRs, bool HasQPX) {
2540   bool UseMemory = false;
2541
2542   // Respect alignment of argument on the stack.
2543   unsigned Align =
2544     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2545   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2546   // If there's no space left in the argument save area, we must
2547   // use memory (this check also catches zero-sized arguments).
2548   if (ArgOffset >= LinkageSize + ParamAreaSize)
2549     UseMemory = true;
2550
2551   // Allocate argument on the stack.
2552   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2553   if (Flags.isInConsecutiveRegsLast())
2554     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2555   // If we overran the argument save area, we must use memory
2556   // (this check catches arguments passed partially in memory)
2557   if (ArgOffset > LinkageSize + ParamAreaSize)
2558     UseMemory = true;
2559
2560   // However, if the argument is actually passed in an FPR or a VR,
2561   // we don't use memory after all.
2562   if (!Flags.isByVal()) {
2563     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2564         // QPX registers overlap with the scalar FP registers.
2565         (HasQPX && (ArgVT == MVT::v4f32 ||
2566                     ArgVT == MVT::v4f64 ||
2567                     ArgVT == MVT::v4i1)))
2568       if (AvailableFPRs > 0) {
2569         --AvailableFPRs;
2570         return false;
2571       }
2572     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2573         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2574         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2575       if (AvailableVRs > 0) {
2576         --AvailableVRs;
2577         return false;
2578       }
2579   }
2580
2581   return UseMemory;
2582 }
2583
2584 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2585 /// ensure minimum alignment required for target.
2586 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2587                                      unsigned NumBytes) {
2588   unsigned TargetAlign = Lowering->getStackAlignment();
2589   unsigned AlignMask = TargetAlign - 1;
2590   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2591   return NumBytes;
2592 }
2593
2594 SDValue
2595 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2596                                         CallingConv::ID CallConv, bool isVarArg,
2597                                         const SmallVectorImpl<ISD::InputArg>
2598                                           &Ins,
2599                                         SDLoc dl, SelectionDAG &DAG,
2600                                         SmallVectorImpl<SDValue> &InVals)
2601                                           const {
2602   if (Subtarget.isSVR4ABI()) {
2603     if (Subtarget.isPPC64())
2604       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2605                                          dl, DAG, InVals);
2606     else
2607       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2608                                          dl, DAG, InVals);
2609   } else {
2610     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2611                                        dl, DAG, InVals);
2612   }
2613 }
2614
2615 SDValue
2616 PPCTargetLowering::LowerFormalArguments_32SVR4(
2617                                       SDValue Chain,
2618                                       CallingConv::ID CallConv, bool isVarArg,
2619                                       const SmallVectorImpl<ISD::InputArg>
2620                                         &Ins,
2621                                       SDLoc dl, SelectionDAG &DAG,
2622                                       SmallVectorImpl<SDValue> &InVals) const {
2623
2624   // 32-bit SVR4 ABI Stack Frame Layout:
2625   //              +-----------------------------------+
2626   //        +-->  |            Back chain             |
2627   //        |     +-----------------------------------+
2628   //        |     | Floating-point register save area |
2629   //        |     +-----------------------------------+
2630   //        |     |    General register save area     |
2631   //        |     +-----------------------------------+
2632   //        |     |          CR save word             |
2633   //        |     +-----------------------------------+
2634   //        |     |         VRSAVE save word          |
2635   //        |     +-----------------------------------+
2636   //        |     |         Alignment padding         |
2637   //        |     +-----------------------------------+
2638   //        |     |     Vector register save area     |
2639   //        |     +-----------------------------------+
2640   //        |     |       Local variable space        |
2641   //        |     +-----------------------------------+
2642   //        |     |        Parameter list area        |
2643   //        |     +-----------------------------------+
2644   //        |     |           LR save word            |
2645   //        |     +-----------------------------------+
2646   // SP-->  +---  |            Back chain             |
2647   //              +-----------------------------------+
2648   //
2649   // Specifications:
2650   //   System V Application Binary Interface PowerPC Processor Supplement
2651   //   AltiVec Technology Programming Interface Manual
2652
2653   MachineFunction &MF = DAG.getMachineFunction();
2654   MachineFrameInfo *MFI = MF.getFrameInfo();
2655   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2656
2657   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2658   // Potential tail calls could cause overwriting of argument stack slots.
2659   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2660                        (CallConv == CallingConv::Fast));
2661   unsigned PtrByteSize = 4;
2662
2663   // Assign locations to all of the incoming arguments.
2664   SmallVector<CCValAssign, 16> ArgLocs;
2665   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2666                  *DAG.getContext());
2667
2668   // Reserve space for the linkage area on the stack.
2669   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2670   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2671
2672   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2673
2674   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2675     CCValAssign &VA = ArgLocs[i];
2676
2677     // Arguments stored in registers.
2678     if (VA.isRegLoc()) {
2679       const TargetRegisterClass *RC;
2680       EVT ValVT = VA.getValVT();
2681
2682       switch (ValVT.getSimpleVT().SimpleTy) {
2683         default:
2684           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2685         case MVT::i1:
2686         case MVT::i32:
2687           RC = &PPC::GPRCRegClass;
2688           break;
2689         case MVT::f32:
2690           RC = &PPC::F4RCRegClass;
2691           break;
2692         case MVT::f64:
2693           if (Subtarget.hasVSX())
2694             RC = &PPC::VSFRCRegClass;
2695           else
2696             RC = &PPC::F8RCRegClass;
2697           break;
2698         case MVT::v16i8:
2699         case MVT::v8i16:
2700         case MVT::v4i32:
2701           RC = &PPC::VRRCRegClass;
2702           break;
2703         case MVT::v4f32:
2704           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2705           break;
2706         case MVT::v2f64:
2707         case MVT::v2i64:
2708           RC = &PPC::VSHRCRegClass;
2709           break;
2710         case MVT::v4f64:
2711           RC = &PPC::QFRCRegClass;
2712           break;
2713         case MVT::v4i1:
2714           RC = &PPC::QBRCRegClass;
2715           break;
2716       }
2717
2718       // Transform the arguments stored in physical registers into virtual ones.
2719       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2720       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2721                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2722
2723       if (ValVT == MVT::i1)
2724         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2725
2726       InVals.push_back(ArgValue);
2727     } else {
2728       // Argument stored in memory.
2729       assert(VA.isMemLoc());
2730
2731       unsigned ArgSize = VA.getLocVT().getStoreSize();
2732       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2733                                       isImmutable);
2734
2735       // Create load nodes to retrieve arguments from the stack.
2736       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2737       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2738                                    MachinePointerInfo(),
2739                                    false, false, false, 0));
2740     }
2741   }
2742
2743   // Assign locations to all of the incoming aggregate by value arguments.
2744   // Aggregates passed by value are stored in the local variable space of the
2745   // caller's stack frame, right above the parameter list area.
2746   SmallVector<CCValAssign, 16> ByValArgLocs;
2747   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2748                       ByValArgLocs, *DAG.getContext());
2749
2750   // Reserve stack space for the allocations in CCInfo.
2751   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2752
2753   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2754
2755   // Area that is at least reserved in the caller of this function.
2756   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2757   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2758
2759   // Set the size that is at least reserved in caller of this function.  Tail
2760   // call optimized function's reserved stack space needs to be aligned so that
2761   // taking the difference between two stack areas will result in an aligned
2762   // stack.
2763   MinReservedArea =
2764       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2765   FuncInfo->setMinReservedArea(MinReservedArea);
2766
2767   SmallVector<SDValue, 8> MemOps;
2768
2769   // If the function takes variable number of arguments, make a frame index for
2770   // the start of the first vararg value... for expansion of llvm.va_start.
2771   if (isVarArg) {
2772     static const MCPhysReg GPArgRegs[] = {
2773       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2774       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2775     };
2776     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2777
2778     static const MCPhysReg FPArgRegs[] = {
2779       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2780       PPC::F8
2781     };
2782     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2783     if (DisablePPCFloatInVariadic)
2784       NumFPArgRegs = 0;
2785
2786     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2787     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2788
2789     // Make room for NumGPArgRegs and NumFPArgRegs.
2790     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2791                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2792
2793     FuncInfo->setVarArgsStackOffset(
2794       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2795                              CCInfo.getNextStackOffset(), true));
2796
2797     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2798     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2799
2800     // The fixed integer arguments of a variadic function are stored to the
2801     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2802     // the result of va_next.
2803     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2804       // Get an existing live-in vreg, or add a new one.
2805       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2806       if (!VReg)
2807         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2808
2809       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2810       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2811                                    MachinePointerInfo(), false, false, 0);
2812       MemOps.push_back(Store);
2813       // Increment the address by four for the next argument to store
2814       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2815       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2816     }
2817
2818     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2819     // is set.
2820     // The double arguments are stored to the VarArgsFrameIndex
2821     // on the stack.
2822     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2823       // Get an existing live-in vreg, or add a new one.
2824       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2825       if (!VReg)
2826         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2827
2828       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2829       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2830                                    MachinePointerInfo(), false, false, 0);
2831       MemOps.push_back(Store);
2832       // Increment the address by eight for the next argument to store
2833       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2834                                          PtrVT);
2835       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2836     }
2837   }
2838
2839   if (!MemOps.empty())
2840     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2841
2842   return Chain;
2843 }
2844
2845 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2846 // value to MVT::i64 and then truncate to the correct register size.
2847 SDValue
2848 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2849                                      SelectionDAG &DAG, SDValue ArgVal,
2850                                      SDLoc dl) const {
2851   if (Flags.isSExt())
2852     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2853                          DAG.getValueType(ObjectVT));
2854   else if (Flags.isZExt())
2855     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2856                          DAG.getValueType(ObjectVT));
2857
2858   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2859 }
2860
2861 SDValue
2862 PPCTargetLowering::LowerFormalArguments_64SVR4(
2863                                       SDValue Chain,
2864                                       CallingConv::ID CallConv, bool isVarArg,
2865                                       const SmallVectorImpl<ISD::InputArg>
2866                                         &Ins,
2867                                       SDLoc dl, SelectionDAG &DAG,
2868                                       SmallVectorImpl<SDValue> &InVals) const {
2869   // TODO: add description of PPC stack frame format, or at least some docs.
2870   //
2871   bool isELFv2ABI = Subtarget.isELFv2ABI();
2872   bool isLittleEndian = Subtarget.isLittleEndian();
2873   MachineFunction &MF = DAG.getMachineFunction();
2874   MachineFrameInfo *MFI = MF.getFrameInfo();
2875   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2876
2877   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2878          "fastcc not supported on varargs functions");
2879
2880   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2881   // Potential tail calls could cause overwriting of argument stack slots.
2882   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2883                        (CallConv == CallingConv::Fast));
2884   unsigned PtrByteSize = 8;
2885   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2886
2887   static const MCPhysReg GPR[] = {
2888     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2889     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2890   };
2891   static const MCPhysReg VR[] = {
2892     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2893     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2894   };
2895   static const MCPhysReg VSRH[] = {
2896     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2897     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2898   };
2899
2900   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2901   const unsigned Num_FPR_Regs = 13;
2902   const unsigned Num_VR_Regs  = array_lengthof(VR);
2903   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2904
2905   // Do a first pass over the arguments to determine whether the ABI
2906   // guarantees that our caller has allocated the parameter save area
2907   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2908   // in the ELFv2 ABI, it is true if this is a vararg function or if
2909   // any parameter is located in a stack slot.
2910
2911   bool HasParameterArea = !isELFv2ABI || isVarArg;
2912   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2913   unsigned NumBytes = LinkageSize;
2914   unsigned AvailableFPRs = Num_FPR_Regs;
2915   unsigned AvailableVRs = Num_VR_Regs;
2916   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2917     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2918                                PtrByteSize, LinkageSize, ParamAreaSize,
2919                                NumBytes, AvailableFPRs, AvailableVRs,
2920                                Subtarget.hasQPX()))
2921       HasParameterArea = true;
2922
2923   // Add DAG nodes to load the arguments or copy them out of registers.  On
2924   // entry to a function on PPC, the arguments start after the linkage area,
2925   // although the first ones are often in registers.
2926
2927   unsigned ArgOffset = LinkageSize;
2928   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2929   unsigned &QFPR_idx = FPR_idx;
2930   SmallVector<SDValue, 8> MemOps;
2931   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2932   unsigned CurArgIdx = 0;
2933   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2934     SDValue ArgVal;
2935     bool needsLoad = false;
2936     EVT ObjectVT = Ins[ArgNo].VT;
2937     EVT OrigVT = Ins[ArgNo].ArgVT;
2938     unsigned ObjSize = ObjectVT.getStoreSize();
2939     unsigned ArgSize = ObjSize;
2940     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2941     if (Ins[ArgNo].isOrigArg()) {
2942       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2943       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2944     }
2945     // We re-align the argument offset for each argument, except when using the
2946     // fast calling convention, when we need to make sure we do that only when
2947     // we'll actually use a stack slot.
2948     unsigned CurArgOffset, Align;
2949     auto ComputeArgOffset = [&]() {
2950       /* Respect alignment of argument on the stack.  */
2951       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2952       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2953       CurArgOffset = ArgOffset;
2954     };
2955
2956     if (CallConv != CallingConv::Fast) {
2957       ComputeArgOffset();
2958
2959       /* Compute GPR index associated with argument offset.  */
2960       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2961       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2962     }
2963
2964     // FIXME the codegen can be much improved in some cases.
2965     // We do not have to keep everything in memory.
2966     if (Flags.isByVal()) {
2967       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2968
2969       if (CallConv == CallingConv::Fast)
2970         ComputeArgOffset();
2971
2972       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2973       ObjSize = Flags.getByValSize();
2974       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2975       // Empty aggregate parameters do not take up registers.  Examples:
2976       //   struct { } a;
2977       //   union  { } b;
2978       //   int c[0];
2979       // etc.  However, we have to provide a place-holder in InVals, so
2980       // pretend we have an 8-byte item at the current address for that
2981       // purpose.
2982       if (!ObjSize) {
2983         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2984         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2985         InVals.push_back(FIN);
2986         continue;
2987       }
2988
2989       // Create a stack object covering all stack doublewords occupied
2990       // by the argument.  If the argument is (fully or partially) on
2991       // the stack, or if the argument is fully in registers but the
2992       // caller has allocated the parameter save anyway, we can refer
2993       // directly to the caller's stack frame.  Otherwise, create a
2994       // local copy in our own frame.
2995       int FI;
2996       if (HasParameterArea ||
2997           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2998         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2999       else
3000         FI = MFI->CreateStackObject(ArgSize, Align, false);
3001       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3002
3003       // Handle aggregates smaller than 8 bytes.
3004       if (ObjSize < PtrByteSize) {
3005         // The value of the object is its address, which differs from the
3006         // address of the enclosing doubleword on big-endian systems.
3007         SDValue Arg = FIN;
3008         if (!isLittleEndian) {
3009           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3010           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3011         }
3012         InVals.push_back(Arg);
3013
3014         if (GPR_idx != Num_GPR_Regs) {
3015           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3016           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3017           SDValue Store;
3018
3019           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3020             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3021                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3022             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3023                                       MachinePointerInfo(FuncArg),
3024                                       ObjType, false, false, 0);
3025           } else {
3026             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3027             // store the whole register as-is to the parameter save area
3028             // slot.
3029             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3030                                  MachinePointerInfo(FuncArg),
3031                                  false, false, 0);
3032           }
3033
3034           MemOps.push_back(Store);
3035         }
3036         // Whether we copied from a register or not, advance the offset
3037         // into the parameter save area by a full doubleword.
3038         ArgOffset += PtrByteSize;
3039         continue;
3040       }
3041
3042       // The value of the object is its address, which is the address of
3043       // its first stack doubleword.
3044       InVals.push_back(FIN);
3045
3046       // Store whatever pieces of the object are in registers to memory.
3047       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3048         if (GPR_idx == Num_GPR_Regs)
3049           break;
3050
3051         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3052         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3053         SDValue Addr = FIN;
3054         if (j) {
3055           SDValue Off = DAG.getConstant(j, PtrVT);
3056           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3057         }
3058         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3059                                      MachinePointerInfo(FuncArg, j),
3060                                      false, false, 0);
3061         MemOps.push_back(Store);
3062         ++GPR_idx;
3063       }
3064       ArgOffset += ArgSize;
3065       continue;
3066     }
3067
3068     switch (ObjectVT.getSimpleVT().SimpleTy) {
3069     default: llvm_unreachable("Unhandled argument type!");
3070     case MVT::i1:
3071     case MVT::i32:
3072     case MVT::i64:
3073       // These can be scalar arguments or elements of an integer array type
3074       // passed directly.  Clang may use those instead of "byval" aggregate
3075       // types to avoid forcing arguments to memory unnecessarily.
3076       if (GPR_idx != Num_GPR_Regs) {
3077         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3078         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3079
3080         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3081           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3082           // value to MVT::i64 and then truncate to the correct register size.
3083           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3084       } else {
3085         if (CallConv == CallingConv::Fast)
3086           ComputeArgOffset();
3087
3088         needsLoad = true;
3089         ArgSize = PtrByteSize;
3090       }
3091       if (CallConv != CallingConv::Fast || needsLoad)
3092         ArgOffset += 8;
3093       break;
3094
3095     case MVT::f32:
3096     case MVT::f64:
3097       // These can be scalar arguments or elements of a float array type
3098       // passed directly.  The latter are used to implement ELFv2 homogenous
3099       // float aggregates.
3100       if (FPR_idx != Num_FPR_Regs) {
3101         unsigned VReg;
3102
3103         if (ObjectVT == MVT::f32)
3104           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3105         else
3106           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3107                                                 ? &PPC::VSFRCRegClass
3108                                                 : &PPC::F8RCRegClass);
3109
3110         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3111         ++FPR_idx;
3112       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3113         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3114         // once we support fp <-> gpr moves.
3115
3116         // This can only ever happen in the presence of f32 array types,
3117         // since otherwise we never run out of FPRs before running out
3118         // of GPRs.
3119         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3120         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3121
3122         if (ObjectVT == MVT::f32) {
3123           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3124             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3125                                  DAG.getConstant(32, MVT::i32));
3126           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3127         }
3128
3129         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3130       } else {
3131         if (CallConv == CallingConv::Fast)
3132           ComputeArgOffset();
3133
3134         needsLoad = true;
3135       }
3136
3137       // When passing an array of floats, the array occupies consecutive
3138       // space in the argument area; only round up to the next doubleword
3139       // at the end of the array.  Otherwise, each float takes 8 bytes.
3140       if (CallConv != CallingConv::Fast || needsLoad) {
3141         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3142         ArgOffset += ArgSize;
3143         if (Flags.isInConsecutiveRegsLast())
3144           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3145       }
3146       break;
3147     case MVT::v4f32:
3148     case MVT::v4i32:
3149     case MVT::v8i16:
3150     case MVT::v16i8:
3151     case MVT::v2f64:
3152     case MVT::v2i64:
3153       if (!Subtarget.hasQPX()) {
3154       // These can be scalar arguments or elements of a vector array type
3155       // passed directly.  The latter are used to implement ELFv2 homogenous
3156       // vector aggregates.
3157       if (VR_idx != Num_VR_Regs) {
3158         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3159                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3160                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3161         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3162         ++VR_idx;
3163       } else {
3164         if (CallConv == CallingConv::Fast)
3165           ComputeArgOffset();
3166
3167         needsLoad = true;
3168       }
3169       if (CallConv != CallingConv::Fast || needsLoad)
3170         ArgOffset += 16;
3171       break;
3172       } // not QPX
3173
3174       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3175              "Invalid QPX parameter type");
3176       /* fall through */
3177
3178     case MVT::v4f64:
3179     case MVT::v4i1:
3180       // QPX vectors are treated like their scalar floating-point subregisters
3181       // (except that they're larger).
3182       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3183       if (QFPR_idx != Num_QFPR_Regs) {
3184         const TargetRegisterClass *RC;
3185         switch (ObjectVT.getSimpleVT().SimpleTy) {
3186         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3187         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3188         default:         RC = &PPC::QBRCRegClass; break;
3189         }
3190
3191         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3192         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3193         ++QFPR_idx;
3194       } else {
3195         if (CallConv == CallingConv::Fast)
3196           ComputeArgOffset();
3197         needsLoad = true;
3198       }
3199       if (CallConv != CallingConv::Fast || needsLoad)
3200         ArgOffset += Sz;
3201       break;
3202     }
3203
3204     // We need to load the argument to a virtual register if we determined
3205     // above that we ran out of physical registers of the appropriate type.
3206     if (needsLoad) {
3207       if (ObjSize < ArgSize && !isLittleEndian)
3208         CurArgOffset += ArgSize - ObjSize;
3209       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3210       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3211       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3212                            false, false, false, 0);
3213     }
3214
3215     InVals.push_back(ArgVal);
3216   }
3217
3218   // Area that is at least reserved in the caller of this function.
3219   unsigned MinReservedArea;
3220   if (HasParameterArea)
3221     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3222   else
3223     MinReservedArea = LinkageSize;
3224
3225   // Set the size that is at least reserved in caller of this function.  Tail
3226   // call optimized functions' reserved stack space needs to be aligned so that
3227   // taking the difference between two stack areas will result in an aligned
3228   // stack.
3229   MinReservedArea =
3230       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3231   FuncInfo->setMinReservedArea(MinReservedArea);
3232
3233   // If the function takes variable number of arguments, make a frame index for
3234   // the start of the first vararg value... for expansion of llvm.va_start.
3235   if (isVarArg) {
3236     int Depth = ArgOffset;
3237
3238     FuncInfo->setVarArgsFrameIndex(
3239       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3240     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3241
3242     // If this function is vararg, store any remaining integer argument regs
3243     // to their spots on the stack so that they may be loaded by deferencing the
3244     // result of va_next.
3245     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3246          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3247       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3248       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3249       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3250                                    MachinePointerInfo(), false, false, 0);
3251       MemOps.push_back(Store);
3252       // Increment the address by four for the next argument to store
3253       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3254       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3255     }
3256   }
3257
3258   if (!MemOps.empty())
3259     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3260
3261   return Chain;
3262 }
3263
3264 SDValue
3265 PPCTargetLowering::LowerFormalArguments_Darwin(
3266                                       SDValue Chain,
3267                                       CallingConv::ID CallConv, bool isVarArg,
3268                                       const SmallVectorImpl<ISD::InputArg>
3269                                         &Ins,
3270                                       SDLoc dl, SelectionDAG &DAG,
3271                                       SmallVectorImpl<SDValue> &InVals) const {
3272   // TODO: add description of PPC stack frame format, or at least some docs.
3273   //
3274   MachineFunction &MF = DAG.getMachineFunction();
3275   MachineFrameInfo *MFI = MF.getFrameInfo();
3276   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3277
3278   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3279   bool isPPC64 = PtrVT == MVT::i64;
3280   // Potential tail calls could cause overwriting of argument stack slots.
3281   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3282                        (CallConv == CallingConv::Fast));
3283   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3284   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3285   unsigned ArgOffset = LinkageSize;
3286   // Area that is at least reserved in caller of this function.
3287   unsigned MinReservedArea = ArgOffset;
3288
3289   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3290     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3291     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3292   };
3293   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3294     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3295     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3296   };
3297   static const MCPhysReg VR[] = {
3298     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3299     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3300   };
3301
3302   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3303   const unsigned Num_FPR_Regs = 13;
3304   const unsigned Num_VR_Regs  = array_lengthof( VR);
3305
3306   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3307
3308   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3309
3310   // In 32-bit non-varargs functions, the stack space for vectors is after the
3311   // stack space for non-vectors.  We do not use this space unless we have
3312   // too many vectors to fit in registers, something that only occurs in
3313   // constructed examples:), but we have to walk the arglist to figure
3314   // that out...for the pathological case, compute VecArgOffset as the
3315   // start of the vector parameter area.  Computing VecArgOffset is the
3316   // entire point of the following loop.
3317   unsigned VecArgOffset = ArgOffset;
3318   if (!isVarArg && !isPPC64) {
3319     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3320          ++ArgNo) {
3321       EVT ObjectVT = Ins[ArgNo].VT;
3322       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3323
3324       if (Flags.isByVal()) {
3325         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3326         unsigned ObjSize = Flags.getByValSize();
3327         unsigned ArgSize =
3328                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3329         VecArgOffset += ArgSize;
3330         continue;
3331       }
3332
3333       switch(ObjectVT.getSimpleVT().SimpleTy) {
3334       default: llvm_unreachable("Unhandled argument type!");
3335       case MVT::i1:
3336       case MVT::i32:
3337       case MVT::f32:
3338         VecArgOffset += 4;
3339         break;
3340       case MVT::i64:  // PPC64
3341       case MVT::f64:
3342         // FIXME: We are guaranteed to be !isPPC64 at this point.
3343         // Does MVT::i64 apply?
3344         VecArgOffset += 8;
3345         break;
3346       case MVT::v4f32:
3347       case MVT::v4i32:
3348       case MVT::v8i16:
3349       case MVT::v16i8:
3350         // Nothing to do, we're only looking at Nonvector args here.
3351         break;
3352       }
3353     }
3354   }
3355   // We've found where the vector parameter area in memory is.  Skip the
3356   // first 12 parameters; these don't use that memory.
3357   VecArgOffset = ((VecArgOffset+15)/16)*16;
3358   VecArgOffset += 12*16;
3359
3360   // Add DAG nodes to load the arguments or copy them out of registers.  On
3361   // entry to a function on PPC, the arguments start after the linkage area,
3362   // although the first ones are often in registers.
3363
3364   SmallVector<SDValue, 8> MemOps;
3365   unsigned nAltivecParamsAtEnd = 0;
3366   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3367   unsigned CurArgIdx = 0;
3368   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3369     SDValue ArgVal;
3370     bool needsLoad = false;
3371     EVT ObjectVT = Ins[ArgNo].VT;
3372     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3373     unsigned ArgSize = ObjSize;
3374     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3375     if (Ins[ArgNo].isOrigArg()) {
3376       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3377       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3378     }
3379     unsigned CurArgOffset = ArgOffset;
3380
3381     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3382     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3383         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3384       if (isVarArg || isPPC64) {
3385         MinReservedArea = ((MinReservedArea+15)/16)*16;
3386         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3387                                                   Flags,
3388                                                   PtrByteSize);
3389       } else  nAltivecParamsAtEnd++;
3390     } else
3391       // Calculate min reserved area.
3392       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3393                                                 Flags,
3394                                                 PtrByteSize);
3395
3396     // FIXME the codegen can be much improved in some cases.
3397     // We do not have to keep everything in memory.
3398     if (Flags.isByVal()) {
3399       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3400
3401       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3402       ObjSize = Flags.getByValSize();
3403       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3404       // Objects of size 1 and 2 are right justified, everything else is
3405       // left justified.  This means the memory address is adjusted forwards.
3406       if (ObjSize==1 || ObjSize==2) {
3407         CurArgOffset = CurArgOffset + (4 - ObjSize);
3408       }
3409       // The value of the object is its address.
3410       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3411       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3412       InVals.push_back(FIN);
3413       if (ObjSize==1 || ObjSize==2) {
3414         if (GPR_idx != Num_GPR_Regs) {
3415           unsigned VReg;
3416           if (isPPC64)
3417             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3418           else
3419             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3420           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3421           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3422           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3423                                             MachinePointerInfo(FuncArg),
3424                                             ObjType, false, false, 0);
3425           MemOps.push_back(Store);
3426           ++GPR_idx;
3427         }
3428
3429         ArgOffset += PtrByteSize;
3430
3431         continue;
3432       }
3433       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3434         // Store whatever pieces of the object are in registers
3435         // to memory.  ArgOffset will be the address of the beginning
3436         // of the object.
3437         if (GPR_idx != Num_GPR_Regs) {
3438           unsigned VReg;
3439           if (isPPC64)
3440             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3441           else
3442             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3443           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3444           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3445           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3446           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3447                                        MachinePointerInfo(FuncArg, j),
3448                                        false, false, 0);
3449           MemOps.push_back(Store);
3450           ++GPR_idx;
3451           ArgOffset += PtrByteSize;
3452         } else {
3453           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3454           break;
3455         }
3456       }
3457       continue;
3458     }
3459
3460     switch (ObjectVT.getSimpleVT().SimpleTy) {
3461     default: llvm_unreachable("Unhandled argument type!");
3462     case MVT::i1:
3463     case MVT::i32:
3464       if (!isPPC64) {
3465         if (GPR_idx != Num_GPR_Regs) {
3466           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3467           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3468
3469           if (ObjectVT == MVT::i1)
3470             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3471
3472           ++GPR_idx;
3473         } else {
3474           needsLoad = true;
3475           ArgSize = PtrByteSize;
3476         }
3477         // All int arguments reserve stack space in the Darwin ABI.
3478         ArgOffset += PtrByteSize;
3479         break;
3480       }
3481       // FALLTHROUGH
3482     case MVT::i64:  // PPC64
3483       if (GPR_idx != Num_GPR_Regs) {
3484         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3485         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3486
3487         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3488           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3489           // value to MVT::i64 and then truncate to the correct register size.
3490           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3491
3492         ++GPR_idx;
3493       } else {
3494         needsLoad = true;
3495         ArgSize = PtrByteSize;
3496       }
3497       // All int arguments reserve stack space in the Darwin ABI.
3498       ArgOffset += 8;
3499       break;
3500
3501     case MVT::f32:
3502     case MVT::f64:
3503       // Every 4 bytes of argument space consumes one of the GPRs available for
3504       // argument passing.
3505       if (GPR_idx != Num_GPR_Regs) {
3506         ++GPR_idx;
3507         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3508           ++GPR_idx;
3509       }
3510       if (FPR_idx != Num_FPR_Regs) {
3511         unsigned VReg;
3512
3513         if (ObjectVT == MVT::f32)
3514           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3515         else
3516           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3517
3518         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3519         ++FPR_idx;
3520       } else {
3521         needsLoad = true;
3522       }
3523
3524       // All FP arguments reserve stack space in the Darwin ABI.
3525       ArgOffset += isPPC64 ? 8 : ObjSize;
3526       break;
3527     case MVT::v4f32:
3528     case MVT::v4i32:
3529     case MVT::v8i16:
3530     case MVT::v16i8:
3531       // Note that vector arguments in registers don't reserve stack space,
3532       // except in varargs functions.
3533       if (VR_idx != Num_VR_Regs) {
3534         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3535         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3536         if (isVarArg) {
3537           while ((ArgOffset % 16) != 0) {
3538             ArgOffset += PtrByteSize;
3539             if (GPR_idx != Num_GPR_Regs)
3540               GPR_idx++;
3541           }
3542           ArgOffset += 16;
3543           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3544         }
3545         ++VR_idx;
3546       } else {
3547         if (!isVarArg && !isPPC64) {
3548           // Vectors go after all the nonvectors.
3549           CurArgOffset = VecArgOffset;
3550           VecArgOffset += 16;
3551         } else {
3552           // Vectors are aligned.
3553           ArgOffset = ((ArgOffset+15)/16)*16;
3554           CurArgOffset = ArgOffset;
3555           ArgOffset += 16;
3556         }
3557         needsLoad = true;
3558       }
3559       break;
3560     }
3561
3562     // We need to load the argument to a virtual register if we determined above
3563     // that we ran out of physical registers of the appropriate type.
3564     if (needsLoad) {
3565       int FI = MFI->CreateFixedObject(ObjSize,
3566                                       CurArgOffset + (ArgSize - ObjSize),
3567                                       isImmutable);
3568       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3569       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3570                            false, false, false, 0);
3571     }
3572
3573     InVals.push_back(ArgVal);
3574   }
3575
3576   // Allow for Altivec parameters at the end, if needed.
3577   if (nAltivecParamsAtEnd) {
3578     MinReservedArea = ((MinReservedArea+15)/16)*16;
3579     MinReservedArea += 16*nAltivecParamsAtEnd;
3580   }
3581
3582   // Area that is at least reserved in the caller of this function.
3583   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3584
3585   // Set the size that is at least reserved in caller of this function.  Tail
3586   // call optimized functions' reserved stack space needs to be aligned so that
3587   // taking the difference between two stack areas will result in an aligned
3588   // stack.
3589   MinReservedArea =
3590       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3591   FuncInfo->setMinReservedArea(MinReservedArea);
3592
3593   // If the function takes variable number of arguments, make a frame index for
3594   // the start of the first vararg value... for expansion of llvm.va_start.
3595   if (isVarArg) {
3596     int Depth = ArgOffset;
3597
3598     FuncInfo->setVarArgsFrameIndex(
3599       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3600                              Depth, true));
3601     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3602
3603     // If this function is vararg, store any remaining integer argument regs
3604     // to their spots on the stack so that they may be loaded by deferencing the
3605     // result of va_next.
3606     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3607       unsigned VReg;
3608
3609       if (isPPC64)
3610         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3611       else
3612         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3613
3614       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3615       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3616                                    MachinePointerInfo(), false, false, 0);
3617       MemOps.push_back(Store);
3618       // Increment the address by four for the next argument to store
3619       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3620       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3621     }
3622   }
3623
3624   if (!MemOps.empty())
3625     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3626
3627   return Chain;
3628 }
3629
3630 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3631 /// adjusted to accommodate the arguments for the tailcall.
3632 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3633                                    unsigned ParamSize) {
3634
3635   if (!isTailCall) return 0;
3636
3637   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3638   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3639   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3640   // Remember only if the new adjustement is bigger.
3641   if (SPDiff < FI->getTailCallSPDelta())
3642     FI->setTailCallSPDelta(SPDiff);
3643
3644   return SPDiff;
3645 }
3646
3647 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3648 /// for tail call optimization. Targets which want to do tail call
3649 /// optimization should implement this function.
3650 bool
3651 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3652                                                      CallingConv::ID CalleeCC,
3653                                                      bool isVarArg,
3654                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3655                                                      SelectionDAG& DAG) const {
3656   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3657     return false;
3658
3659   // Variable argument functions are not supported.
3660   if (isVarArg)
3661     return false;
3662
3663   MachineFunction &MF = DAG.getMachineFunction();
3664   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3665   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3666     // Functions containing by val parameters are not supported.
3667     for (unsigned i = 0; i != Ins.size(); i++) {
3668        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3669        if (Flags.isByVal()) return false;
3670     }
3671
3672     // Non-PIC/GOT tail calls are supported.
3673     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3674       return true;
3675
3676     // At the moment we can only do local tail calls (in same module, hidden
3677     // or protected) if we are generating PIC.
3678     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3679       return G->getGlobal()->hasHiddenVisibility()
3680           || G->getGlobal()->hasProtectedVisibility();
3681   }
3682
3683   return false;
3684 }
3685
3686 /// isCallCompatibleAddress - Return the immediate to use if the specified
3687 /// 32-bit value is representable in the immediate field of a BxA instruction.
3688 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3689   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3690   if (!C) return nullptr;
3691
3692   int Addr = C->getZExtValue();
3693   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3694       SignExtend32<26>(Addr) != Addr)
3695     return nullptr;  // Top 6 bits have to be sext of immediate.
3696
3697   return DAG.getConstant((int)C->getZExtValue() >> 2,
3698                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3699 }
3700
3701 namespace {
3702
3703 struct TailCallArgumentInfo {
3704   SDValue Arg;
3705   SDValue FrameIdxOp;
3706   int       FrameIdx;
3707
3708   TailCallArgumentInfo() : FrameIdx(0) {}
3709 };
3710
3711 }
3712
3713 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3714 static void
3715 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3716                                            SDValue Chain,
3717                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3718                    SmallVectorImpl<SDValue> &MemOpChains,
3719                    SDLoc dl) {
3720   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3721     SDValue Arg = TailCallArgs[i].Arg;
3722     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3723     int FI = TailCallArgs[i].FrameIdx;
3724     // Store relative to framepointer.
3725     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3726                                        MachinePointerInfo::getFixedStack(FI),
3727                                        false, false, 0));
3728   }
3729 }
3730
3731 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3732 /// the appropriate stack slot for the tail call optimized function call.
3733 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3734                                                MachineFunction &MF,
3735                                                SDValue Chain,
3736                                                SDValue OldRetAddr,
3737                                                SDValue OldFP,
3738                                                int SPDiff,
3739                                                bool isPPC64,
3740                                                bool isDarwinABI,
3741                                                SDLoc dl) {
3742   if (SPDiff) {
3743     // Calculate the new stack slot for the return address.
3744     int SlotSize = isPPC64 ? 8 : 4;
3745     const PPCFrameLowering *FL =
3746         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3747     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3748     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3749                                                           NewRetAddrLoc, true);
3750     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3751     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3752     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3753                          MachinePointerInfo::getFixedStack(NewRetAddr),
3754                          false, false, 0);
3755
3756     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3757     // slot as the FP is never overwritten.
3758     if (isDarwinABI) {
3759       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3760       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3761                                                           true);
3762       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3763       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3764                            MachinePointerInfo::getFixedStack(NewFPIdx),
3765                            false, false, 0);
3766     }
3767   }
3768   return Chain;
3769 }
3770
3771 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3772 /// the position of the argument.
3773 static void
3774 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3775                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3776                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3777   int Offset = ArgOffset + SPDiff;
3778   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3779   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3780   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3781   SDValue FIN = DAG.getFrameIndex(FI, VT);
3782   TailCallArgumentInfo Info;
3783   Info.Arg = Arg;
3784   Info.FrameIdxOp = FIN;
3785   Info.FrameIdx = FI;
3786   TailCallArguments.push_back(Info);
3787 }
3788
3789 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3790 /// stack slot. Returns the chain as result and the loaded frame pointers in
3791 /// LROpOut/FPOpout. Used when tail calling.
3792 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3793                                                         int SPDiff,
3794                                                         SDValue Chain,
3795                                                         SDValue &LROpOut,
3796                                                         SDValue &FPOpOut,
3797                                                         bool isDarwinABI,
3798                                                         SDLoc dl) const {
3799   if (SPDiff) {
3800     // Load the LR and FP stack slot for later adjusting.
3801     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3802     LROpOut = getReturnAddrFrameIndex(DAG);
3803     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3804                           false, false, false, 0);
3805     Chain = SDValue(LROpOut.getNode(), 1);
3806
3807     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3808     // slot as the FP is never overwritten.
3809     if (isDarwinABI) {
3810       FPOpOut = getFramePointerFrameIndex(DAG);
3811       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3812                             false, false, false, 0);
3813       Chain = SDValue(FPOpOut.getNode(), 1);
3814     }
3815   }
3816   return Chain;
3817 }
3818
3819 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3820 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3821 /// specified by the specific parameter attribute. The copy will be passed as
3822 /// a byval function parameter.
3823 /// Sometimes what we are copying is the end of a larger object, the part that
3824 /// does not fit in registers.
3825 static SDValue
3826 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3827                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3828                           SDLoc dl) {
3829   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3830   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3831                        false, false, MachinePointerInfo(),
3832                        MachinePointerInfo());
3833 }
3834
3835 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3836 /// tail calls.
3837 static void
3838 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3839                  SDValue Arg, SDValue PtrOff, int SPDiff,
3840                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3841                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3842                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3843                  SDLoc dl) {
3844   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3845   if (!isTailCall) {
3846     if (isVector) {
3847       SDValue StackPtr;
3848       if (isPPC64)
3849         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3850       else
3851         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3852       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3853                            DAG.getConstant(ArgOffset, PtrVT));
3854     }
3855     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3856                                        MachinePointerInfo(), false, false, 0));
3857   // Calculate and remember argument location.
3858   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3859                                   TailCallArguments);
3860 }
3861
3862 static
3863 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3864                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3865                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3866                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3867   MachineFunction &MF = DAG.getMachineFunction();
3868
3869   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3870   // might overwrite each other in case of tail call optimization.
3871   SmallVector<SDValue, 8> MemOpChains2;
3872   // Do not flag preceding copytoreg stuff together with the following stuff.
3873   InFlag = SDValue();
3874   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3875                                     MemOpChains2, dl);
3876   if (!MemOpChains2.empty())
3877     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3878
3879   // Store the return address to the appropriate stack slot.
3880   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3881                                         isPPC64, isDarwinABI, dl);
3882
3883   // Emit callseq_end just before tailcall node.
3884   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3885                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3886   InFlag = Chain.getValue(1);
3887 }
3888
3889 // Is this global address that of a function that can be called by name? (as
3890 // opposed to something that must hold a descriptor for an indirect call).
3891 static bool isFunctionGlobalAddress(SDValue Callee) {
3892   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3893     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3894         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3895       return false;
3896
3897     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3898   }
3899
3900   return false;
3901 }
3902
3903 static
3904 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3905                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3906                      bool isTailCall, bool IsPatchPoint,
3907                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3908                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3909                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3910
3911   bool isPPC64 = Subtarget.isPPC64();
3912   bool isSVR4ABI = Subtarget.isSVR4ABI();
3913   bool isELFv2ABI = Subtarget.isELFv2ABI();
3914
3915   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3916   NodeTys.push_back(MVT::Other);   // Returns a chain
3917   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3918
3919   unsigned CallOpc = PPCISD::CALL;
3920
3921   bool needIndirectCall = true;
3922   if (!isSVR4ABI || !isPPC64)
3923     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3924       // If this is an absolute destination address, use the munged value.
3925       Callee = SDValue(Dest, 0);
3926       needIndirectCall = false;
3927     }
3928
3929   if (isFunctionGlobalAddress(Callee)) {
3930     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3931     // A call to a TLS address is actually an indirect call to a
3932     // thread-specific pointer.
3933     unsigned OpFlags = 0;
3934     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3935          (Subtarget.getTargetTriple().isMacOSX() &&
3936           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3937          (G->getGlobal()->isDeclaration() ||
3938           G->getGlobal()->isWeakForLinker())) ||
3939         (Subtarget.isTargetELF() && !isPPC64 &&
3940          !G->getGlobal()->hasLocalLinkage() &&
3941          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3942       // PC-relative references to external symbols should go through $stub,
3943       // unless we're building with the leopard linker or later, which
3944       // automatically synthesizes these stubs.
3945       OpFlags = PPCII::MO_PLT_OR_STUB;
3946     }
3947
3948     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3949     // every direct call is) turn it into a TargetGlobalAddress /
3950     // TargetExternalSymbol node so that legalize doesn't hack it.
3951     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3952                                         Callee.getValueType(), 0, OpFlags);
3953     needIndirectCall = false;
3954   }
3955
3956   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3957     unsigned char OpFlags = 0;
3958
3959     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3960          (Subtarget.getTargetTriple().isMacOSX() &&
3961           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3962         (Subtarget.isTargetELF() && !isPPC64 &&
3963          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3964       // PC-relative references to external symbols should go through $stub,
3965       // unless we're building with the leopard linker or later, which
3966       // automatically synthesizes these stubs.
3967       OpFlags = PPCII::MO_PLT_OR_STUB;
3968     }
3969
3970     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3971                                          OpFlags);
3972     needIndirectCall = false;
3973   }
3974
3975   if (IsPatchPoint) {
3976     // We'll form an invalid direct call when lowering a patchpoint; the full
3977     // sequence for an indirect call is complicated, and many of the
3978     // instructions introduced might have side effects (and, thus, can't be
3979     // removed later). The call itself will be removed as soon as the
3980     // argument/return lowering is complete, so the fact that it has the wrong
3981     // kind of operands should not really matter.
3982     needIndirectCall = false;
3983   }
3984
3985   if (needIndirectCall) {
3986     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3987     // to do the call, we can't use PPCISD::CALL.
3988     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3989
3990     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3991       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3992       // entry point, but to the function descriptor (the function entry point
3993       // address is part of the function descriptor though).
3994       // The function descriptor is a three doubleword structure with the
3995       // following fields: function entry point, TOC base address and
3996       // environment pointer.
3997       // Thus for a call through a function pointer, the following actions need
3998       // to be performed:
3999       //   1. Save the TOC of the caller in the TOC save area of its stack
4000       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4001       //   2. Load the address of the function entry point from the function
4002       //      descriptor.
4003       //   3. Load the TOC of the callee from the function descriptor into r2.
4004       //   4. Load the environment pointer from the function descriptor into
4005       //      r11.
4006       //   5. Branch to the function entry point address.
4007       //   6. On return of the callee, the TOC of the caller needs to be
4008       //      restored (this is done in FinishCall()).
4009       //
4010       // The loads are scheduled at the beginning of the call sequence, and the
4011       // register copies are flagged together to ensure that no other
4012       // operations can be scheduled in between. E.g. without flagging the
4013       // copies together, a TOC access in the caller could be scheduled between
4014       // the assignment of the callee TOC and the branch to the callee, which
4015       // results in the TOC access going through the TOC of the callee instead
4016       // of going through the TOC of the caller, which leads to incorrect code.
4017
4018       // Load the address of the function entry point from the function
4019       // descriptor.
4020       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4021       if (LDChain.getValueType() == MVT::Glue)
4022         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4023
4024       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4025
4026       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4027       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4028                                         false, false, LoadsInv, 8);
4029
4030       // Load environment pointer into r11.
4031       SDValue PtrOff = DAG.getIntPtrConstant(16);
4032       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4033       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4034                                        MPI.getWithOffset(16), false, false,
4035                                        LoadsInv, 8);
4036
4037       SDValue TOCOff = DAG.getIntPtrConstant(8);
4038       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4039       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4040                                    MPI.getWithOffset(8), false, false,
4041                                    LoadsInv, 8);
4042
4043       setUsesTOCBasePtr(DAG);
4044       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4045                                         InFlag);
4046       Chain = TOCVal.getValue(0);
4047       InFlag = TOCVal.getValue(1);
4048
4049       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4050                                         InFlag);
4051
4052       Chain = EnvVal.getValue(0);
4053       InFlag = EnvVal.getValue(1);
4054
4055       MTCTROps[0] = Chain;
4056       MTCTROps[1] = LoadFuncPtr;
4057       MTCTROps[2] = InFlag;
4058     }
4059
4060     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4061                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4062     InFlag = Chain.getValue(1);
4063
4064     NodeTys.clear();
4065     NodeTys.push_back(MVT::Other);
4066     NodeTys.push_back(MVT::Glue);
4067     Ops.push_back(Chain);
4068     CallOpc = PPCISD::BCTRL;
4069     Callee.setNode(nullptr);
4070     // Add use of X11 (holding environment pointer)
4071     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4072       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4073     // Add CTR register as callee so a bctr can be emitted later.
4074     if (isTailCall)
4075       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4076   }
4077
4078   // If this is a direct call, pass the chain and the callee.
4079   if (Callee.getNode()) {
4080     Ops.push_back(Chain);
4081     Ops.push_back(Callee);
4082   }
4083   // If this is a tail call add stack pointer delta.
4084   if (isTailCall)
4085     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4086
4087   // Add argument registers to the end of the list so that they are known live
4088   // into the call.
4089   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4090     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4091                                   RegsToPass[i].second.getValueType()));
4092
4093   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4094   // into the call.
4095   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4096     setUsesTOCBasePtr(DAG);
4097     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4098   }
4099
4100   return CallOpc;
4101 }
4102
4103 static
4104 bool isLocalCall(const SDValue &Callee)
4105 {
4106   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4107     return !G->getGlobal()->isDeclaration() &&
4108            !G->getGlobal()->isWeakForLinker();
4109   return false;
4110 }
4111
4112 SDValue
4113 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4114                                    CallingConv::ID CallConv, bool isVarArg,
4115                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4116                                    SDLoc dl, SelectionDAG &DAG,
4117                                    SmallVectorImpl<SDValue> &InVals) const {
4118
4119   SmallVector<CCValAssign, 16> RVLocs;
4120   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4121                     *DAG.getContext());
4122   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4123
4124   // Copy all of the result registers out of their specified physreg.
4125   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4126     CCValAssign &VA = RVLocs[i];
4127     assert(VA.isRegLoc() && "Can only return in registers!");
4128
4129     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4130                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4131     Chain = Val.getValue(1);
4132     InFlag = Val.getValue(2);
4133
4134     switch (VA.getLocInfo()) {
4135     default: llvm_unreachable("Unknown loc info!");
4136     case CCValAssign::Full: break;
4137     case CCValAssign::AExt:
4138       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4139       break;
4140     case CCValAssign::ZExt:
4141       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4142                         DAG.getValueType(VA.getValVT()));
4143       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4144       break;
4145     case CCValAssign::SExt:
4146       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4147                         DAG.getValueType(VA.getValVT()));
4148       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4149       break;
4150     }
4151
4152     InVals.push_back(Val);
4153   }
4154
4155   return Chain;
4156 }
4157
4158 SDValue
4159 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4160                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4161                               SelectionDAG &DAG,
4162                               SmallVector<std::pair<unsigned, SDValue>, 8>
4163                                 &RegsToPass,
4164                               SDValue InFlag, SDValue Chain,
4165                               SDValue CallSeqStart, SDValue &Callee,
4166                               int SPDiff, unsigned NumBytes,
4167                               const SmallVectorImpl<ISD::InputArg> &Ins,
4168                               SmallVectorImpl<SDValue> &InVals,
4169                               ImmutableCallSite *CS) const {
4170
4171   std::vector<EVT> NodeTys;
4172   SmallVector<SDValue, 8> Ops;
4173   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4174                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4175                                  Ops, NodeTys, CS, Subtarget);
4176
4177   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4178   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4179     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4180
4181   // When performing tail call optimization the callee pops its arguments off
4182   // the stack. Account for this here so these bytes can be pushed back on in
4183   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4184   int BytesCalleePops =
4185     (CallConv == CallingConv::Fast &&
4186      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4187
4188   // Add a register mask operand representing the call-preserved registers.
4189   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4190   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
4191   assert(Mask && "Missing call preserved mask for calling convention");
4192   Ops.push_back(DAG.getRegisterMask(Mask));
4193
4194   if (InFlag.getNode())
4195     Ops.push_back(InFlag);
4196
4197   // Emit tail call.
4198   if (isTailCall) {
4199     assert(((Callee.getOpcode() == ISD::Register &&
4200              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4201             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4202             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4203             isa<ConstantSDNode>(Callee)) &&
4204     "Expecting an global address, external symbol, absolute value or register");
4205
4206     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4207   }
4208
4209   // Add a NOP immediately after the branch instruction when using the 64-bit
4210   // SVR4 ABI. At link time, if caller and callee are in a different module and
4211   // thus have a different TOC, the call will be replaced with a call to a stub
4212   // function which saves the current TOC, loads the TOC of the callee and
4213   // branches to the callee. The NOP will be replaced with a load instruction
4214   // which restores the TOC of the caller from the TOC save slot of the current
4215   // stack frame. If caller and callee belong to the same module (and have the
4216   // same TOC), the NOP will remain unchanged.
4217
4218   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4219       !IsPatchPoint) {
4220     if (CallOpc == PPCISD::BCTRL) {
4221       // This is a call through a function pointer.
4222       // Restore the caller TOC from the save area into R2.
4223       // See PrepareCall() for more information about calls through function
4224       // pointers in the 64-bit SVR4 ABI.
4225       // We are using a target-specific load with r2 hard coded, because the
4226       // result of a target-independent load would never go directly into r2,
4227       // since r2 is a reserved register (which prevents the register allocator
4228       // from allocating it), resulting in an additional register being
4229       // allocated and an unnecessary move instruction being generated.
4230       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4231
4232       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4233       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4234       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4235       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4236       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4237
4238       // The address needs to go after the chain input but before the flag (or
4239       // any other variadic arguments).
4240       Ops.insert(std::next(Ops.begin()), AddTOC);
4241     } else if ((CallOpc == PPCISD::CALL) &&
4242                (!isLocalCall(Callee) ||
4243                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4244       // Otherwise insert NOP for non-local calls.
4245       CallOpc = PPCISD::CALL_NOP;
4246   }
4247
4248   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4249   InFlag = Chain.getValue(1);
4250
4251   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4252                              DAG.getIntPtrConstant(BytesCalleePops, true),
4253                              InFlag, dl);
4254   if (!Ins.empty())
4255     InFlag = Chain.getValue(1);
4256
4257   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4258                          Ins, dl, DAG, InVals);
4259 }
4260
4261 SDValue
4262 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4263                              SmallVectorImpl<SDValue> &InVals) const {
4264   SelectionDAG &DAG                     = CLI.DAG;
4265   SDLoc &dl                             = CLI.DL;
4266   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4267   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4268   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4269   SDValue Chain                         = CLI.Chain;
4270   SDValue Callee                        = CLI.Callee;
4271   bool &isTailCall                      = CLI.IsTailCall;
4272   CallingConv::ID CallConv              = CLI.CallConv;
4273   bool isVarArg                         = CLI.IsVarArg;
4274   bool IsPatchPoint                     = CLI.IsPatchPoint;
4275   ImmutableCallSite *CS                 = CLI.CS;
4276
4277   if (isTailCall)
4278     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4279                                                    Ins, DAG);
4280
4281   if (!isTailCall && CS && CS->isMustTailCall())
4282     report_fatal_error("failed to perform tail call elimination on a call "
4283                        "site marked musttail");
4284
4285   if (Subtarget.isSVR4ABI()) {
4286     if (Subtarget.isPPC64())
4287       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4288                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4289                               dl, DAG, InVals, CS);
4290     else
4291       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4292                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4293                               dl, DAG, InVals, CS);
4294   }
4295
4296   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4297                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4298                           dl, DAG, InVals, CS);
4299 }
4300
4301 SDValue
4302 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4303                                     CallingConv::ID CallConv, bool isVarArg,
4304                                     bool isTailCall, bool IsPatchPoint,
4305                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4306                                     const SmallVectorImpl<SDValue> &OutVals,
4307                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4308                                     SDLoc dl, SelectionDAG &DAG,
4309                                     SmallVectorImpl<SDValue> &InVals,
4310                                     ImmutableCallSite *CS) const {
4311   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4312   // of the 32-bit SVR4 ABI stack frame layout.
4313
4314   assert((CallConv == CallingConv::C ||
4315           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4316
4317   unsigned PtrByteSize = 4;
4318
4319   MachineFunction &MF = DAG.getMachineFunction();
4320
4321   // Mark this function as potentially containing a function that contains a
4322   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4323   // and restoring the callers stack pointer in this functions epilog. This is
4324   // done because by tail calling the called function might overwrite the value
4325   // in this function's (MF) stack pointer stack slot 0(SP).
4326   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4327       CallConv == CallingConv::Fast)
4328     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4329
4330   // Count how many bytes are to be pushed on the stack, including the linkage
4331   // area, parameter list area and the part of the local variable space which
4332   // contains copies of aggregates which are passed by value.
4333
4334   // Assign locations to all of the outgoing arguments.
4335   SmallVector<CCValAssign, 16> ArgLocs;
4336   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4337                  *DAG.getContext());
4338
4339   // Reserve space for the linkage area on the stack.
4340   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4341                        PtrByteSize);
4342
4343   if (isVarArg) {
4344     // Handle fixed and variable vector arguments differently.
4345     // Fixed vector arguments go into registers as long as registers are
4346     // available. Variable vector arguments always go into memory.
4347     unsigned NumArgs = Outs.size();
4348
4349     for (unsigned i = 0; i != NumArgs; ++i) {
4350       MVT ArgVT = Outs[i].VT;
4351       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4352       bool Result;
4353
4354       if (Outs[i].IsFixed) {
4355         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4356                                CCInfo);
4357       } else {
4358         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4359                                       ArgFlags, CCInfo);
4360       }
4361
4362       if (Result) {
4363 #ifndef NDEBUG
4364         errs() << "Call operand #" << i << " has unhandled type "
4365              << EVT(ArgVT).getEVTString() << "\n";
4366 #endif
4367         llvm_unreachable(nullptr);
4368       }
4369     }
4370   } else {
4371     // All arguments are treated the same.
4372     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4373   }
4374
4375   // Assign locations to all of the outgoing aggregate by value arguments.
4376   SmallVector<CCValAssign, 16> ByValArgLocs;
4377   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4378                       ByValArgLocs, *DAG.getContext());
4379
4380   // Reserve stack space for the allocations in CCInfo.
4381   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4382
4383   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4384
4385   // Size of the linkage area, parameter list area and the part of the local
4386   // space variable where copies of aggregates which are passed by value are
4387   // stored.
4388   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4389
4390   // Calculate by how many bytes the stack has to be adjusted in case of tail
4391   // call optimization.
4392   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4393
4394   // Adjust the stack pointer for the new arguments...
4395   // These operations are automatically eliminated by the prolog/epilog pass
4396   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4397                                dl);
4398   SDValue CallSeqStart = Chain;
4399
4400   // Load the return address and frame pointer so it can be moved somewhere else
4401   // later.
4402   SDValue LROp, FPOp;
4403   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4404                                        dl);
4405
4406   // Set up a copy of the stack pointer for use loading and storing any
4407   // arguments that may not fit in the registers available for argument
4408   // passing.
4409   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4410
4411   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4412   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4413   SmallVector<SDValue, 8> MemOpChains;
4414
4415   bool seenFloatArg = false;
4416   // Walk the register/memloc assignments, inserting copies/loads.
4417   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4418        i != e;
4419        ++i) {
4420     CCValAssign &VA = ArgLocs[i];
4421     SDValue Arg = OutVals[i];
4422     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4423
4424     if (Flags.isByVal()) {
4425       // Argument is an aggregate which is passed by value, thus we need to
4426       // create a copy of it in the local variable space of the current stack
4427       // frame (which is the stack frame of the caller) and pass the address of
4428       // this copy to the callee.
4429       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4430       CCValAssign &ByValVA = ByValArgLocs[j++];
4431       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4432
4433       // Memory reserved in the local variable space of the callers stack frame.
4434       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4435
4436       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4437       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4438
4439       // Create a copy of the argument in the local area of the current
4440       // stack frame.
4441       SDValue MemcpyCall =
4442         CreateCopyOfByValArgument(Arg, PtrOff,
4443                                   CallSeqStart.getNode()->getOperand(0),
4444                                   Flags, DAG, dl);
4445
4446       // This must go outside the CALLSEQ_START..END.
4447       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4448                            CallSeqStart.getNode()->getOperand(1),
4449                            SDLoc(MemcpyCall));
4450       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4451                              NewCallSeqStart.getNode());
4452       Chain = CallSeqStart = NewCallSeqStart;
4453
4454       // Pass the address of the aggregate copy on the stack either in a
4455       // physical register or in the parameter list area of the current stack
4456       // frame to the callee.
4457       Arg = PtrOff;
4458     }
4459
4460     if (VA.isRegLoc()) {
4461       if (Arg.getValueType() == MVT::i1)
4462         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4463
4464       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4465       // Put argument in a physical register.
4466       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4467     } else {
4468       // Put argument in the parameter list area of the current stack frame.
4469       assert(VA.isMemLoc());
4470       unsigned LocMemOffset = VA.getLocMemOffset();
4471
4472       if (!isTailCall) {
4473         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4474         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4475
4476         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4477                                            MachinePointerInfo(),
4478                                            false, false, 0));
4479       } else {
4480         // Calculate and remember argument location.
4481         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4482                                  TailCallArguments);
4483       }
4484     }
4485   }
4486
4487   if (!MemOpChains.empty())
4488     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4489
4490   // Build a sequence of copy-to-reg nodes chained together with token chain
4491   // and flag operands which copy the outgoing args into the appropriate regs.
4492   SDValue InFlag;
4493   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4494     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4495                              RegsToPass[i].second, InFlag);
4496     InFlag = Chain.getValue(1);
4497   }
4498
4499   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4500   // registers.
4501   if (isVarArg) {
4502     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4503     SDValue Ops[] = { Chain, InFlag };
4504
4505     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4506                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4507
4508     InFlag = Chain.getValue(1);
4509   }
4510
4511   if (isTailCall)
4512     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4513                     false, TailCallArguments);
4514
4515   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4516                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4517                     NumBytes, Ins, InVals, CS);
4518 }
4519
4520 // Copy an argument into memory, being careful to do this outside the
4521 // call sequence for the call to which the argument belongs.
4522 SDValue
4523 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4524                                               SDValue CallSeqStart,
4525                                               ISD::ArgFlagsTy Flags,
4526                                               SelectionDAG &DAG,
4527                                               SDLoc dl) const {
4528   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4529                         CallSeqStart.getNode()->getOperand(0),
4530                         Flags, DAG, dl);
4531   // The MEMCPY must go outside the CALLSEQ_START..END.
4532   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4533                              CallSeqStart.getNode()->getOperand(1),
4534                              SDLoc(MemcpyCall));
4535   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4536                          NewCallSeqStart.getNode());
4537   return NewCallSeqStart;
4538 }
4539
4540 SDValue
4541 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4542                                     CallingConv::ID CallConv, bool isVarArg,
4543                                     bool isTailCall, bool IsPatchPoint,
4544                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4545                                     const SmallVectorImpl<SDValue> &OutVals,
4546                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4547                                     SDLoc dl, SelectionDAG &DAG,
4548                                     SmallVectorImpl<SDValue> &InVals,
4549                                     ImmutableCallSite *CS) const {
4550
4551   bool isELFv2ABI = Subtarget.isELFv2ABI();
4552   bool isLittleEndian = Subtarget.isLittleEndian();
4553   unsigned NumOps = Outs.size();
4554
4555   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4556   unsigned PtrByteSize = 8;
4557
4558   MachineFunction &MF = DAG.getMachineFunction();
4559
4560   // Mark this function as potentially containing a function that contains a
4561   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4562   // and restoring the callers stack pointer in this functions epilog. This is
4563   // done because by tail calling the called function might overwrite the value
4564   // in this function's (MF) stack pointer stack slot 0(SP).
4565   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4566       CallConv == CallingConv::Fast)
4567     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4568
4569   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4570          "fastcc not supported on varargs functions");
4571
4572   // Count how many bytes are to be pushed on the stack, including the linkage
4573   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4574   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4575   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4576   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4577   unsigned NumBytes = LinkageSize;
4578   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4579   unsigned &QFPR_idx = FPR_idx;
4580
4581   static const MCPhysReg GPR[] = {
4582     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4583     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4584   };
4585   static const MCPhysReg VR[] = {
4586     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4587     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4588   };
4589   static const MCPhysReg VSRH[] = {
4590     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4591     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4592   };
4593
4594   const unsigned NumGPRs = array_lengthof(GPR);
4595   const unsigned NumFPRs = 13;
4596   const unsigned NumVRs  = array_lengthof(VR);
4597   const unsigned NumQFPRs = NumFPRs;
4598
4599   // When using the fast calling convention, we don't provide backing for
4600   // arguments that will be in registers.
4601   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4602
4603   // Add up all the space actually used.
4604   for (unsigned i = 0; i != NumOps; ++i) {
4605     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4606     EVT ArgVT = Outs[i].VT;
4607     EVT OrigVT = Outs[i].ArgVT;
4608
4609     if (CallConv == CallingConv::Fast) {
4610       if (Flags.isByVal())
4611         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4612       else
4613         switch (ArgVT.getSimpleVT().SimpleTy) {
4614         default: llvm_unreachable("Unexpected ValueType for argument!");
4615         case MVT::i1:
4616         case MVT::i32:
4617         case MVT::i64:
4618           if (++NumGPRsUsed <= NumGPRs)
4619             continue;
4620           break;
4621         case MVT::v4i32:
4622         case MVT::v8i16:
4623         case MVT::v16i8:
4624         case MVT::v2f64:
4625         case MVT::v2i64:
4626           if (++NumVRsUsed <= NumVRs)
4627             continue;
4628           break;
4629         case MVT::v4f32:
4630           // When using QPX, this is handled like a FP register, otherwise, it
4631           // is an Altivec register.
4632           if (Subtarget.hasQPX()) {
4633             if (++NumFPRsUsed <= NumFPRs)
4634               continue;
4635           } else {
4636             if (++NumVRsUsed <= NumVRs)
4637               continue;
4638           }
4639           break;
4640         case MVT::f32:
4641         case MVT::f64:
4642         case MVT::v4f64: // QPX
4643         case MVT::v4i1:  // QPX
4644           if (++NumFPRsUsed <= NumFPRs)
4645             continue;
4646           break;
4647         }
4648     }
4649
4650     /* Respect alignment of argument on the stack.  */
4651     unsigned Align =
4652       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4653     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4654
4655     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4656     if (Flags.isInConsecutiveRegsLast())
4657       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4658   }
4659
4660   unsigned NumBytesActuallyUsed = NumBytes;
4661
4662   // The prolog code of the callee may store up to 8 GPR argument registers to
4663   // the stack, allowing va_start to index over them in memory if its varargs.
4664   // Because we cannot tell if this is needed on the caller side, we have to
4665   // conservatively assume that it is needed.  As such, make sure we have at
4666   // least enough stack space for the caller to store the 8 GPRs.
4667   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4668   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4669
4670   // Tail call needs the stack to be aligned.
4671   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4672       CallConv == CallingConv::Fast)
4673     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4674
4675   // Calculate by how many bytes the stack has to be adjusted in case of tail
4676   // call optimization.
4677   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4678
4679   // To protect arguments on the stack from being clobbered in a tail call,
4680   // force all the loads to happen before doing any other lowering.
4681   if (isTailCall)
4682     Chain = DAG.getStackArgumentTokenFactor(Chain);
4683
4684   // Adjust the stack pointer for the new arguments...
4685   // These operations are automatically eliminated by the prolog/epilog pass
4686   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4687                                dl);
4688   SDValue CallSeqStart = Chain;
4689
4690   // Load the return address and frame pointer so it can be move somewhere else
4691   // later.
4692   SDValue LROp, FPOp;
4693   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4694                                        dl);
4695
4696   // Set up a copy of the stack pointer for use loading and storing any
4697   // arguments that may not fit in the registers available for argument
4698   // passing.
4699   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4700
4701   // Figure out which arguments are going to go in registers, and which in
4702   // memory.  Also, if this is a vararg function, floating point operations
4703   // must be stored to our stack, and loaded into integer regs as well, if
4704   // any integer regs are available for argument passing.
4705   unsigned ArgOffset = LinkageSize;
4706
4707   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4708   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4709
4710   SmallVector<SDValue, 8> MemOpChains;
4711   for (unsigned i = 0; i != NumOps; ++i) {
4712     SDValue Arg = OutVals[i];
4713     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4714     EVT ArgVT = Outs[i].VT;
4715     EVT OrigVT = Outs[i].ArgVT;
4716
4717     // PtrOff will be used to store the current argument to the stack if a
4718     // register cannot be found for it.
4719     SDValue PtrOff;
4720
4721     // We re-align the argument offset for each argument, except when using the
4722     // fast calling convention, when we need to make sure we do that only when
4723     // we'll actually use a stack slot.
4724     auto ComputePtrOff = [&]() {
4725       /* Respect alignment of argument on the stack.  */
4726       unsigned Align =
4727         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4728       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4729
4730       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4731
4732       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4733     };
4734
4735     if (CallConv != CallingConv::Fast) {
4736       ComputePtrOff();
4737
4738       /* Compute GPR index associated with argument offset.  */
4739       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4740       GPR_idx = std::min(GPR_idx, NumGPRs);
4741     }
4742
4743     // Promote integers to 64-bit values.
4744     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4745       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4746       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4747       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4748     }
4749
4750     // FIXME memcpy is used way more than necessary.  Correctness first.
4751     // Note: "by value" is code for passing a structure by value, not
4752     // basic types.
4753     if (Flags.isByVal()) {
4754       // Note: Size includes alignment padding, so
4755       //   struct x { short a; char b; }
4756       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4757       // These are the proper values we need for right-justifying the
4758       // aggregate in a parameter register.
4759       unsigned Size = Flags.getByValSize();
4760
4761       // An empty aggregate parameter takes up no storage and no
4762       // registers.
4763       if (Size == 0)
4764         continue;
4765
4766       if (CallConv == CallingConv::Fast)
4767         ComputePtrOff();
4768
4769       // All aggregates smaller than 8 bytes must be passed right-justified.
4770       if (Size==1 || Size==2 || Size==4) {
4771         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4772         if (GPR_idx != NumGPRs) {
4773           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4774                                         MachinePointerInfo(), VT,
4775                                         false, false, false, 0);
4776           MemOpChains.push_back(Load.getValue(1));
4777           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4778
4779           ArgOffset += PtrByteSize;
4780           continue;
4781         }
4782       }
4783
4784       if (GPR_idx == NumGPRs && Size < 8) {
4785         SDValue AddPtr = PtrOff;
4786         if (!isLittleEndian) {
4787           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4788                                           PtrOff.getValueType());
4789           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4790         }
4791         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4792                                                           CallSeqStart,
4793                                                           Flags, DAG, dl);
4794         ArgOffset += PtrByteSize;
4795         continue;
4796       }
4797       // Copy entire object into memory.  There are cases where gcc-generated
4798       // code assumes it is there, even if it could be put entirely into
4799       // registers.  (This is not what the doc says.)
4800
4801       // FIXME: The above statement is likely due to a misunderstanding of the
4802       // documents.  All arguments must be copied into the parameter area BY
4803       // THE CALLEE in the event that the callee takes the address of any
4804       // formal argument.  That has not yet been implemented.  However, it is
4805       // reasonable to use the stack area as a staging area for the register
4806       // load.
4807
4808       // Skip this for small aggregates, as we will use the same slot for a
4809       // right-justified copy, below.
4810       if (Size >= 8)
4811         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4812                                                           CallSeqStart,
4813                                                           Flags, DAG, dl);
4814
4815       // When a register is available, pass a small aggregate right-justified.
4816       if (Size < 8 && GPR_idx != NumGPRs) {
4817         // The easiest way to get this right-justified in a register
4818         // is to copy the structure into the rightmost portion of a
4819         // local variable slot, then load the whole slot into the
4820         // register.
4821         // FIXME: The memcpy seems to produce pretty awful code for
4822         // small aggregates, particularly for packed ones.
4823         // FIXME: It would be preferable to use the slot in the
4824         // parameter save area instead of a new local variable.
4825         SDValue AddPtr = PtrOff;
4826         if (!isLittleEndian) {
4827           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4828           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4829         }
4830         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4831                                                           CallSeqStart,
4832                                                           Flags, DAG, dl);
4833
4834         // Load the slot into the register.
4835         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4836                                    MachinePointerInfo(),
4837                                    false, false, false, 0);
4838         MemOpChains.push_back(Load.getValue(1));
4839         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4840
4841         // Done with this argument.
4842         ArgOffset += PtrByteSize;
4843         continue;
4844       }
4845
4846       // For aggregates larger than PtrByteSize, copy the pieces of the
4847       // object that fit into registers from the parameter save area.
4848       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4849         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4850         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4851         if (GPR_idx != NumGPRs) {
4852           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4853                                      MachinePointerInfo(),
4854                                      false, false, false, 0);
4855           MemOpChains.push_back(Load.getValue(1));
4856           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4857           ArgOffset += PtrByteSize;
4858         } else {
4859           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4860           break;
4861         }
4862       }
4863       continue;
4864     }
4865
4866     switch (Arg.getSimpleValueType().SimpleTy) {
4867     default: llvm_unreachable("Unexpected ValueType for argument!");
4868     case MVT::i1:
4869     case MVT::i32:
4870     case MVT::i64:
4871       // These can be scalar arguments or elements of an integer array type
4872       // passed directly.  Clang may use those instead of "byval" aggregate
4873       // types to avoid forcing arguments to memory unnecessarily.
4874       if (GPR_idx != NumGPRs) {
4875         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4876       } else {
4877         if (CallConv == CallingConv::Fast)
4878           ComputePtrOff();
4879
4880         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4881                          true, isTailCall, false, MemOpChains,
4882                          TailCallArguments, dl);
4883         if (CallConv == CallingConv::Fast)
4884           ArgOffset += PtrByteSize;
4885       }
4886       if (CallConv != CallingConv::Fast)
4887         ArgOffset += PtrByteSize;
4888       break;
4889     case MVT::f32:
4890     case MVT::f64: {
4891       // These can be scalar arguments or elements of a float array type
4892       // passed directly.  The latter are used to implement ELFv2 homogenous
4893       // float aggregates.
4894
4895       // Named arguments go into FPRs first, and once they overflow, the
4896       // remaining arguments go into GPRs and then the parameter save area.
4897       // Unnamed arguments for vararg functions always go to GPRs and
4898       // then the parameter save area.  For now, put all arguments to vararg
4899       // routines always in both locations (FPR *and* GPR or stack slot).
4900       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4901       bool NeededLoad = false;
4902
4903       // First load the argument into the next available FPR.
4904       if (FPR_idx != NumFPRs)
4905         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4906
4907       // Next, load the argument into GPR or stack slot if needed.
4908       if (!NeedGPROrStack)
4909         ;
4910       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4911         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4912         // once we support fp <-> gpr moves.
4913
4914         // In the non-vararg case, this can only ever happen in the
4915         // presence of f32 array types, since otherwise we never run
4916         // out of FPRs before running out of GPRs.
4917         SDValue ArgVal;
4918
4919         // Double values are always passed in a single GPR.
4920         if (Arg.getValueType() != MVT::f32) {
4921           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4922
4923         // Non-array float values are extended and passed in a GPR.
4924         } else if (!Flags.isInConsecutiveRegs()) {
4925           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4926           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4927
4928         // If we have an array of floats, we collect every odd element
4929         // together with its predecessor into one GPR.
4930         } else if (ArgOffset % PtrByteSize != 0) {
4931           SDValue Lo, Hi;
4932           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4933           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4934           if (!isLittleEndian)
4935             std::swap(Lo, Hi);
4936           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4937
4938         // The final element, if even, goes into the first half of a GPR.
4939         } else if (Flags.isInConsecutiveRegsLast()) {
4940           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4941           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4942           if (!isLittleEndian)
4943             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4944                                  DAG.getConstant(32, MVT::i32));
4945
4946         // Non-final even elements are skipped; they will be handled
4947         // together the with subsequent argument on the next go-around.
4948         } else
4949           ArgVal = SDValue();
4950
4951         if (ArgVal.getNode())
4952           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4953       } else {
4954         if (CallConv == CallingConv::Fast)
4955           ComputePtrOff();
4956
4957         // Single-precision floating-point values are mapped to the
4958         // second (rightmost) word of the stack doubleword.
4959         if (Arg.getValueType() == MVT::f32 &&
4960             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4961           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4962           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4963         }
4964
4965         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4966                          true, isTailCall, false, MemOpChains,
4967                          TailCallArguments, dl);
4968
4969         NeededLoad = true;
4970       }
4971       // When passing an array of floats, the array occupies consecutive
4972       // space in the argument area; only round up to the next doubleword
4973       // at the end of the array.  Otherwise, each float takes 8 bytes.
4974       if (CallConv != CallingConv::Fast || NeededLoad) {
4975         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4976                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4977         if (Flags.isInConsecutiveRegsLast())
4978           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4979       }
4980       break;
4981     }
4982     case MVT::v4f32:
4983     case MVT::v4i32:
4984     case MVT::v8i16:
4985     case MVT::v16i8:
4986     case MVT::v2f64:
4987     case MVT::v2i64:
4988       if (!Subtarget.hasQPX()) {
4989       // These can be scalar arguments or elements of a vector array type
4990       // passed directly.  The latter are used to implement ELFv2 homogenous
4991       // vector aggregates.
4992
4993       // For a varargs call, named arguments go into VRs or on the stack as
4994       // usual; unnamed arguments always go to the stack or the corresponding
4995       // GPRs when within range.  For now, we always put the value in both
4996       // locations (or even all three).
4997       if (isVarArg) {
4998         // We could elide this store in the case where the object fits
4999         // entirely in R registers.  Maybe later.
5000         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5001                                      MachinePointerInfo(), false, false, 0);
5002         MemOpChains.push_back(Store);
5003         if (VR_idx != NumVRs) {
5004           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5005                                      MachinePointerInfo(),
5006                                      false, false, false, 0);
5007           MemOpChains.push_back(Load.getValue(1));
5008
5009           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5010                            Arg.getSimpleValueType() == MVT::v2i64) ?
5011                           VSRH[VR_idx] : VR[VR_idx];
5012           ++VR_idx;
5013
5014           RegsToPass.push_back(std::make_pair(VReg, Load));
5015         }
5016         ArgOffset += 16;
5017         for (unsigned i=0; i<16; i+=PtrByteSize) {
5018           if (GPR_idx == NumGPRs)
5019             break;
5020           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5021                                   DAG.getConstant(i, PtrVT));
5022           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5023                                      false, false, false, 0);
5024           MemOpChains.push_back(Load.getValue(1));
5025           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5026         }
5027         break;
5028       }
5029
5030       // Non-varargs Altivec params go into VRs or on the stack.
5031       if (VR_idx != NumVRs) {
5032         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5033                          Arg.getSimpleValueType() == MVT::v2i64) ?
5034                         VSRH[VR_idx] : VR[VR_idx];
5035         ++VR_idx;
5036
5037         RegsToPass.push_back(std::make_pair(VReg, Arg));
5038       } else {
5039         if (CallConv == CallingConv::Fast)
5040           ComputePtrOff();
5041
5042         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5043                          true, isTailCall, true, MemOpChains,
5044                          TailCallArguments, dl);
5045         if (CallConv == CallingConv::Fast)
5046           ArgOffset += 16;
5047       }
5048
5049       if (CallConv != CallingConv::Fast)
5050         ArgOffset += 16;
5051       break;
5052       } // not QPX
5053
5054       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5055              "Invalid QPX parameter type");
5056
5057       /* fall through */
5058     case MVT::v4f64:
5059     case MVT::v4i1: {
5060       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5061       if (isVarArg) {
5062         // We could elide this store in the case where the object fits
5063         // entirely in R registers.  Maybe later.
5064         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5065                                      MachinePointerInfo(), false, false, 0);
5066         MemOpChains.push_back(Store);
5067         if (QFPR_idx != NumQFPRs) {
5068           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5069                                      Store, PtrOff, MachinePointerInfo(),
5070                                      false, false, false, 0);
5071           MemOpChains.push_back(Load.getValue(1));
5072           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5073         }
5074         ArgOffset += (IsF32 ? 16 : 32);
5075         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5076           if (GPR_idx == NumGPRs)
5077             break;
5078           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5079                                   DAG.getConstant(i, PtrVT));
5080           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5081                                      false, false, false, 0);
5082           MemOpChains.push_back(Load.getValue(1));
5083           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5084         }
5085         break;
5086       }
5087
5088       // Non-varargs QPX params go into registers or on the stack.
5089       if (QFPR_idx != NumQFPRs) {
5090         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5091       } else {
5092         if (CallConv == CallingConv::Fast)
5093           ComputePtrOff();
5094
5095         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5096                          true, isTailCall, true, MemOpChains,
5097                          TailCallArguments, dl);
5098         if (CallConv == CallingConv::Fast)
5099           ArgOffset += (IsF32 ? 16 : 32);
5100       }
5101
5102       if (CallConv != CallingConv::Fast)
5103         ArgOffset += (IsF32 ? 16 : 32);
5104       break;
5105       }
5106     }
5107   }
5108
5109   assert(NumBytesActuallyUsed == ArgOffset);
5110   (void)NumBytesActuallyUsed;
5111
5112   if (!MemOpChains.empty())
5113     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5114
5115   // Check if this is an indirect call (MTCTR/BCTRL).
5116   // See PrepareCall() for more information about calls through function
5117   // pointers in the 64-bit SVR4 ABI.
5118   if (!isTailCall && !IsPatchPoint &&
5119       !isFunctionGlobalAddress(Callee) &&
5120       !isa<ExternalSymbolSDNode>(Callee)) {
5121     // Load r2 into a virtual register and store it to the TOC save area.
5122     setUsesTOCBasePtr(DAG);
5123     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5124     // TOC save area offset.
5125     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5126     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5127     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5128     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5129                          MachinePointerInfo::getStack(TOCSaveOffset),
5130                          false, false, 0);
5131     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5132     // This does not mean the MTCTR instruction must use R12; it's easier
5133     // to model this as an extra parameter, so do that.
5134     if (isELFv2ABI && !IsPatchPoint)
5135       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5136   }
5137
5138   // Build a sequence of copy-to-reg nodes chained together with token chain
5139   // and flag operands which copy the outgoing args into the appropriate regs.
5140   SDValue InFlag;
5141   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5142     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5143                              RegsToPass[i].second, InFlag);
5144     InFlag = Chain.getValue(1);
5145   }
5146
5147   if (isTailCall)
5148     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5149                     FPOp, true, TailCallArguments);
5150
5151   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5152                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5153                     NumBytes, Ins, InVals, CS);
5154 }
5155
5156 SDValue
5157 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5158                                     CallingConv::ID CallConv, bool isVarArg,
5159                                     bool isTailCall, bool IsPatchPoint,
5160                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5161                                     const SmallVectorImpl<SDValue> &OutVals,
5162                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5163                                     SDLoc dl, SelectionDAG &DAG,
5164                                     SmallVectorImpl<SDValue> &InVals,
5165                                     ImmutableCallSite *CS) const {
5166
5167   unsigned NumOps = Outs.size();
5168
5169   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5170   bool isPPC64 = PtrVT == MVT::i64;
5171   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5172
5173   MachineFunction &MF = DAG.getMachineFunction();
5174
5175   // Mark this function as potentially containing a function that contains a
5176   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5177   // and restoring the callers stack pointer in this functions epilog. This is
5178   // done because by tail calling the called function might overwrite the value
5179   // in this function's (MF) stack pointer stack slot 0(SP).
5180   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5181       CallConv == CallingConv::Fast)
5182     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5183
5184   // Count how many bytes are to be pushed on the stack, including the linkage
5185   // area, and parameter passing area.  We start with 24/48 bytes, which is
5186   // prereserved space for [SP][CR][LR][3 x unused].
5187   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5188   unsigned NumBytes = LinkageSize;
5189
5190   // Add up all the space actually used.
5191   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5192   // they all go in registers, but we must reserve stack space for them for
5193   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5194   // assigned stack space in order, with padding so Altivec parameters are
5195   // 16-byte aligned.
5196   unsigned nAltivecParamsAtEnd = 0;
5197   for (unsigned i = 0; i != NumOps; ++i) {
5198     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5199     EVT ArgVT = Outs[i].VT;
5200     // Varargs Altivec parameters are padded to a 16 byte boundary.
5201     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5202         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5203         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5204       if (!isVarArg && !isPPC64) {
5205         // Non-varargs Altivec parameters go after all the non-Altivec
5206         // parameters; handle those later so we know how much padding we need.
5207         nAltivecParamsAtEnd++;
5208         continue;
5209       }
5210       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5211       NumBytes = ((NumBytes+15)/16)*16;
5212     }
5213     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5214   }
5215
5216   // Allow for Altivec parameters at the end, if needed.
5217   if (nAltivecParamsAtEnd) {
5218     NumBytes = ((NumBytes+15)/16)*16;
5219     NumBytes += 16*nAltivecParamsAtEnd;
5220   }
5221
5222   // The prolog code of the callee may store up to 8 GPR argument registers to
5223   // the stack, allowing va_start to index over them in memory if its varargs.
5224   // Because we cannot tell if this is needed on the caller side, we have to
5225   // conservatively assume that it is needed.  As such, make sure we have at
5226   // least enough stack space for the caller to store the 8 GPRs.
5227   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5228
5229   // Tail call needs the stack to be aligned.
5230   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5231       CallConv == CallingConv::Fast)
5232     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5233
5234   // Calculate by how many bytes the stack has to be adjusted in case of tail
5235   // call optimization.
5236   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5237
5238   // To protect arguments on the stack from being clobbered in a tail call,
5239   // force all the loads to happen before doing any other lowering.
5240   if (isTailCall)
5241     Chain = DAG.getStackArgumentTokenFactor(Chain);
5242
5243   // Adjust the stack pointer for the new arguments...
5244   // These operations are automatically eliminated by the prolog/epilog pass
5245   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5246                                dl);
5247   SDValue CallSeqStart = Chain;
5248
5249   // Load the return address and frame pointer so it can be move somewhere else
5250   // later.
5251   SDValue LROp, FPOp;
5252   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5253                                        dl);
5254
5255   // Set up a copy of the stack pointer for use loading and storing any
5256   // arguments that may not fit in the registers available for argument
5257   // passing.
5258   SDValue StackPtr;
5259   if (isPPC64)
5260     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5261   else
5262     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5263
5264   // Figure out which arguments are going to go in registers, and which in
5265   // memory.  Also, if this is a vararg function, floating point operations
5266   // must be stored to our stack, and loaded into integer regs as well, if
5267   // any integer regs are available for argument passing.
5268   unsigned ArgOffset = LinkageSize;
5269   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5270
5271   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5272     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5273     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5274   };
5275   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5276     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5277     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5278   };
5279   static const MCPhysReg VR[] = {
5280     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5281     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5282   };
5283   const unsigned NumGPRs = array_lengthof(GPR_32);
5284   const unsigned NumFPRs = 13;
5285   const unsigned NumVRs  = array_lengthof(VR);
5286
5287   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5288
5289   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5290   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5291
5292   SmallVector<SDValue, 8> MemOpChains;
5293   for (unsigned i = 0; i != NumOps; ++i) {
5294     SDValue Arg = OutVals[i];
5295     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5296
5297     // PtrOff will be used to store the current argument to the stack if a
5298     // register cannot be found for it.
5299     SDValue PtrOff;
5300
5301     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5302
5303     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5304
5305     // On PPC64, promote integers to 64-bit values.
5306     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5307       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5308       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5309       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5310     }
5311
5312     // FIXME memcpy is used way more than necessary.  Correctness first.
5313     // Note: "by value" is code for passing a structure by value, not
5314     // basic types.
5315     if (Flags.isByVal()) {
5316       unsigned Size = Flags.getByValSize();
5317       // Very small objects are passed right-justified.  Everything else is
5318       // passed left-justified.
5319       if (Size==1 || Size==2) {
5320         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5321         if (GPR_idx != NumGPRs) {
5322           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5323                                         MachinePointerInfo(), VT,
5324                                         false, false, false, 0);
5325           MemOpChains.push_back(Load.getValue(1));
5326           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5327
5328           ArgOffset += PtrByteSize;
5329         } else {
5330           SDValue Const = DAG.getConstant(PtrByteSize - Size,
5331                                           PtrOff.getValueType());
5332           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5333           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5334                                                             CallSeqStart,
5335                                                             Flags, DAG, dl);
5336           ArgOffset += PtrByteSize;
5337         }
5338         continue;
5339       }
5340       // Copy entire object into memory.  There are cases where gcc-generated
5341       // code assumes it is there, even if it could be put entirely into
5342       // registers.  (This is not what the doc says.)
5343       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5344                                                         CallSeqStart,
5345                                                         Flags, DAG, dl);
5346
5347       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5348       // copy the pieces of the object that fit into registers from the
5349       // parameter save area.
5350       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5351         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5352         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5353         if (GPR_idx != NumGPRs) {
5354           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5355                                      MachinePointerInfo(),
5356                                      false, false, false, 0);
5357           MemOpChains.push_back(Load.getValue(1));
5358           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5359           ArgOffset += PtrByteSize;
5360         } else {
5361           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5362           break;
5363         }
5364       }
5365       continue;
5366     }
5367
5368     switch (Arg.getSimpleValueType().SimpleTy) {
5369     default: llvm_unreachable("Unexpected ValueType for argument!");
5370     case MVT::i1:
5371     case MVT::i32:
5372     case MVT::i64:
5373       if (GPR_idx != NumGPRs) {
5374         if (Arg.getValueType() == MVT::i1)
5375           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5376
5377         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5378       } else {
5379         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5380                          isPPC64, isTailCall, false, MemOpChains,
5381                          TailCallArguments, dl);
5382       }
5383       ArgOffset += PtrByteSize;
5384       break;
5385     case MVT::f32:
5386     case MVT::f64:
5387       if (FPR_idx != NumFPRs) {
5388         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5389
5390         if (isVarArg) {
5391           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5392                                        MachinePointerInfo(), false, false, 0);
5393           MemOpChains.push_back(Store);
5394
5395           // Float varargs are always shadowed in available integer registers
5396           if (GPR_idx != NumGPRs) {
5397             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5398                                        MachinePointerInfo(), false, false,
5399                                        false, 0);
5400             MemOpChains.push_back(Load.getValue(1));
5401             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5402           }
5403           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5404             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5405             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5406             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5407                                        MachinePointerInfo(),
5408                                        false, false, false, 0);
5409             MemOpChains.push_back(Load.getValue(1));
5410             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5411           }
5412         } else {
5413           // If we have any FPRs remaining, we may also have GPRs remaining.
5414           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5415           // GPRs.
5416           if (GPR_idx != NumGPRs)
5417             ++GPR_idx;
5418           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5419               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5420             ++GPR_idx;
5421         }
5422       } else
5423         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5424                          isPPC64, isTailCall, false, MemOpChains,
5425                          TailCallArguments, dl);
5426       if (isPPC64)
5427         ArgOffset += 8;
5428       else
5429         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5430       break;
5431     case MVT::v4f32:
5432     case MVT::v4i32:
5433     case MVT::v8i16:
5434     case MVT::v16i8:
5435       if (isVarArg) {
5436         // These go aligned on the stack, or in the corresponding R registers
5437         // when within range.  The Darwin PPC ABI doc claims they also go in
5438         // V registers; in fact gcc does this only for arguments that are
5439         // prototyped, not for those that match the ...  We do it for all
5440         // arguments, seems to work.
5441         while (ArgOffset % 16 !=0) {
5442           ArgOffset += PtrByteSize;
5443           if (GPR_idx != NumGPRs)
5444             GPR_idx++;
5445         }
5446         // We could elide this store in the case where the object fits
5447         // entirely in R registers.  Maybe later.
5448         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5449                             DAG.getConstant(ArgOffset, PtrVT));
5450         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5451                                      MachinePointerInfo(), false, false, 0);
5452         MemOpChains.push_back(Store);
5453         if (VR_idx != NumVRs) {
5454           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5455                                      MachinePointerInfo(),
5456                                      false, false, false, 0);
5457           MemOpChains.push_back(Load.getValue(1));
5458           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5459         }
5460         ArgOffset += 16;
5461         for (unsigned i=0; i<16; i+=PtrByteSize) {
5462           if (GPR_idx == NumGPRs)
5463             break;
5464           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5465                                   DAG.getConstant(i, PtrVT));
5466           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5467                                      false, false, false, 0);
5468           MemOpChains.push_back(Load.getValue(1));
5469           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5470         }
5471         break;
5472       }
5473
5474       // Non-varargs Altivec params generally go in registers, but have
5475       // stack space allocated at the end.
5476       if (VR_idx != NumVRs) {
5477         // Doesn't have GPR space allocated.
5478         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5479       } else if (nAltivecParamsAtEnd==0) {
5480         // We are emitting Altivec params in order.
5481         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5482                          isPPC64, isTailCall, true, MemOpChains,
5483                          TailCallArguments, dl);
5484         ArgOffset += 16;
5485       }
5486       break;
5487     }
5488   }
5489   // If all Altivec parameters fit in registers, as they usually do,
5490   // they get stack space following the non-Altivec parameters.  We
5491   // don't track this here because nobody below needs it.
5492   // If there are more Altivec parameters than fit in registers emit
5493   // the stores here.
5494   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5495     unsigned j = 0;
5496     // Offset is aligned; skip 1st 12 params which go in V registers.
5497     ArgOffset = ((ArgOffset+15)/16)*16;
5498     ArgOffset += 12*16;
5499     for (unsigned i = 0; i != NumOps; ++i) {
5500       SDValue Arg = OutVals[i];
5501       EVT ArgType = Outs[i].VT;
5502       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5503           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5504         if (++j > NumVRs) {
5505           SDValue PtrOff;
5506           // We are emitting Altivec params in order.
5507           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5508                            isPPC64, isTailCall, true, MemOpChains,
5509                            TailCallArguments, dl);
5510           ArgOffset += 16;
5511         }
5512       }
5513     }
5514   }
5515
5516   if (!MemOpChains.empty())
5517     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5518
5519   // On Darwin, R12 must contain the address of an indirect callee.  This does
5520   // not mean the MTCTR instruction must use R12; it's easier to model this as
5521   // an extra parameter, so do that.
5522   if (!isTailCall &&
5523       !isFunctionGlobalAddress(Callee) &&
5524       !isa<ExternalSymbolSDNode>(Callee) &&
5525       !isBLACompatibleAddress(Callee, DAG))
5526     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5527                                                    PPC::R12), Callee));
5528
5529   // Build a sequence of copy-to-reg nodes chained together with token chain
5530   // and flag operands which copy the outgoing args into the appropriate regs.
5531   SDValue InFlag;
5532   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5533     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5534                              RegsToPass[i].second, InFlag);
5535     InFlag = Chain.getValue(1);
5536   }
5537
5538   if (isTailCall)
5539     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5540                     FPOp, true, TailCallArguments);
5541
5542   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5543                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5544                     NumBytes, Ins, InVals, CS);
5545 }
5546
5547 bool
5548 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5549                                   MachineFunction &MF, bool isVarArg,
5550                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5551                                   LLVMContext &Context) const {
5552   SmallVector<CCValAssign, 16> RVLocs;
5553   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5554   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5555 }
5556
5557 SDValue
5558 PPCTargetLowering::LowerReturn(SDValue Chain,
5559                                CallingConv::ID CallConv, bool isVarArg,
5560                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5561                                const SmallVectorImpl<SDValue> &OutVals,
5562                                SDLoc dl, SelectionDAG &DAG) const {
5563
5564   SmallVector<CCValAssign, 16> RVLocs;
5565   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5566                  *DAG.getContext());
5567   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5568
5569   SDValue Flag;
5570   SmallVector<SDValue, 4> RetOps(1, Chain);
5571
5572   // Copy the result values into the output registers.
5573   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5574     CCValAssign &VA = RVLocs[i];
5575     assert(VA.isRegLoc() && "Can only return in registers!");
5576
5577     SDValue Arg = OutVals[i];
5578
5579     switch (VA.getLocInfo()) {
5580     default: llvm_unreachable("Unknown loc info!");
5581     case CCValAssign::Full: break;
5582     case CCValAssign::AExt:
5583       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5584       break;
5585     case CCValAssign::ZExt:
5586       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5587       break;
5588     case CCValAssign::SExt:
5589       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5590       break;
5591     }
5592
5593     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5594     Flag = Chain.getValue(1);
5595     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5596   }
5597
5598   RetOps[0] = Chain;  // Update chain.
5599
5600   // Add the flag if we have it.
5601   if (Flag.getNode())
5602     RetOps.push_back(Flag);
5603
5604   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5605 }
5606
5607 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5608                                    const PPCSubtarget &Subtarget) const {
5609   // When we pop the dynamic allocation we need to restore the SP link.
5610   SDLoc dl(Op);
5611
5612   // Get the corect type for pointers.
5613   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5614
5615   // Construct the stack pointer operand.
5616   bool isPPC64 = Subtarget.isPPC64();
5617   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5618   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5619
5620   // Get the operands for the STACKRESTORE.
5621   SDValue Chain = Op.getOperand(0);
5622   SDValue SaveSP = Op.getOperand(1);
5623
5624   // Load the old link SP.
5625   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5626                                    MachinePointerInfo(),
5627                                    false, false, false, 0);
5628
5629   // Restore the stack pointer.
5630   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5631
5632   // Store the old link SP.
5633   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5634                       false, false, 0);
5635 }
5636
5637
5638
5639 SDValue
5640 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5641   MachineFunction &MF = DAG.getMachineFunction();
5642   bool isPPC64 = Subtarget.isPPC64();
5643   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5644
5645   // Get current frame pointer save index.  The users of this index will be
5646   // primarily DYNALLOC instructions.
5647   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5648   int RASI = FI->getReturnAddrSaveIndex();
5649
5650   // If the frame pointer save index hasn't been defined yet.
5651   if (!RASI) {
5652     // Find out what the fix offset of the frame pointer save area.
5653     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5654     // Allocate the frame index for frame pointer save area.
5655     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5656     // Save the result.
5657     FI->setReturnAddrSaveIndex(RASI);
5658   }
5659   return DAG.getFrameIndex(RASI, PtrVT);
5660 }
5661
5662 SDValue
5663 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5664   MachineFunction &MF = DAG.getMachineFunction();
5665   bool isPPC64 = Subtarget.isPPC64();
5666   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5667
5668   // Get current frame pointer save index.  The users of this index will be
5669   // primarily DYNALLOC instructions.
5670   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5671   int FPSI = FI->getFramePointerSaveIndex();
5672
5673   // If the frame pointer save index hasn't been defined yet.
5674   if (!FPSI) {
5675     // Find out what the fix offset of the frame pointer save area.
5676     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5677     // Allocate the frame index for frame pointer save area.
5678     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5679     // Save the result.
5680     FI->setFramePointerSaveIndex(FPSI);
5681   }
5682   return DAG.getFrameIndex(FPSI, PtrVT);
5683 }
5684
5685 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5686                                          SelectionDAG &DAG,
5687                                          const PPCSubtarget &Subtarget) const {
5688   // Get the inputs.
5689   SDValue Chain = Op.getOperand(0);
5690   SDValue Size  = Op.getOperand(1);
5691   SDLoc dl(Op);
5692
5693   // Get the corect type for pointers.
5694   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5695   // Negate the size.
5696   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5697                                   DAG.getConstant(0, PtrVT), Size);
5698   // Construct a node for the frame pointer save index.
5699   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5700   // Build a DYNALLOC node.
5701   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5702   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5703   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5704 }
5705
5706 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5707                                                SelectionDAG &DAG) const {
5708   SDLoc DL(Op);
5709   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5710                      DAG.getVTList(MVT::i32, MVT::Other),
5711                      Op.getOperand(0), Op.getOperand(1));
5712 }
5713
5714 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5715                                                 SelectionDAG &DAG) const {
5716   SDLoc DL(Op);
5717   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5718                      Op.getOperand(0), Op.getOperand(1));
5719 }
5720
5721 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5722   if (Op.getValueType().isVector())
5723     return LowerVectorLoad(Op, DAG);
5724
5725   assert(Op.getValueType() == MVT::i1 &&
5726          "Custom lowering only for i1 loads");
5727
5728   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5729
5730   SDLoc dl(Op);
5731   LoadSDNode *LD = cast<LoadSDNode>(Op);
5732
5733   SDValue Chain = LD->getChain();
5734   SDValue BasePtr = LD->getBasePtr();
5735   MachineMemOperand *MMO = LD->getMemOperand();
5736
5737   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5738                                  BasePtr, MVT::i8, MMO);
5739   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5740
5741   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5742   return DAG.getMergeValues(Ops, dl);
5743 }
5744
5745 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5746   if (Op.getOperand(1).getValueType().isVector())
5747     return LowerVectorStore(Op, DAG);
5748
5749   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5750          "Custom lowering only for i1 stores");
5751
5752   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5753
5754   SDLoc dl(Op);
5755   StoreSDNode *ST = cast<StoreSDNode>(Op);
5756
5757   SDValue Chain = ST->getChain();
5758   SDValue BasePtr = ST->getBasePtr();
5759   SDValue Value = ST->getValue();
5760   MachineMemOperand *MMO = ST->getMemOperand();
5761
5762   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5763   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5764 }
5765
5766 // FIXME: Remove this once the ANDI glue bug is fixed:
5767 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5768   assert(Op.getValueType() == MVT::i1 &&
5769          "Custom lowering only for i1 results");
5770
5771   SDLoc DL(Op);
5772   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5773                      Op.getOperand(0));
5774 }
5775
5776 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5777 /// possible.
5778 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5779   // Not FP? Not a fsel.
5780   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5781       !Op.getOperand(2).getValueType().isFloatingPoint())
5782     return Op;
5783
5784   // We might be able to do better than this under some circumstances, but in
5785   // general, fsel-based lowering of select is a finite-math-only optimization.
5786   // For more information, see section F.3 of the 2.06 ISA specification.
5787   if (!DAG.getTarget().Options.NoInfsFPMath ||
5788       !DAG.getTarget().Options.NoNaNsFPMath)
5789     return Op;
5790
5791   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5792
5793   EVT ResVT = Op.getValueType();
5794   EVT CmpVT = Op.getOperand(0).getValueType();
5795   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5796   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5797   SDLoc dl(Op);
5798
5799   // If the RHS of the comparison is a 0.0, we don't need to do the
5800   // subtraction at all.
5801   SDValue Sel1;
5802   if (isFloatingPointZero(RHS))
5803     switch (CC) {
5804     default: break;       // SETUO etc aren't handled by fsel.
5805     case ISD::SETNE:
5806       std::swap(TV, FV);
5807     case ISD::SETEQ:
5808       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5809         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5810       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5811       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5812         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5813       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5814                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5815     case ISD::SETULT:
5816     case ISD::SETLT:
5817       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5818     case ISD::SETOGE:
5819     case ISD::SETGE:
5820       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5821         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5822       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5823     case ISD::SETUGT:
5824     case ISD::SETGT:
5825       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5826     case ISD::SETOLE:
5827     case ISD::SETLE:
5828       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5829         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5830       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5831                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5832     }
5833
5834   SDValue Cmp;
5835   switch (CC) {
5836   default: break;       // SETUO etc aren't handled by fsel.
5837   case ISD::SETNE:
5838     std::swap(TV, FV);
5839   case ISD::SETEQ:
5840     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5841     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5842       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5843     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5844     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5845       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5846     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5847                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5848   case ISD::SETULT:
5849   case ISD::SETLT:
5850     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5851     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5852       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5853     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5854   case ISD::SETOGE:
5855   case ISD::SETGE:
5856     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5857     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5858       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5859     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5860   case ISD::SETUGT:
5861   case ISD::SETGT:
5862     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5863     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5864       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5865     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5866   case ISD::SETOLE:
5867   case ISD::SETLE:
5868     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5869     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5870       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5871     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5872   }
5873   return Op;
5874 }
5875
5876 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5877                                                SelectionDAG &DAG,
5878                                                SDLoc dl) const {
5879   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5880   SDValue Src = Op.getOperand(0);
5881   if (Src.getValueType() == MVT::f32)
5882     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5883
5884   SDValue Tmp;
5885   switch (Op.getSimpleValueType().SimpleTy) {
5886   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5887   case MVT::i32:
5888     Tmp = DAG.getNode(
5889         Op.getOpcode() == ISD::FP_TO_SINT
5890             ? PPCISD::FCTIWZ
5891             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5892         dl, MVT::f64, Src);
5893     break;
5894   case MVT::i64:
5895     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5896            "i64 FP_TO_UINT is supported only with FPCVT");
5897     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5898                                                         PPCISD::FCTIDUZ,
5899                       dl, MVT::f64, Src);
5900     break;
5901   }
5902
5903   // Convert the FP value to an int value through memory.
5904   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5905     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5906   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5907   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5908   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5909
5910   // Emit a store to the stack slot.
5911   SDValue Chain;
5912   if (i32Stack) {
5913     MachineFunction &MF = DAG.getMachineFunction();
5914     MachineMemOperand *MMO =
5915       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5916     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5917     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5918               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5919   } else
5920     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5921                          MPI, false, false, 0);
5922
5923   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5924   // add in a bias.
5925   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5926     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5927                         DAG.getConstant(4, FIPtr.getValueType()));
5928     MPI = MPI.getWithOffset(4);
5929   }
5930
5931   RLI.Chain = Chain;
5932   RLI.Ptr = FIPtr;
5933   RLI.MPI = MPI;
5934 }
5935
5936 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5937                                           SDLoc dl) const {
5938   ReuseLoadInfo RLI;
5939   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5940
5941   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5942                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5943                      RLI.Ranges);
5944 }
5945
5946 // We're trying to insert a regular store, S, and then a load, L. If the
5947 // incoming value, O, is a load, we might just be able to have our load use the
5948 // address used by O. However, we don't know if anything else will store to
5949 // that address before we can load from it. To prevent this situation, we need
5950 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5951 // the same chain operand as O, we create a token factor from the chain results
5952 // of O and L, and we replace all uses of O's chain result with that token
5953 // factor (see spliceIntoChain below for this last part).
5954 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5955                                             ReuseLoadInfo &RLI,
5956                                             SelectionDAG &DAG,
5957                                             ISD::LoadExtType ET) const {
5958   SDLoc dl(Op);
5959   if (ET == ISD::NON_EXTLOAD &&
5960       (Op.getOpcode() == ISD::FP_TO_UINT ||
5961        Op.getOpcode() == ISD::FP_TO_SINT) &&
5962       isOperationLegalOrCustom(Op.getOpcode(),
5963                                Op.getOperand(0).getValueType())) {
5964
5965     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5966     return true;
5967   }
5968
5969   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5970   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5971       LD->isNonTemporal())
5972     return false;
5973   if (LD->getMemoryVT() != MemVT)
5974     return false;
5975
5976   RLI.Ptr = LD->getBasePtr();
5977   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5978     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5979            "Non-pre-inc AM on PPC?");
5980     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5981                           LD->getOffset());
5982   }
5983
5984   RLI.Chain = LD->getChain();
5985   RLI.MPI = LD->getPointerInfo();
5986   RLI.IsInvariant = LD->isInvariant();
5987   RLI.Alignment = LD->getAlignment();
5988   RLI.AAInfo = LD->getAAInfo();
5989   RLI.Ranges = LD->getRanges();
5990
5991   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5992   return true;
5993 }
5994
5995 // Given the head of the old chain, ResChain, insert a token factor containing
5996 // it and NewResChain, and make users of ResChain now be users of that token
5997 // factor.
5998 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5999                                         SDValue NewResChain,
6000                                         SelectionDAG &DAG) const {
6001   if (!ResChain)
6002     return;
6003
6004   SDLoc dl(NewResChain);
6005
6006   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6007                            NewResChain, DAG.getUNDEF(MVT::Other));
6008   assert(TF.getNode() != NewResChain.getNode() &&
6009          "A new TF really is required here");
6010
6011   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6012   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6013 }
6014
6015 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6016                                           SelectionDAG &DAG) const {
6017   SDLoc dl(Op);
6018
6019   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6020     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6021       return SDValue();
6022
6023     SDValue Value = Op.getOperand(0);
6024     // The values are now known to be -1 (false) or 1 (true). To convert this
6025     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6026     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6027     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6028   
6029     SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6030     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6031                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6032   
6033     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6034
6035     if (Op.getValueType() != MVT::v4f64)
6036       Value = DAG.getNode(ISD::FP_ROUND, dl,
6037                           Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6038     return Value;
6039   }
6040
6041   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6042   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6043     return SDValue();
6044
6045   if (Op.getOperand(0).getValueType() == MVT::i1)
6046     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6047                        DAG.getConstantFP(1.0, Op.getValueType()),
6048                        DAG.getConstantFP(0.0, Op.getValueType()));
6049
6050   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6051          "UINT_TO_FP is supported only with FPCVT");
6052
6053   // If we have FCFIDS, then use it when converting to single-precision.
6054   // Otherwise, convert to double-precision and then round.
6055   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6056                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6057                                                             : PPCISD::FCFIDS)
6058                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6059                                                             : PPCISD::FCFID);
6060   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6061                   ? MVT::f32
6062                   : MVT::f64;
6063
6064   if (Op.getOperand(0).getValueType() == MVT::i64) {
6065     SDValue SINT = Op.getOperand(0);
6066     // When converting to single-precision, we actually need to convert
6067     // to double-precision first and then round to single-precision.
6068     // To avoid double-rounding effects during that operation, we have
6069     // to prepare the input operand.  Bits that might be truncated when
6070     // converting to double-precision are replaced by a bit that won't
6071     // be lost at this stage, but is below the single-precision rounding
6072     // position.
6073     //
6074     // However, if -enable-unsafe-fp-math is in effect, accept double
6075     // rounding to avoid the extra overhead.
6076     if (Op.getValueType() == MVT::f32 &&
6077         !Subtarget.hasFPCVT() &&
6078         !DAG.getTarget().Options.UnsafeFPMath) {
6079
6080       // Twiddle input to make sure the low 11 bits are zero.  (If this
6081       // is the case, we are guaranteed the value will fit into the 53 bit
6082       // mantissa of an IEEE double-precision value without rounding.)
6083       // If any of those low 11 bits were not zero originally, make sure
6084       // bit 12 (value 2048) is set instead, so that the final rounding
6085       // to single-precision gets the correct result.
6086       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6087                                   SINT, DAG.getConstant(2047, MVT::i64));
6088       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6089                           Round, DAG.getConstant(2047, MVT::i64));
6090       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6091       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6092                           Round, DAG.getConstant(-2048, MVT::i64));
6093
6094       // However, we cannot use that value unconditionally: if the magnitude
6095       // of the input value is small, the bit-twiddling we did above might
6096       // end up visibly changing the output.  Fortunately, in that case, we
6097       // don't need to twiddle bits since the original input will convert
6098       // exactly to double-precision floating-point already.  Therefore,
6099       // construct a conditional to use the original value if the top 11
6100       // bits are all sign-bit copies, and use the rounded value computed
6101       // above otherwise.
6102       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6103                                  SINT, DAG.getConstant(53, MVT::i32));
6104       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6105                          Cond, DAG.getConstant(1, MVT::i64));
6106       Cond = DAG.getSetCC(dl, MVT::i32,
6107                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6108
6109       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6110     }
6111
6112     ReuseLoadInfo RLI;
6113     SDValue Bits;
6114
6115     MachineFunction &MF = DAG.getMachineFunction();
6116     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6117       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6118                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6119                          RLI.Ranges);
6120       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6121     } else if (Subtarget.hasLFIWAX() &&
6122                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6123       MachineMemOperand *MMO =
6124         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6125                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6126       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6127       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6128                                      DAG.getVTList(MVT::f64, MVT::Other),
6129                                      Ops, MVT::i32, MMO);
6130       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6131     } else if (Subtarget.hasFPCVT() &&
6132                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6133       MachineMemOperand *MMO =
6134         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6135                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6136       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6137       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6138                                      DAG.getVTList(MVT::f64, MVT::Other),
6139                                      Ops, MVT::i32, MMO);
6140       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6141     } else if (((Subtarget.hasLFIWAX() &&
6142                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6143                 (Subtarget.hasFPCVT() &&
6144                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6145                SINT.getOperand(0).getValueType() == MVT::i32) {
6146       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6147       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6148
6149       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6150       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6151
6152       SDValue Store =
6153         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6154                      MachinePointerInfo::getFixedStack(FrameIdx),
6155                      false, false, 0);
6156
6157       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6158              "Expected an i32 store");
6159
6160       RLI.Ptr = FIdx;
6161       RLI.Chain = Store;
6162       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6163       RLI.Alignment = 4;
6164
6165       MachineMemOperand *MMO =
6166         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6167                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6168       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6169       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6170                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6171                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6172                                      Ops, MVT::i32, MMO);
6173     } else
6174       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6175
6176     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6177
6178     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6179       FP = DAG.getNode(ISD::FP_ROUND, dl,
6180                        MVT::f32, FP, DAG.getIntPtrConstant(0));
6181     return FP;
6182   }
6183
6184   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6185          "Unhandled INT_TO_FP type in custom expander!");
6186   // Since we only generate this in 64-bit mode, we can take advantage of
6187   // 64-bit registers.  In particular, sign extend the input value into the
6188   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6189   // then lfd it and fcfid it.
6190   MachineFunction &MF = DAG.getMachineFunction();
6191   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6192   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6193
6194   SDValue Ld;
6195   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6196     ReuseLoadInfo RLI;
6197     bool ReusingLoad;
6198     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6199                                             DAG))) {
6200       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6201       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6202
6203       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6204                                    MachinePointerInfo::getFixedStack(FrameIdx),
6205                                    false, false, 0);
6206
6207       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6208              "Expected an i32 store");
6209
6210       RLI.Ptr = FIdx;
6211       RLI.Chain = Store;
6212       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6213       RLI.Alignment = 4;
6214     }
6215
6216     MachineMemOperand *MMO =
6217       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6218                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6219     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6220     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6221                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6222                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6223                                  Ops, MVT::i32, MMO);
6224     if (ReusingLoad)
6225       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6226   } else {
6227     assert(Subtarget.isPPC64() &&
6228            "i32->FP without LFIWAX supported only on PPC64");
6229
6230     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6231     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6232
6233     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6234                                 Op.getOperand(0));
6235
6236     // STD the extended value into the stack slot.
6237     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6238                                  MachinePointerInfo::getFixedStack(FrameIdx),
6239                                  false, false, 0);
6240
6241     // Load the value as a double.
6242     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6243                      MachinePointerInfo::getFixedStack(FrameIdx),
6244                      false, false, false, 0);
6245   }
6246
6247   // FCFID it and return it.
6248   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6249   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6250     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6251   return FP;
6252 }
6253
6254 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6255                                             SelectionDAG &DAG) const {
6256   SDLoc dl(Op);
6257   /*
6258    The rounding mode is in bits 30:31 of FPSR, and has the following
6259    settings:
6260      00 Round to nearest
6261      01 Round to 0
6262      10 Round to +inf
6263      11 Round to -inf
6264
6265   FLT_ROUNDS, on the other hand, expects the following:
6266     -1 Undefined
6267      0 Round to 0
6268      1 Round to nearest
6269      2 Round to +inf
6270      3 Round to -inf
6271
6272   To perform the conversion, we do:
6273     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6274   */
6275
6276   MachineFunction &MF = DAG.getMachineFunction();
6277   EVT VT = Op.getValueType();
6278   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6279
6280   // Save FP Control Word to register
6281   EVT NodeTys[] = {
6282     MVT::f64,    // return register
6283     MVT::Glue    // unused in this context
6284   };
6285   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6286
6287   // Save FP register to stack slot
6288   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6289   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6290   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6291                                StackSlot, MachinePointerInfo(), false, false,0);
6292
6293   // Load FP Control Word from low 32 bits of stack slot.
6294   SDValue Four = DAG.getConstant(4, PtrVT);
6295   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6296   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6297                             false, false, false, 0);
6298
6299   // Transform as necessary
6300   SDValue CWD1 =
6301     DAG.getNode(ISD::AND, dl, MVT::i32,
6302                 CWD, DAG.getConstant(3, MVT::i32));
6303   SDValue CWD2 =
6304     DAG.getNode(ISD::SRL, dl, MVT::i32,
6305                 DAG.getNode(ISD::AND, dl, MVT::i32,
6306                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6307                                         CWD, DAG.getConstant(3, MVT::i32)),
6308                             DAG.getConstant(3, MVT::i32)),
6309                 DAG.getConstant(1, MVT::i32));
6310
6311   SDValue RetVal =
6312     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6313
6314   return DAG.getNode((VT.getSizeInBits() < 16 ?
6315                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6316 }
6317
6318 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6319   EVT VT = Op.getValueType();
6320   unsigned BitWidth = VT.getSizeInBits();
6321   SDLoc dl(Op);
6322   assert(Op.getNumOperands() == 3 &&
6323          VT == Op.getOperand(1).getValueType() &&
6324          "Unexpected SHL!");
6325
6326   // Expand into a bunch of logical ops.  Note that these ops
6327   // depend on the PPC behavior for oversized shift amounts.
6328   SDValue Lo = Op.getOperand(0);
6329   SDValue Hi = Op.getOperand(1);
6330   SDValue Amt = Op.getOperand(2);
6331   EVT AmtVT = Amt.getValueType();
6332
6333   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6334                              DAG.getConstant(BitWidth, AmtVT), Amt);
6335   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6336   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6337   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6338   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6339                              DAG.getConstant(-BitWidth, AmtVT));
6340   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6341   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6342   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6343   SDValue OutOps[] = { OutLo, OutHi };
6344   return DAG.getMergeValues(OutOps, dl);
6345 }
6346
6347 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6348   EVT VT = Op.getValueType();
6349   SDLoc dl(Op);
6350   unsigned BitWidth = VT.getSizeInBits();
6351   assert(Op.getNumOperands() == 3 &&
6352          VT == Op.getOperand(1).getValueType() &&
6353          "Unexpected SRL!");
6354
6355   // Expand into a bunch of logical ops.  Note that these ops
6356   // depend on the PPC behavior for oversized shift amounts.
6357   SDValue Lo = Op.getOperand(0);
6358   SDValue Hi = Op.getOperand(1);
6359   SDValue Amt = Op.getOperand(2);
6360   EVT AmtVT = Amt.getValueType();
6361
6362   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6363                              DAG.getConstant(BitWidth, AmtVT), Amt);
6364   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6365   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6366   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6367   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6368                              DAG.getConstant(-BitWidth, AmtVT));
6369   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6370   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6371   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6372   SDValue OutOps[] = { OutLo, OutHi };
6373   return DAG.getMergeValues(OutOps, dl);
6374 }
6375
6376 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6377   SDLoc dl(Op);
6378   EVT VT = Op.getValueType();
6379   unsigned BitWidth = VT.getSizeInBits();
6380   assert(Op.getNumOperands() == 3 &&
6381          VT == Op.getOperand(1).getValueType() &&
6382          "Unexpected SRA!");
6383
6384   // Expand into a bunch of logical ops, followed by a select_cc.
6385   SDValue Lo = Op.getOperand(0);
6386   SDValue Hi = Op.getOperand(1);
6387   SDValue Amt = Op.getOperand(2);
6388   EVT AmtVT = Amt.getValueType();
6389
6390   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6391                              DAG.getConstant(BitWidth, AmtVT), Amt);
6392   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6393   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6394   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6395   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6396                              DAG.getConstant(-BitWidth, AmtVT));
6397   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6398   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6399   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6400                                   Tmp4, Tmp6, ISD::SETLE);
6401   SDValue OutOps[] = { OutLo, OutHi };
6402   return DAG.getMergeValues(OutOps, dl);
6403 }
6404
6405 //===----------------------------------------------------------------------===//
6406 // Vector related lowering.
6407 //
6408
6409 /// BuildSplatI - Build a canonical splati of Val with an element size of
6410 /// SplatSize.  Cast the result to VT.
6411 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6412                              SelectionDAG &DAG, SDLoc dl) {
6413   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6414
6415   static const MVT VTys[] = { // canonical VT to use for each size.
6416     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6417   };
6418
6419   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6420
6421   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6422   if (Val == -1)
6423     SplatSize = 1;
6424
6425   EVT CanonicalVT = VTys[SplatSize-1];
6426
6427   // Build a canonical splat for this value.
6428   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6429   SmallVector<SDValue, 8> Ops;
6430   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6431   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6432   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6433 }
6434
6435 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6436 /// specified intrinsic ID.
6437 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6438                                 SelectionDAG &DAG, SDLoc dl,
6439                                 EVT DestVT = MVT::Other) {
6440   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6441   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6442                      DAG.getConstant(IID, MVT::i32), Op);
6443 }
6444
6445 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6446 /// specified intrinsic ID.
6447 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6448                                 SelectionDAG &DAG, SDLoc dl,
6449                                 EVT DestVT = MVT::Other) {
6450   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6451   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6452                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6453 }
6454
6455 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6456 /// specified intrinsic ID.
6457 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6458                                 SDValue Op2, SelectionDAG &DAG,
6459                                 SDLoc dl, EVT DestVT = MVT::Other) {
6460   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6461   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6462                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6463 }
6464
6465
6466 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6467 /// amount.  The result has the specified value type.
6468 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6469                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6470   // Force LHS/RHS to be the right type.
6471   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6472   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6473
6474   int Ops[16];
6475   for (unsigned i = 0; i != 16; ++i)
6476     Ops[i] = i + Amt;
6477   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6478   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6479 }
6480
6481 // If this is a case we can't handle, return null and let the default
6482 // expansion code take care of it.  If we CAN select this case, and if it
6483 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6484 // this case more efficiently than a constant pool load, lower it to the
6485 // sequence of ops that should be used.
6486 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6487                                              SelectionDAG &DAG) const {
6488   SDLoc dl(Op);
6489   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6490   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6491
6492   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6493     // We first build an i32 vector, load it into a QPX register,
6494     // then convert it to a floating-point vector and compare it
6495     // to a zero vector to get the boolean result.
6496     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6497     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6498     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6499     EVT PtrVT = getPointerTy();
6500     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6501
6502     assert(BVN->getNumOperands() == 4 &&
6503       "BUILD_VECTOR for v4i1 does not have 4 operands");
6504
6505     bool IsConst = true;
6506     for (unsigned i = 0; i < 4; ++i) {
6507       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6508       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6509         IsConst = false;
6510         break;
6511       }
6512     }
6513
6514     if (IsConst) {
6515       Constant *One =
6516         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6517       Constant *NegOne =
6518         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6519
6520       SmallVector<Constant*, 4> CV(4, NegOne);
6521       for (unsigned i = 0; i < 4; ++i) {
6522         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6523           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6524         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6525                    getConstantIntValue()->isZero())
6526           continue;
6527         else
6528           CV[i] = One;
6529       }
6530
6531       Constant *CP = ConstantVector::get(CV);
6532       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6533                       16 /* alignment */);
6534  
6535       SmallVector<SDValue, 2> Ops;
6536       Ops.push_back(DAG.getEntryNode());
6537       Ops.push_back(CPIdx);
6538
6539       SmallVector<EVT, 2> ValueVTs;
6540       ValueVTs.push_back(MVT::v4i1);
6541       ValueVTs.push_back(MVT::Other); // chain
6542       SDVTList VTs = DAG.getVTList(ValueVTs);
6543
6544       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6545         dl, VTs, Ops, MVT::v4f32,
6546         MachinePointerInfo::getConstantPool());
6547     }
6548
6549     SmallVector<SDValue, 4> Stores;
6550     for (unsigned i = 0; i < 4; ++i) {
6551       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6552
6553       unsigned Offset = 4*i;
6554       SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6555       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6556
6557       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6558       if (StoreSize > 4) {
6559         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6560                                            BVN->getOperand(i), Idx,
6561                                            PtrInfo.getWithOffset(Offset),
6562                                            MVT::i32, false, false, 0));
6563       } else {
6564         SDValue StoreValue = BVN->getOperand(i);
6565         if (StoreSize < 4)
6566           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6567
6568         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6569                                       StoreValue, Idx,
6570                                       PtrInfo.getWithOffset(Offset),
6571                                       false, false, 0));
6572       }
6573     }
6574
6575     SDValue StoreChain;
6576     if (!Stores.empty())
6577       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6578     else
6579       StoreChain = DAG.getEntryNode();
6580
6581     // Now load from v4i32 into the QPX register; this will extend it to
6582     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6583     // is typed as v4f64 because the QPX register integer states are not
6584     // explicitly represented.
6585
6586     SmallVector<SDValue, 2> Ops;
6587     Ops.push_back(StoreChain);
6588     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6589     Ops.push_back(FIdx);
6590
6591     SmallVector<EVT, 2> ValueVTs;
6592     ValueVTs.push_back(MVT::v4f64);
6593     ValueVTs.push_back(MVT::Other); // chain
6594     SDVTList VTs = DAG.getVTList(ValueVTs);
6595
6596     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6597       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6598     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6599       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6600       LoadedVect);
6601
6602     SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6603     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6604                           FPZeros, FPZeros, FPZeros, FPZeros);
6605
6606     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6607   }
6608
6609   // All other QPX vectors are handled by generic code.
6610   if (Subtarget.hasQPX())
6611     return SDValue();
6612
6613   // Check if this is a splat of a constant value.
6614   APInt APSplatBits, APSplatUndef;
6615   unsigned SplatBitSize;
6616   bool HasAnyUndefs;
6617   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6618                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6619     return SDValue();
6620
6621   unsigned SplatBits = APSplatBits.getZExtValue();
6622   unsigned SplatUndef = APSplatUndef.getZExtValue();
6623   unsigned SplatSize = SplatBitSize / 8;
6624
6625   // First, handle single instruction cases.
6626
6627   // All zeros?
6628   if (SplatBits == 0) {
6629     // Canonicalize all zero vectors to be v4i32.
6630     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6631       SDValue Z = DAG.getConstant(0, MVT::i32);
6632       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6633       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6634     }
6635     return Op;
6636   }
6637
6638   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6639   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6640                     (32-SplatBitSize));
6641   if (SextVal >= -16 && SextVal <= 15)
6642     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6643
6644
6645   // Two instruction sequences.
6646
6647   // If this value is in the range [-32,30] and is even, use:
6648   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6649   // If this value is in the range [17,31] and is odd, use:
6650   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6651   // If this value is in the range [-31,-17] and is odd, use:
6652   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6653   // Note the last two are three-instruction sequences.
6654   if (SextVal >= -32 && SextVal <= 31) {
6655     // To avoid having these optimizations undone by constant folding,
6656     // we convert to a pseudo that will be expanded later into one of
6657     // the above forms.
6658     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6659     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6660               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6661     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6662     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6663     if (VT == Op.getValueType())
6664       return RetVal;
6665     else
6666       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6667   }
6668
6669   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6670   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6671   // for fneg/fabs.
6672   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6673     // Make -1 and vspltisw -1:
6674     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6675
6676     // Make the VSLW intrinsic, computing 0x8000_0000.
6677     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6678                                    OnesV, DAG, dl);
6679
6680     // xor by OnesV to invert it.
6681     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6682     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6683   }
6684
6685   // The remaining cases assume either big endian element order or
6686   // a splat-size that equates to the element size of the vector
6687   // to be built.  An example that doesn't work for little endian is
6688   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6689   // and a vector element size of 16 bits.  The code below will
6690   // produce the vector in big endian element order, which for little
6691   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6692
6693   // For now, just avoid these optimizations in that case.
6694   // FIXME: Develop correct optimizations for LE with mismatched
6695   // splat and element sizes.
6696
6697   if (Subtarget.isLittleEndian() &&
6698       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6699     return SDValue();
6700
6701   // Check to see if this is a wide variety of vsplti*, binop self cases.
6702   static const signed char SplatCsts[] = {
6703     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6704     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6705   };
6706
6707   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6708     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6709     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6710     int i = SplatCsts[idx];
6711
6712     // Figure out what shift amount will be used by altivec if shifted by i in
6713     // this splat size.
6714     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6715
6716     // vsplti + shl self.
6717     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6718       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6719       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6720         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6721         Intrinsic::ppc_altivec_vslw
6722       };
6723       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6724       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6725     }
6726
6727     // vsplti + srl self.
6728     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6729       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6730       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6731         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6732         Intrinsic::ppc_altivec_vsrw
6733       };
6734       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6735       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6736     }
6737
6738     // vsplti + sra self.
6739     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6740       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6741       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6742         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6743         Intrinsic::ppc_altivec_vsraw
6744       };
6745       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6746       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6747     }
6748
6749     // vsplti + rol self.
6750     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6751                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6752       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6753       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6754         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6755         Intrinsic::ppc_altivec_vrlw
6756       };
6757       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6758       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6759     }
6760
6761     // t = vsplti c, result = vsldoi t, t, 1
6762     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6763       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6764       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6765     }
6766     // t = vsplti c, result = vsldoi t, t, 2
6767     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6768       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6769       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6770     }
6771     // t = vsplti c, result = vsldoi t, t, 3
6772     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6773       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6774       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6775     }
6776   }
6777
6778   return SDValue();
6779 }
6780
6781 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6782 /// the specified operations to build the shuffle.
6783 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6784                                       SDValue RHS, SelectionDAG &DAG,
6785                                       SDLoc dl) {
6786   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6787   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6788   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6789
6790   enum {
6791     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6792     OP_VMRGHW,
6793     OP_VMRGLW,
6794     OP_VSPLTISW0,
6795     OP_VSPLTISW1,
6796     OP_VSPLTISW2,
6797     OP_VSPLTISW3,
6798     OP_VSLDOI4,
6799     OP_VSLDOI8,
6800     OP_VSLDOI12
6801   };
6802
6803   if (OpNum == OP_COPY) {
6804     if (LHSID == (1*9+2)*9+3) return LHS;
6805     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6806     return RHS;
6807   }
6808
6809   SDValue OpLHS, OpRHS;
6810   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6811   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6812
6813   int ShufIdxs[16];
6814   switch (OpNum) {
6815   default: llvm_unreachable("Unknown i32 permute!");
6816   case OP_VMRGHW:
6817     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6818     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6819     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6820     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6821     break;
6822   case OP_VMRGLW:
6823     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6824     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6825     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6826     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6827     break;
6828   case OP_VSPLTISW0:
6829     for (unsigned i = 0; i != 16; ++i)
6830       ShufIdxs[i] = (i&3)+0;
6831     break;
6832   case OP_VSPLTISW1:
6833     for (unsigned i = 0; i != 16; ++i)
6834       ShufIdxs[i] = (i&3)+4;
6835     break;
6836   case OP_VSPLTISW2:
6837     for (unsigned i = 0; i != 16; ++i)
6838       ShufIdxs[i] = (i&3)+8;
6839     break;
6840   case OP_VSPLTISW3:
6841     for (unsigned i = 0; i != 16; ++i)
6842       ShufIdxs[i] = (i&3)+12;
6843     break;
6844   case OP_VSLDOI4:
6845     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6846   case OP_VSLDOI8:
6847     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6848   case OP_VSLDOI12:
6849     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6850   }
6851   EVT VT = OpLHS.getValueType();
6852   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6853   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6854   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6855   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6856 }
6857
6858 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6859 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6860 /// return the code it can be lowered into.  Worst case, it can always be
6861 /// lowered into a vperm.
6862 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6863                                                SelectionDAG &DAG) const {
6864   SDLoc dl(Op);
6865   SDValue V1 = Op.getOperand(0);
6866   SDValue V2 = Op.getOperand(1);
6867   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6868   EVT VT = Op.getValueType();
6869   bool isLittleEndian = Subtarget.isLittleEndian();
6870
6871   if (Subtarget.hasQPX()) {
6872     if (VT.getVectorNumElements() != 4)
6873       return SDValue();
6874
6875     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6876
6877     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6878     if (AlignIdx != -1) {
6879       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6880                          DAG.getConstant(AlignIdx, MVT::i32));
6881     } else if (SVOp->isSplat()) {
6882       int SplatIdx = SVOp->getSplatIndex();
6883       if (SplatIdx >= 4) {
6884         std::swap(V1, V2);
6885         SplatIdx -= 4;
6886       }
6887
6888       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6889       // nothing to do.
6890
6891       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6892                          DAG.getConstant(SplatIdx, MVT::i32));
6893     }
6894
6895     // Lower this into a qvgpci/qvfperm pair.
6896
6897     // Compute the qvgpci literal
6898     unsigned idx = 0;
6899     for (unsigned i = 0; i < 4; ++i) {
6900       int m = SVOp->getMaskElt(i);
6901       unsigned mm = m >= 0 ? (unsigned) m : i;
6902       idx |= mm << (3-i)*3;
6903     }
6904
6905     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6906                              DAG.getConstant(idx, MVT::i32));
6907     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6908   }
6909
6910   // Cases that are handled by instructions that take permute immediates
6911   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6912   // selected by the instruction selector.
6913   if (V2.getOpcode() == ISD::UNDEF) {
6914     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6915         PPC::isSplatShuffleMask(SVOp, 2) ||
6916         PPC::isSplatShuffleMask(SVOp, 4) ||
6917         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6918         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6919         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6920         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6921         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6922         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6923         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6924         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6925         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6926       return Op;
6927     }
6928   }
6929
6930   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6931   // and produce a fixed permutation.  If any of these match, do not lower to
6932   // VPERM.
6933   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6934   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6935       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6936       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6937       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6938       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6939       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6940       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6941       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6942       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6943     return Op;
6944
6945   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6946   // perfect shuffle table to emit an optimal matching sequence.
6947   ArrayRef<int> PermMask = SVOp->getMask();
6948
6949   unsigned PFIndexes[4];
6950   bool isFourElementShuffle = true;
6951   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6952     unsigned EltNo = 8;   // Start out undef.
6953     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6954       if (PermMask[i*4+j] < 0)
6955         continue;   // Undef, ignore it.
6956
6957       unsigned ByteSource = PermMask[i*4+j];
6958       if ((ByteSource & 3) != j) {
6959         isFourElementShuffle = false;
6960         break;
6961       }
6962
6963       if (EltNo == 8) {
6964         EltNo = ByteSource/4;
6965       } else if (EltNo != ByteSource/4) {
6966         isFourElementShuffle = false;
6967         break;
6968       }
6969     }
6970     PFIndexes[i] = EltNo;
6971   }
6972
6973   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6974   // perfect shuffle vector to determine if it is cost effective to do this as
6975   // discrete instructions, or whether we should use a vperm.
6976   // For now, we skip this for little endian until such time as we have a
6977   // little-endian perfect shuffle table.
6978   if (isFourElementShuffle && !isLittleEndian) {
6979     // Compute the index in the perfect shuffle table.
6980     unsigned PFTableIndex =
6981       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6982
6983     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6984     unsigned Cost  = (PFEntry >> 30);
6985
6986     // Determining when to avoid vperm is tricky.  Many things affect the cost
6987     // of vperm, particularly how many times the perm mask needs to be computed.
6988     // For example, if the perm mask can be hoisted out of a loop or is already
6989     // used (perhaps because there are multiple permutes with the same shuffle
6990     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6991     // the loop requires an extra register.
6992     //
6993     // As a compromise, we only emit discrete instructions if the shuffle can be
6994     // generated in 3 or fewer operations.  When we have loop information
6995     // available, if this block is within a loop, we should avoid using vperm
6996     // for 3-operation perms and use a constant pool load instead.
6997     if (Cost < 3)
6998       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6999   }
7000
7001   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7002   // vector that will get spilled to the constant pool.
7003   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7004
7005   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7006   // that it is in input element units, not in bytes.  Convert now.
7007
7008   // For little endian, the order of the input vectors is reversed, and
7009   // the permutation mask is complemented with respect to 31.  This is
7010   // necessary to produce proper semantics with the big-endian-biased vperm
7011   // instruction.
7012   EVT EltVT = V1.getValueType().getVectorElementType();
7013   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7014
7015   SmallVector<SDValue, 16> ResultMask;
7016   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7017     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7018
7019     for (unsigned j = 0; j != BytesPerElement; ++j)
7020       if (isLittleEndian)
7021         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7022                                              MVT::i32));
7023       else
7024         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7025                                              MVT::i32));
7026   }
7027
7028   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7029                                   ResultMask);
7030   if (isLittleEndian)
7031     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7032                        V2, V1, VPermMask);
7033   else
7034     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7035                        V1, V2, VPermMask);
7036 }
7037
7038 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7039 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7040 /// information about the intrinsic.
7041 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7042                                   bool &isDot, const PPCSubtarget &Subtarget) {
7043   unsigned IntrinsicID =
7044     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7045   CompareOpc = -1;
7046   isDot = false;
7047   switch (IntrinsicID) {
7048   default: return false;
7049     // Comparison predicates.
7050   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7051   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7052   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7053   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7054   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7055   case Intrinsic::ppc_altivec_vcmpequd_p: 
7056     if (Subtarget.hasP8Altivec()) {
7057       CompareOpc = 199; 
7058       isDot = 1; 
7059     }
7060     else 
7061       return false;
7062
7063     break;
7064   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7065   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7066   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7067   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7068   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7069   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7070     if (Subtarget.hasP8Altivec()) {
7071       CompareOpc = 967; 
7072       isDot = 1; 
7073     }
7074     else 
7075       return false;
7076
7077     break;
7078   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7079   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7080   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7081   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7082     if (Subtarget.hasP8Altivec()) {
7083       CompareOpc = 711; 
7084       isDot = 1; 
7085     }
7086     else 
7087       return false;
7088
7089     break;
7090       
7091     // Normal Comparisons.
7092   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7093   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7094   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7095   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7096   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7097   case Intrinsic::ppc_altivec_vcmpequd:
7098     if (Subtarget.hasP8Altivec()) {
7099       CompareOpc = 199; 
7100       isDot = 0; 
7101     }
7102     else
7103       return false;
7104
7105     break;
7106   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7107   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7108   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7109   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7110   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7111   case Intrinsic::ppc_altivec_vcmpgtsd:   
7112     if (Subtarget.hasP8Altivec()) {
7113       CompareOpc = 967; 
7114       isDot = 0; 
7115     }
7116     else
7117       return false;
7118
7119     break;
7120   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7121   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7122   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7123   case Intrinsic::ppc_altivec_vcmpgtud:   
7124     if (Subtarget.hasP8Altivec()) {
7125       CompareOpc = 711; 
7126       isDot = 0; 
7127     }
7128     else
7129       return false;
7130
7131     break;
7132   }
7133   return true;
7134 }
7135
7136 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7137 /// lower, do it, otherwise return null.
7138 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7139                                                    SelectionDAG &DAG) const {
7140   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7141   // opcode number of the comparison.
7142   SDLoc dl(Op);
7143   int CompareOpc;
7144   bool isDot;
7145   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7146     return SDValue();    // Don't custom lower most intrinsics.
7147
7148   // If this is a non-dot comparison, make the VCMP node and we are done.
7149   if (!isDot) {
7150     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7151                               Op.getOperand(1), Op.getOperand(2),
7152                               DAG.getConstant(CompareOpc, MVT::i32));
7153     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7154   }
7155
7156   // Create the PPCISD altivec 'dot' comparison node.
7157   SDValue Ops[] = {
7158     Op.getOperand(2),  // LHS
7159     Op.getOperand(3),  // RHS
7160     DAG.getConstant(CompareOpc, MVT::i32)
7161   };
7162   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7163   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7164
7165   // Now that we have the comparison, emit a copy from the CR to a GPR.
7166   // This is flagged to the above dot comparison.
7167   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7168                                 DAG.getRegister(PPC::CR6, MVT::i32),
7169                                 CompNode.getValue(1));
7170
7171   // Unpack the result based on how the target uses it.
7172   unsigned BitNo;   // Bit # of CR6.
7173   bool InvertBit;   // Invert result?
7174   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7175   default:  // Can't happen, don't crash on invalid number though.
7176   case 0:   // Return the value of the EQ bit of CR6.
7177     BitNo = 0; InvertBit = false;
7178     break;
7179   case 1:   // Return the inverted value of the EQ bit of CR6.
7180     BitNo = 0; InvertBit = true;
7181     break;
7182   case 2:   // Return the value of the LT bit of CR6.
7183     BitNo = 2; InvertBit = false;
7184     break;
7185   case 3:   // Return the inverted value of the LT bit of CR6.
7186     BitNo = 2; InvertBit = true;
7187     break;
7188   }
7189
7190   // Shift the bit into the low position.
7191   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7192                       DAG.getConstant(8-(3-BitNo), MVT::i32));
7193   // Isolate the bit.
7194   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7195                       DAG.getConstant(1, MVT::i32));
7196
7197   // If we are supposed to, toggle the bit.
7198   if (InvertBit)
7199     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7200                         DAG.getConstant(1, MVT::i32));
7201   return Flags;
7202 }
7203
7204 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7205                                                   SelectionDAG &DAG) const {
7206   SDLoc dl(Op);
7207   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7208   // instructions), but for smaller types, we need to first extend up to v2i32
7209   // before doing going farther.
7210   if (Op.getValueType() == MVT::v2i64) {
7211     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7212     if (ExtVT != MVT::v2i32) {
7213       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7214       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7215                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7216                                         ExtVT.getVectorElementType(), 4)));
7217       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7218       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7219                        DAG.getValueType(MVT::v2i32));
7220     }
7221
7222     return Op;
7223   }
7224
7225   return SDValue();
7226 }
7227
7228 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7229                                                    SelectionDAG &DAG) const {
7230   SDLoc dl(Op);
7231   // Create a stack slot that is 16-byte aligned.
7232   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7233   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7234   EVT PtrVT = getPointerTy();
7235   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7236
7237   // Store the input value into Value#0 of the stack slot.
7238   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7239                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7240                                false, false, 0);
7241   // Load it out.
7242   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7243                      false, false, false, 0);
7244 }
7245
7246 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7247                                                    SelectionDAG &DAG) const {
7248   SDLoc dl(Op);
7249   SDNode *N = Op.getNode();
7250
7251   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7252          "Unknown extract_vector_elt type");
7253
7254   SDValue Value = N->getOperand(0);
7255
7256   // The first part of this is like the store lowering except that we don't
7257   // need to track the chain.
7258
7259   // The values are now known to be -1 (false) or 1 (true). To convert this
7260   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7261   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7262   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7263
7264   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7265   // understand how to form the extending load.
7266   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7267   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7268                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7269
7270   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7271
7272   // Now convert to an integer and store.
7273   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7274     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7275     Value);
7276
7277   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7278   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7279   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7280   EVT PtrVT = getPointerTy();
7281   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7282
7283   SDValue StoreChain = DAG.getEntryNode();
7284   SmallVector<SDValue, 2> Ops;
7285   Ops.push_back(StoreChain);
7286   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7287   Ops.push_back(Value);
7288   Ops.push_back(FIdx);
7289
7290   SmallVector<EVT, 2> ValueVTs;
7291   ValueVTs.push_back(MVT::Other); // chain
7292   SDVTList VTs = DAG.getVTList(ValueVTs);
7293
7294   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7295     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7296
7297   // Extract the value requested.
7298   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7299   SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7300   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7301
7302   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7303                                PtrInfo.getWithOffset(Offset),
7304                                false, false, false, 0);
7305
7306   if (!Subtarget.useCRBits())
7307     return IntVal;
7308
7309   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7310 }
7311
7312 /// Lowering for QPX v4i1 loads
7313 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7314                                            SelectionDAG &DAG) const {
7315   SDLoc dl(Op);
7316   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7317   SDValue LoadChain = LN->getChain();
7318   SDValue BasePtr = LN->getBasePtr();
7319
7320   if (Op.getValueType() == MVT::v4f64 ||
7321       Op.getValueType() == MVT::v4f32) {
7322     EVT MemVT = LN->getMemoryVT();
7323     unsigned Alignment = LN->getAlignment();
7324
7325     // If this load is properly aligned, then it is legal.
7326     if (Alignment >= MemVT.getStoreSize())
7327       return Op;
7328
7329     EVT ScalarVT = Op.getValueType().getScalarType(),
7330         ScalarMemVT = MemVT.getScalarType();
7331     unsigned Stride = ScalarMemVT.getStoreSize();
7332
7333     SmallVector<SDValue, 8> Vals, LoadChains;
7334     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7335       SDValue Load;
7336       if (ScalarVT != ScalarMemVT)
7337         Load =
7338           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7339                          BasePtr,
7340                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7341                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7342                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7343                          LN->getAAInfo());
7344       else
7345         Load =
7346           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7347                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7348                        LN->isVolatile(), LN->isNonTemporal(),
7349                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7350                        LN->getAAInfo());
7351
7352       if (Idx == 0 && LN->isIndexed()) {
7353         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7354                "Unknown addressing mode on vector load");
7355         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7356                                   LN->getAddressingMode());
7357       }
7358
7359       Vals.push_back(Load);
7360       LoadChains.push_back(Load.getValue(1));
7361
7362       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7363                             DAG.getConstant(Stride, BasePtr.getValueType()));
7364     }
7365
7366     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7367     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7368                                    Op.getValueType(), Vals);
7369
7370     if (LN->isIndexed()) {
7371       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7372       return DAG.getMergeValues(RetOps, dl);
7373     }
7374
7375     SDValue RetOps[] = { Value, TF };
7376     return DAG.getMergeValues(RetOps, dl);
7377   }
7378
7379   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7380   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7381
7382   // To lower v4i1 from a byte array, we load the byte elements of the
7383   // vector and then reuse the BUILD_VECTOR logic.
7384
7385   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7386   for (unsigned i = 0; i < 4; ++i) {
7387     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7388     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7389
7390     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7391                         dl, MVT::i32, LoadChain, Idx,
7392                         LN->getPointerInfo().getWithOffset(i),
7393                         MVT::i8 /* memory type */,
7394                         LN->isVolatile(), LN->isNonTemporal(),
7395                         LN->isInvariant(),
7396                         1 /* alignment */, LN->getAAInfo()));
7397     VectElmtChains.push_back(VectElmts[i].getValue(1));
7398   }
7399
7400   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7401   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7402
7403   SDValue RVals[] = { Value, LoadChain };
7404   return DAG.getMergeValues(RVals, dl);
7405 }
7406
7407 /// Lowering for QPX v4i1 stores
7408 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7409                                             SelectionDAG &DAG) const {
7410   SDLoc dl(Op);
7411   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7412   SDValue StoreChain = SN->getChain();
7413   SDValue BasePtr = SN->getBasePtr();
7414   SDValue Value = SN->getValue();
7415
7416   if (Value.getValueType() == MVT::v4f64 ||
7417       Value.getValueType() == MVT::v4f32) {
7418     EVT MemVT = SN->getMemoryVT();
7419     unsigned Alignment = SN->getAlignment();
7420
7421     // If this store is properly aligned, then it is legal.
7422     if (Alignment >= MemVT.getStoreSize())
7423       return Op;
7424
7425     EVT ScalarVT = Value.getValueType().getScalarType(),
7426         ScalarMemVT = MemVT.getScalarType();
7427     unsigned Stride = ScalarMemVT.getStoreSize();
7428
7429     SmallVector<SDValue, 8> Stores;
7430     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7431       SDValue Ex =
7432         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7433                     DAG.getConstant(Idx, getVectorIdxTy()));
7434       SDValue Store;
7435       if (ScalarVT != ScalarMemVT)
7436         Store =
7437           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7438                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7439                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7440                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7441       else
7442         Store =
7443           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7444                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7445                        SN->isVolatile(), SN->isNonTemporal(),
7446                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7447
7448       if (Idx == 0 && SN->isIndexed()) {
7449         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7450                "Unknown addressing mode on vector store");
7451         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7452                                     SN->getAddressingMode());
7453       }
7454
7455       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7456                             DAG.getConstant(Stride, BasePtr.getValueType()));
7457       Stores.push_back(Store);
7458     }
7459
7460     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7461
7462     if (SN->isIndexed()) {
7463       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7464       return DAG.getMergeValues(RetOps, dl);
7465     }
7466
7467     return TF;
7468   }
7469
7470   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7471   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7472
7473   // The values are now known to be -1 (false) or 1 (true). To convert this
7474   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7475   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7476   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7477
7478   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7479   // understand how to form the extending load.
7480   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7481   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7482                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7483
7484   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7485
7486   // Now convert to an integer and store.
7487   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7488     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7489     Value);
7490
7491   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7492   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7493   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7494   EVT PtrVT = getPointerTy();
7495   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7496
7497   SmallVector<SDValue, 2> Ops;
7498   Ops.push_back(StoreChain);
7499   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7500   Ops.push_back(Value);
7501   Ops.push_back(FIdx);
7502
7503   SmallVector<EVT, 2> ValueVTs;
7504   ValueVTs.push_back(MVT::Other); // chain
7505   SDVTList VTs = DAG.getVTList(ValueVTs);
7506
7507   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7508     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7509
7510   // Move data into the byte array.
7511   SmallVector<SDValue, 4> Loads, LoadChains;
7512   for (unsigned i = 0; i < 4; ++i) {
7513     unsigned Offset = 4*i;
7514     SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7515     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7516
7517     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7518                                    PtrInfo.getWithOffset(Offset),
7519                                    false, false, false, 0));
7520     LoadChains.push_back(Loads[i].getValue(1));
7521   }
7522
7523   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7524
7525   SmallVector<SDValue, 4> Stores;
7526   for (unsigned i = 0; i < 4; ++i) {
7527     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7528     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7529
7530     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7531                                        SN->getPointerInfo().getWithOffset(i),
7532                                        MVT::i8 /* memory type */,
7533                                        SN->isNonTemporal(), SN->isVolatile(), 
7534                                        1 /* alignment */, SN->getAAInfo()));
7535   }
7536
7537   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7538
7539   return StoreChain;
7540 }
7541
7542 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7543   SDLoc dl(Op);
7544   if (Op.getValueType() == MVT::v4i32) {
7545     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7546
7547     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7548     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7549
7550     SDValue RHSSwap =   // = vrlw RHS, 16
7551       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7552
7553     // Shrinkify inputs to v8i16.
7554     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7555     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7556     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7557
7558     // Low parts multiplied together, generating 32-bit results (we ignore the
7559     // top parts).
7560     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7561                                         LHS, RHS, DAG, dl, MVT::v4i32);
7562
7563     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7564                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7565     // Shift the high parts up 16 bits.
7566     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7567                               Neg16, DAG, dl);
7568     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7569   } else if (Op.getValueType() == MVT::v8i16) {
7570     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7571
7572     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7573
7574     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7575                             LHS, RHS, Zero, DAG, dl);
7576   } else if (Op.getValueType() == MVT::v16i8) {
7577     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7578     bool isLittleEndian = Subtarget.isLittleEndian();
7579
7580     // Multiply the even 8-bit parts, producing 16-bit sums.
7581     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7582                                            LHS, RHS, DAG, dl, MVT::v8i16);
7583     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7584
7585     // Multiply the odd 8-bit parts, producing 16-bit sums.
7586     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7587                                           LHS, RHS, DAG, dl, MVT::v8i16);
7588     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7589
7590     // Merge the results together.  Because vmuleub and vmuloub are
7591     // instructions with a big-endian bias, we must reverse the
7592     // element numbering and reverse the meaning of "odd" and "even"
7593     // when generating little endian code.
7594     int Ops[16];
7595     for (unsigned i = 0; i != 8; ++i) {
7596       if (isLittleEndian) {
7597         Ops[i*2  ] = 2*i;
7598         Ops[i*2+1] = 2*i+16;
7599       } else {
7600         Ops[i*2  ] = 2*i+1;
7601         Ops[i*2+1] = 2*i+1+16;
7602       }
7603     }
7604     if (isLittleEndian)
7605       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7606     else
7607       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7608   } else {
7609     llvm_unreachable("Unknown mul to lower!");
7610   }
7611 }
7612
7613 /// LowerOperation - Provide custom lowering hooks for some operations.
7614 ///
7615 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7616   switch (Op.getOpcode()) {
7617   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7618   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7619   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7620   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7621   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7622   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7623   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7624   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7625   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7626   case ISD::VASTART:
7627     return LowerVASTART(Op, DAG, Subtarget);
7628
7629   case ISD::VAARG:
7630     return LowerVAARG(Op, DAG, Subtarget);
7631
7632   case ISD::VACOPY:
7633     return LowerVACOPY(Op, DAG, Subtarget);
7634
7635   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7636   case ISD::DYNAMIC_STACKALLOC:
7637     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7638
7639   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7640   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7641
7642   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7643   case ISD::STORE:              return LowerSTORE(Op, DAG);
7644   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7645   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7646   case ISD::FP_TO_UINT:
7647   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7648                                                       SDLoc(Op));
7649   case ISD::UINT_TO_FP:
7650   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7651   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7652
7653   // Lower 64-bit shifts.
7654   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7655   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7656   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7657
7658   // Vector-related lowering.
7659   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7660   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7661   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7662   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7663   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7664   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7665   case ISD::MUL:                return LowerMUL(Op, DAG);
7666
7667   // For counter-based loop handling.
7668   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7669
7670   // Frame & Return address.
7671   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7672   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7673   }
7674 }
7675
7676 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7677                                            SmallVectorImpl<SDValue>&Results,
7678                                            SelectionDAG &DAG) const {
7679   SDLoc dl(N);
7680   switch (N->getOpcode()) {
7681   default:
7682     llvm_unreachable("Do not know how to custom type legalize this operation!");
7683   case ISD::READCYCLECOUNTER: {
7684     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7685     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7686
7687     Results.push_back(RTB);
7688     Results.push_back(RTB.getValue(1));
7689     Results.push_back(RTB.getValue(2));
7690     break;
7691   }
7692   case ISD::INTRINSIC_W_CHAIN: {
7693     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7694         Intrinsic::ppc_is_decremented_ctr_nonzero)
7695       break;
7696
7697     assert(N->getValueType(0) == MVT::i1 &&
7698            "Unexpected result type for CTR decrement intrinsic");
7699     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7700     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7701     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7702                                  N->getOperand(1)); 
7703
7704     Results.push_back(NewInt);
7705     Results.push_back(NewInt.getValue(1));
7706     break;
7707   }
7708   case ISD::VAARG: {
7709     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7710       return;
7711
7712     EVT VT = N->getValueType(0);
7713
7714     if (VT == MVT::i64) {
7715       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7716
7717       Results.push_back(NewNode);
7718       Results.push_back(NewNode.getValue(1));
7719     }
7720     return;
7721   }
7722   case ISD::FP_ROUND_INREG: {
7723     assert(N->getValueType(0) == MVT::ppcf128);
7724     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7725     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7726                              MVT::f64, N->getOperand(0),
7727                              DAG.getIntPtrConstant(0));
7728     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7729                              MVT::f64, N->getOperand(0),
7730                              DAG.getIntPtrConstant(1));
7731
7732     // Add the two halves of the long double in round-to-zero mode.
7733     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7734
7735     // We know the low half is about to be thrown away, so just use something
7736     // convenient.
7737     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7738                                 FPreg, FPreg));
7739     return;
7740   }
7741   case ISD::FP_TO_SINT:
7742     // LowerFP_TO_INT() can only handle f32 and f64.
7743     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7744       return;
7745     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7746     return;
7747   }
7748 }
7749
7750
7751 //===----------------------------------------------------------------------===//
7752 //  Other Lowering Code
7753 //===----------------------------------------------------------------------===//
7754
7755 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7756   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7757   Function *Func = Intrinsic::getDeclaration(M, Id);
7758   return Builder.CreateCall(Func);
7759 }
7760
7761 // The mappings for emitLeading/TrailingFence is taken from
7762 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7763 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7764                                          AtomicOrdering Ord, bool IsStore,
7765                                          bool IsLoad) const {
7766   if (Ord == SequentiallyConsistent)
7767     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7768   else if (isAtLeastRelease(Ord))
7769     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7770   else
7771     return nullptr;
7772 }
7773
7774 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7775                                           AtomicOrdering Ord, bool IsStore,
7776                                           bool IsLoad) const {
7777   if (IsLoad && isAtLeastAcquire(Ord))
7778     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7779   // FIXME: this is too conservative, a dependent branch + isync is enough.
7780   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7781   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7782   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7783   else
7784     return nullptr;
7785 }
7786
7787 MachineBasicBlock *
7788 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7789                                     unsigned AtomicSize,
7790                                     unsigned BinOpcode) const {
7791   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7792   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7793
7794   auto LoadMnemonic = PPC::LDARX;
7795   auto StoreMnemonic = PPC::STDCX;
7796   switch (AtomicSize) {
7797   default:
7798     llvm_unreachable("Unexpected size of atomic entity");
7799   case 1:
7800     LoadMnemonic = PPC::LBARX;
7801     StoreMnemonic = PPC::STBCX;
7802     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7803     break;
7804   case 2:
7805     LoadMnemonic = PPC::LHARX;
7806     StoreMnemonic = PPC::STHCX;
7807     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7808     break;
7809   case 4:
7810     LoadMnemonic = PPC::LWARX;
7811     StoreMnemonic = PPC::STWCX;
7812     break;
7813   case 8:
7814     LoadMnemonic = PPC::LDARX;
7815     StoreMnemonic = PPC::STDCX;
7816     break;
7817   }
7818
7819   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7820   MachineFunction *F = BB->getParent();
7821   MachineFunction::iterator It = BB;
7822   ++It;
7823
7824   unsigned dest = MI->getOperand(0).getReg();
7825   unsigned ptrA = MI->getOperand(1).getReg();
7826   unsigned ptrB = MI->getOperand(2).getReg();
7827   unsigned incr = MI->getOperand(3).getReg();
7828   DebugLoc dl = MI->getDebugLoc();
7829
7830   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7831   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7832   F->insert(It, loopMBB);
7833   F->insert(It, exitMBB);
7834   exitMBB->splice(exitMBB->begin(), BB,
7835                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7836   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7837
7838   MachineRegisterInfo &RegInfo = F->getRegInfo();
7839   unsigned TmpReg = (!BinOpcode) ? incr :
7840     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7841                                            : &PPC::GPRCRegClass);
7842
7843   //  thisMBB:
7844   //   ...
7845   //   fallthrough --> loopMBB
7846   BB->addSuccessor(loopMBB);
7847
7848   //  loopMBB:
7849   //   l[wd]arx dest, ptr
7850   //   add r0, dest, incr
7851   //   st[wd]cx. r0, ptr
7852   //   bne- loopMBB
7853   //   fallthrough --> exitMBB
7854   BB = loopMBB;
7855   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7856     .addReg(ptrA).addReg(ptrB);
7857   if (BinOpcode)
7858     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7859   BuildMI(BB, dl, TII->get(StoreMnemonic))
7860     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7861   BuildMI(BB, dl, TII->get(PPC::BCC))
7862     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7863   BB->addSuccessor(loopMBB);
7864   BB->addSuccessor(exitMBB);
7865
7866   //  exitMBB:
7867   //   ...
7868   BB = exitMBB;
7869   return BB;
7870 }
7871
7872 MachineBasicBlock *
7873 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7874                                             MachineBasicBlock *BB,
7875                                             bool is8bit,    // operation
7876                                             unsigned BinOpcode) const {
7877   // If we support part-word atomic mnemonics, just use them
7878   if (Subtarget.hasPartwordAtomics())
7879     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7880
7881   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7882   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7883   // In 64 bit mode we have to use 64 bits for addresses, even though the
7884   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
7885   // registers without caring whether they're 32 or 64, but here we're
7886   // doing actual arithmetic on the addresses.
7887   bool is64bit = Subtarget.isPPC64();
7888   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7889
7890   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7891   MachineFunction *F = BB->getParent();
7892   MachineFunction::iterator It = BB;
7893   ++It;
7894
7895   unsigned dest = MI->getOperand(0).getReg();
7896   unsigned ptrA = MI->getOperand(1).getReg();
7897   unsigned ptrB = MI->getOperand(2).getReg();
7898   unsigned incr = MI->getOperand(3).getReg();
7899   DebugLoc dl = MI->getDebugLoc();
7900
7901   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7902   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7903   F->insert(It, loopMBB);
7904   F->insert(It, exitMBB);
7905   exitMBB->splice(exitMBB->begin(), BB,
7906                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7907   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7908
7909   MachineRegisterInfo &RegInfo = F->getRegInfo();
7910   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7911                                           : &PPC::GPRCRegClass;
7912   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7913   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7914   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7915   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7916   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7917   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7918   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7919   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7920   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7921   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7922   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7923   unsigned Ptr1Reg;
7924   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7925
7926   //  thisMBB:
7927   //   ...
7928   //   fallthrough --> loopMBB
7929   BB->addSuccessor(loopMBB);
7930
7931   // The 4-byte load must be aligned, while a char or short may be
7932   // anywhere in the word.  Hence all this nasty bookkeeping code.
7933   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7934   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7935   //   xori shift, shift1, 24 [16]
7936   //   rlwinm ptr, ptr1, 0, 0, 29
7937   //   slw incr2, incr, shift
7938   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7939   //   slw mask, mask2, shift
7940   //  loopMBB:
7941   //   lwarx tmpDest, ptr
7942   //   add tmp, tmpDest, incr2
7943   //   andc tmp2, tmpDest, mask
7944   //   and tmp3, tmp, mask
7945   //   or tmp4, tmp3, tmp2
7946   //   stwcx. tmp4, ptr
7947   //   bne- loopMBB
7948   //   fallthrough --> exitMBB
7949   //   srw dest, tmpDest, shift
7950   if (ptrA != ZeroReg) {
7951     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7952     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7953       .addReg(ptrA).addReg(ptrB);
7954   } else {
7955     Ptr1Reg = ptrB;
7956   }
7957   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7958       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7959   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7960       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7961   if (is64bit)
7962     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7963       .addReg(Ptr1Reg).addImm(0).addImm(61);
7964   else
7965     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7966       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7967   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7968       .addReg(incr).addReg(ShiftReg);
7969   if (is8bit)
7970     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7971   else {
7972     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7973     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7974   }
7975   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7976       .addReg(Mask2Reg).addReg(ShiftReg);
7977
7978   BB = loopMBB;
7979   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7980     .addReg(ZeroReg).addReg(PtrReg);
7981   if (BinOpcode)
7982     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7983       .addReg(Incr2Reg).addReg(TmpDestReg);
7984   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7985     .addReg(TmpDestReg).addReg(MaskReg);
7986   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7987     .addReg(TmpReg).addReg(MaskReg);
7988   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7989     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7990   BuildMI(BB, dl, TII->get(PPC::STWCX))
7991     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7992   BuildMI(BB, dl, TII->get(PPC::BCC))
7993     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7994   BB->addSuccessor(loopMBB);
7995   BB->addSuccessor(exitMBB);
7996
7997   //  exitMBB:
7998   //   ...
7999   BB = exitMBB;
8000   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8001     .addReg(ShiftReg);
8002   return BB;
8003 }
8004
8005 llvm::MachineBasicBlock*
8006 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8007                                     MachineBasicBlock *MBB) const {
8008   DebugLoc DL = MI->getDebugLoc();
8009   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8010
8011   MachineFunction *MF = MBB->getParent();
8012   MachineRegisterInfo &MRI = MF->getRegInfo();
8013
8014   const BasicBlock *BB = MBB->getBasicBlock();
8015   MachineFunction::iterator I = MBB;
8016   ++I;
8017
8018   // Memory Reference
8019   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8020   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8021
8022   unsigned DstReg = MI->getOperand(0).getReg();
8023   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8024   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8025   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8026   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8027
8028   MVT PVT = getPointerTy();
8029   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8030          "Invalid Pointer Size!");
8031   // For v = setjmp(buf), we generate
8032   //
8033   // thisMBB:
8034   //  SjLjSetup mainMBB
8035   //  bl mainMBB
8036   //  v_restore = 1
8037   //  b sinkMBB
8038   //
8039   // mainMBB:
8040   //  buf[LabelOffset] = LR
8041   //  v_main = 0
8042   //
8043   // sinkMBB:
8044   //  v = phi(main, restore)
8045   //
8046
8047   MachineBasicBlock *thisMBB = MBB;
8048   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8049   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8050   MF->insert(I, mainMBB);
8051   MF->insert(I, sinkMBB);
8052
8053   MachineInstrBuilder MIB;
8054
8055   // Transfer the remainder of BB and its successor edges to sinkMBB.
8056   sinkMBB->splice(sinkMBB->begin(), MBB,
8057                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8058   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8059
8060   // Note that the structure of the jmp_buf used here is not compatible
8061   // with that used by libc, and is not designed to be. Specifically, it
8062   // stores only those 'reserved' registers that LLVM does not otherwise
8063   // understand how to spill. Also, by convention, by the time this
8064   // intrinsic is called, Clang has already stored the frame address in the
8065   // first slot of the buffer and stack address in the third. Following the
8066   // X86 target code, we'll store the jump address in the second slot. We also
8067   // need to save the TOC pointer (R2) to handle jumps between shared
8068   // libraries, and that will be stored in the fourth slot. The thread
8069   // identifier (R13) is not affected.
8070
8071   // thisMBB:
8072   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8073   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8074   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8075
8076   // Prepare IP either in reg.
8077   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8078   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8079   unsigned BufReg = MI->getOperand(1).getReg();
8080
8081   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8082     setUsesTOCBasePtr(*MBB->getParent());
8083     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8084             .addReg(PPC::X2)
8085             .addImm(TOCOffset)
8086             .addReg(BufReg);
8087     MIB.setMemRefs(MMOBegin, MMOEnd);
8088   }
8089
8090   // Naked functions never have a base pointer, and so we use r1. For all
8091   // other functions, this decision must be delayed until during PEI.
8092   unsigned BaseReg;
8093   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8094     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8095   else
8096     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8097
8098   MIB = BuildMI(*thisMBB, MI, DL,
8099                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8100             .addReg(BaseReg)
8101             .addImm(BPOffset)
8102             .addReg(BufReg);
8103   MIB.setMemRefs(MMOBegin, MMOEnd);
8104
8105   // Setup
8106   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8107   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8108   MIB.addRegMask(TRI->getNoPreservedMask());
8109
8110   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8111
8112   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8113           .addMBB(mainMBB);
8114   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8115
8116   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8117   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8118
8119   // mainMBB:
8120   //  mainDstReg = 0
8121   MIB =
8122       BuildMI(mainMBB, DL,
8123               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8124
8125   // Store IP
8126   if (Subtarget.isPPC64()) {
8127     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8128             .addReg(LabelReg)
8129             .addImm(LabelOffset)
8130             .addReg(BufReg);
8131   } else {
8132     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8133             .addReg(LabelReg)
8134             .addImm(LabelOffset)
8135             .addReg(BufReg);
8136   }
8137
8138   MIB.setMemRefs(MMOBegin, MMOEnd);
8139
8140   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8141   mainMBB->addSuccessor(sinkMBB);
8142
8143   // sinkMBB:
8144   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8145           TII->get(PPC::PHI), DstReg)
8146     .addReg(mainDstReg).addMBB(mainMBB)
8147     .addReg(restoreDstReg).addMBB(thisMBB);
8148
8149   MI->eraseFromParent();
8150   return sinkMBB;
8151 }
8152
8153 MachineBasicBlock *
8154 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8155                                      MachineBasicBlock *MBB) const {
8156   DebugLoc DL = MI->getDebugLoc();
8157   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8158
8159   MachineFunction *MF = MBB->getParent();
8160   MachineRegisterInfo &MRI = MF->getRegInfo();
8161
8162   // Memory Reference
8163   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8164   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8165
8166   MVT PVT = getPointerTy();
8167   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8168          "Invalid Pointer Size!");
8169
8170   const TargetRegisterClass *RC =
8171     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8172   unsigned Tmp = MRI.createVirtualRegister(RC);
8173   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8174   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8175   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8176   unsigned BP =
8177       (PVT == MVT::i64)
8178           ? PPC::X30
8179           : (Subtarget.isSVR4ABI() &&
8180                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8181                  ? PPC::R29
8182                  : PPC::R30);
8183
8184   MachineInstrBuilder MIB;
8185
8186   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8187   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8188   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8189   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8190
8191   unsigned BufReg = MI->getOperand(0).getReg();
8192
8193   // Reload FP (the jumped-to function may not have had a
8194   // frame pointer, and if so, then its r31 will be restored
8195   // as necessary).
8196   if (PVT == MVT::i64) {
8197     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8198             .addImm(0)
8199             .addReg(BufReg);
8200   } else {
8201     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8202             .addImm(0)
8203             .addReg(BufReg);
8204   }
8205   MIB.setMemRefs(MMOBegin, MMOEnd);
8206
8207   // Reload IP
8208   if (PVT == MVT::i64) {
8209     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8210             .addImm(LabelOffset)
8211             .addReg(BufReg);
8212   } else {
8213     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8214             .addImm(LabelOffset)
8215             .addReg(BufReg);
8216   }
8217   MIB.setMemRefs(MMOBegin, MMOEnd);
8218
8219   // Reload SP
8220   if (PVT == MVT::i64) {
8221     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8222             .addImm(SPOffset)
8223             .addReg(BufReg);
8224   } else {
8225     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8226             .addImm(SPOffset)
8227             .addReg(BufReg);
8228   }
8229   MIB.setMemRefs(MMOBegin, MMOEnd);
8230
8231   // Reload BP
8232   if (PVT == MVT::i64) {
8233     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8234             .addImm(BPOffset)
8235             .addReg(BufReg);
8236   } else {
8237     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8238             .addImm(BPOffset)
8239             .addReg(BufReg);
8240   }
8241   MIB.setMemRefs(MMOBegin, MMOEnd);
8242
8243   // Reload TOC
8244   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8245     setUsesTOCBasePtr(*MBB->getParent());
8246     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8247             .addImm(TOCOffset)
8248             .addReg(BufReg);
8249
8250     MIB.setMemRefs(MMOBegin, MMOEnd);
8251   }
8252
8253   // Jump
8254   BuildMI(*MBB, MI, DL,
8255           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8256   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8257
8258   MI->eraseFromParent();
8259   return MBB;
8260 }
8261
8262 MachineBasicBlock *
8263 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8264                                                MachineBasicBlock *BB) const {
8265   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8266       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8267     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8268         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8269       // Call lowering should have added an r2 operand to indicate a dependence
8270       // on the TOC base pointer value. It can't however, because there is no
8271       // way to mark the dependence as implicit there, and so the stackmap code
8272       // will confuse it with a regular operand. Instead, add the dependence
8273       // here.
8274       setUsesTOCBasePtr(*BB->getParent());
8275       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8276     }
8277
8278     return emitPatchPoint(MI, BB);
8279   }
8280
8281   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8282       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8283     return emitEHSjLjSetJmp(MI, BB);
8284   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8285              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8286     return emitEHSjLjLongJmp(MI, BB);
8287   }
8288
8289   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8290
8291   // To "insert" these instructions we actually have to insert their
8292   // control-flow patterns.
8293   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8294   MachineFunction::iterator It = BB;
8295   ++It;
8296
8297   MachineFunction *F = BB->getParent();
8298
8299   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8300                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8301                               MI->getOpcode() == PPC::SELECT_I4 ||
8302                               MI->getOpcode() == PPC::SELECT_I8)) {
8303     SmallVector<MachineOperand, 2> Cond;
8304     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8305         MI->getOpcode() == PPC::SELECT_CC_I8)
8306       Cond.push_back(MI->getOperand(4));
8307     else
8308       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8309     Cond.push_back(MI->getOperand(1));
8310
8311     DebugLoc dl = MI->getDebugLoc();
8312     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8313                       Cond, MI->getOperand(2).getReg(),
8314                       MI->getOperand(3).getReg());
8315   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8316              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8317              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8318              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8319              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8320              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8321              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8322              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8323              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8324              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8325              MI->getOpcode() == PPC::SELECT_I4 ||
8326              MI->getOpcode() == PPC::SELECT_I8 ||
8327              MI->getOpcode() == PPC::SELECT_F4 ||
8328              MI->getOpcode() == PPC::SELECT_F8 ||
8329              MI->getOpcode() == PPC::SELECT_QFRC ||
8330              MI->getOpcode() == PPC::SELECT_QSRC ||
8331              MI->getOpcode() == PPC::SELECT_QBRC ||
8332              MI->getOpcode() == PPC::SELECT_VRRC ||
8333              MI->getOpcode() == PPC::SELECT_VSFRC ||
8334              MI->getOpcode() == PPC::SELECT_VSRC) {
8335     // The incoming instruction knows the destination vreg to set, the
8336     // condition code register to branch on, the true/false values to
8337     // select between, and a branch opcode to use.
8338
8339     //  thisMBB:
8340     //  ...
8341     //   TrueVal = ...
8342     //   cmpTY ccX, r1, r2
8343     //   bCC copy1MBB
8344     //   fallthrough --> copy0MBB
8345     MachineBasicBlock *thisMBB = BB;
8346     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8347     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8348     DebugLoc dl = MI->getDebugLoc();
8349     F->insert(It, copy0MBB);
8350     F->insert(It, sinkMBB);
8351
8352     // Transfer the remainder of BB and its successor edges to sinkMBB.
8353     sinkMBB->splice(sinkMBB->begin(), BB,
8354                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8355     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8356
8357     // Next, add the true and fallthrough blocks as its successors.
8358     BB->addSuccessor(copy0MBB);
8359     BB->addSuccessor(sinkMBB);
8360
8361     if (MI->getOpcode() == PPC::SELECT_I4 ||
8362         MI->getOpcode() == PPC::SELECT_I8 ||
8363         MI->getOpcode() == PPC::SELECT_F4 ||
8364         MI->getOpcode() == PPC::SELECT_F8 ||
8365         MI->getOpcode() == PPC::SELECT_QFRC ||
8366         MI->getOpcode() == PPC::SELECT_QSRC ||
8367         MI->getOpcode() == PPC::SELECT_QBRC ||
8368         MI->getOpcode() == PPC::SELECT_VRRC ||
8369         MI->getOpcode() == PPC::SELECT_VSFRC ||
8370         MI->getOpcode() == PPC::SELECT_VSRC) {
8371       BuildMI(BB, dl, TII->get(PPC::BC))
8372         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8373     } else {
8374       unsigned SelectPred = MI->getOperand(4).getImm();
8375       BuildMI(BB, dl, TII->get(PPC::BCC))
8376         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8377     }
8378
8379     //  copy0MBB:
8380     //   %FalseValue = ...
8381     //   # fallthrough to sinkMBB
8382     BB = copy0MBB;
8383
8384     // Update machine-CFG edges
8385     BB->addSuccessor(sinkMBB);
8386
8387     //  sinkMBB:
8388     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8389     //  ...
8390     BB = sinkMBB;
8391     BuildMI(*BB, BB->begin(), dl,
8392             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8393       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8394       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8395   } else if (MI->getOpcode() == PPC::ReadTB) {
8396     // To read the 64-bit time-base register on a 32-bit target, we read the
8397     // two halves. Should the counter have wrapped while it was being read, we
8398     // need to try again.
8399     // ...
8400     // readLoop:
8401     // mfspr Rx,TBU # load from TBU
8402     // mfspr Ry,TB  # load from TB
8403     // mfspr Rz,TBU # load from TBU
8404     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8405     // bne readLoop   # branch if they're not equal
8406     // ...
8407
8408     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8409     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8410     DebugLoc dl = MI->getDebugLoc();
8411     F->insert(It, readMBB);
8412     F->insert(It, sinkMBB);
8413
8414     // Transfer the remainder of BB and its successor edges to sinkMBB.
8415     sinkMBB->splice(sinkMBB->begin(), BB,
8416                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8417     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8418
8419     BB->addSuccessor(readMBB);
8420     BB = readMBB;
8421
8422     MachineRegisterInfo &RegInfo = F->getRegInfo();
8423     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8424     unsigned LoReg = MI->getOperand(0).getReg();
8425     unsigned HiReg = MI->getOperand(1).getReg();
8426
8427     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8428     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8429     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8430
8431     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8432
8433     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8434       .addReg(HiReg).addReg(ReadAgainReg);
8435     BuildMI(BB, dl, TII->get(PPC::BCC))
8436       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8437
8438     BB->addSuccessor(readMBB);
8439     BB->addSuccessor(sinkMBB);
8440   }
8441   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8442     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8443   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8444     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8445   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8446     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8447   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8448     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8449
8450   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8451     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8452   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8453     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8454   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8455     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8456   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8457     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8458
8459   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8460     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8461   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8462     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8463   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8464     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8465   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8466     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8467
8468   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8469     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8470   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8471     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8472   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8473     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8474   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8475     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8476
8477   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8478     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8479   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8480     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8481   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8482     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8483   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8484     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8485
8486   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8487     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8488   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8489     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8490   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8491     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8492   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8493     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8494
8495   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8496     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8497   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8498     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8499   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8500     BB = EmitAtomicBinary(MI, BB, 4, 0);
8501   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8502     BB = EmitAtomicBinary(MI, BB, 8, 0);
8503
8504   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8505            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8506            (Subtarget.hasPartwordAtomics() &&
8507             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8508            (Subtarget.hasPartwordAtomics() &&
8509             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8510     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8511
8512     auto LoadMnemonic = PPC::LDARX;
8513     auto StoreMnemonic = PPC::STDCX;
8514     switch(MI->getOpcode()) {
8515     default:
8516       llvm_unreachable("Compare and swap of unknown size");
8517     case PPC::ATOMIC_CMP_SWAP_I8:
8518       LoadMnemonic = PPC::LBARX;
8519       StoreMnemonic = PPC::STBCX;
8520       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8521       break;
8522     case PPC::ATOMIC_CMP_SWAP_I16:
8523       LoadMnemonic = PPC::LHARX;
8524       StoreMnemonic = PPC::STHCX;
8525       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8526       break;
8527     case PPC::ATOMIC_CMP_SWAP_I32:
8528       LoadMnemonic = PPC::LWARX;
8529       StoreMnemonic = PPC::STWCX;
8530       break;
8531     case PPC::ATOMIC_CMP_SWAP_I64:
8532       LoadMnemonic = PPC::LDARX;
8533       StoreMnemonic = PPC::STDCX;
8534       break;
8535     }
8536     unsigned dest   = MI->getOperand(0).getReg();
8537     unsigned ptrA   = MI->getOperand(1).getReg();
8538     unsigned ptrB   = MI->getOperand(2).getReg();
8539     unsigned oldval = MI->getOperand(3).getReg();
8540     unsigned newval = MI->getOperand(4).getReg();
8541     DebugLoc dl     = MI->getDebugLoc();
8542
8543     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8544     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8545     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8546     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8547     F->insert(It, loop1MBB);
8548     F->insert(It, loop2MBB);
8549     F->insert(It, midMBB);
8550     F->insert(It, exitMBB);
8551     exitMBB->splice(exitMBB->begin(), BB,
8552                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8553     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8554
8555     //  thisMBB:
8556     //   ...
8557     //   fallthrough --> loopMBB
8558     BB->addSuccessor(loop1MBB);
8559
8560     // loop1MBB:
8561     //   l[bhwd]arx dest, ptr
8562     //   cmp[wd] dest, oldval
8563     //   bne- midMBB
8564     // loop2MBB:
8565     //   st[bhwd]cx. newval, ptr
8566     //   bne- loopMBB
8567     //   b exitBB
8568     // midMBB:
8569     //   st[bhwd]cx. dest, ptr
8570     // exitBB:
8571     BB = loop1MBB;
8572     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8573       .addReg(ptrA).addReg(ptrB);
8574     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8575       .addReg(oldval).addReg(dest);
8576     BuildMI(BB, dl, TII->get(PPC::BCC))
8577       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8578     BB->addSuccessor(loop2MBB);
8579     BB->addSuccessor(midMBB);
8580
8581     BB = loop2MBB;
8582     BuildMI(BB, dl, TII->get(StoreMnemonic))
8583       .addReg(newval).addReg(ptrA).addReg(ptrB);
8584     BuildMI(BB, dl, TII->get(PPC::BCC))
8585       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8586     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8587     BB->addSuccessor(loop1MBB);
8588     BB->addSuccessor(exitMBB);
8589
8590     BB = midMBB;
8591     BuildMI(BB, dl, TII->get(StoreMnemonic))
8592       .addReg(dest).addReg(ptrA).addReg(ptrB);
8593     BB->addSuccessor(exitMBB);
8594
8595     //  exitMBB:
8596     //   ...
8597     BB = exitMBB;
8598   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8599              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8600     // We must use 64-bit registers for addresses when targeting 64-bit,
8601     // since we're actually doing arithmetic on them.  Other registers
8602     // can be 32-bit.
8603     bool is64bit = Subtarget.isPPC64();
8604     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8605
8606     unsigned dest   = MI->getOperand(0).getReg();
8607     unsigned ptrA   = MI->getOperand(1).getReg();
8608     unsigned ptrB   = MI->getOperand(2).getReg();
8609     unsigned oldval = MI->getOperand(3).getReg();
8610     unsigned newval = MI->getOperand(4).getReg();
8611     DebugLoc dl     = MI->getDebugLoc();
8612
8613     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8614     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8615     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8616     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8617     F->insert(It, loop1MBB);
8618     F->insert(It, loop2MBB);
8619     F->insert(It, midMBB);
8620     F->insert(It, exitMBB);
8621     exitMBB->splice(exitMBB->begin(), BB,
8622                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8623     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8624
8625     MachineRegisterInfo &RegInfo = F->getRegInfo();
8626     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8627                                             : &PPC::GPRCRegClass;
8628     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8629     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8630     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8631     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8632     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8633     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8634     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8635     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8636     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8637     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8638     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8639     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8640     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8641     unsigned Ptr1Reg;
8642     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8643     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8644     //  thisMBB:
8645     //   ...
8646     //   fallthrough --> loopMBB
8647     BB->addSuccessor(loop1MBB);
8648
8649     // The 4-byte load must be aligned, while a char or short may be
8650     // anywhere in the word.  Hence all this nasty bookkeeping code.
8651     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8652     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8653     //   xori shift, shift1, 24 [16]
8654     //   rlwinm ptr, ptr1, 0, 0, 29
8655     //   slw newval2, newval, shift
8656     //   slw oldval2, oldval,shift
8657     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8658     //   slw mask, mask2, shift
8659     //   and newval3, newval2, mask
8660     //   and oldval3, oldval2, mask
8661     // loop1MBB:
8662     //   lwarx tmpDest, ptr
8663     //   and tmp, tmpDest, mask
8664     //   cmpw tmp, oldval3
8665     //   bne- midMBB
8666     // loop2MBB:
8667     //   andc tmp2, tmpDest, mask
8668     //   or tmp4, tmp2, newval3
8669     //   stwcx. tmp4, ptr
8670     //   bne- loop1MBB
8671     //   b exitBB
8672     // midMBB:
8673     //   stwcx. tmpDest, ptr
8674     // exitBB:
8675     //   srw dest, tmpDest, shift
8676     if (ptrA != ZeroReg) {
8677       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8678       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8679         .addReg(ptrA).addReg(ptrB);
8680     } else {
8681       Ptr1Reg = ptrB;
8682     }
8683     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8684         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8685     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8686         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8687     if (is64bit)
8688       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8689         .addReg(Ptr1Reg).addImm(0).addImm(61);
8690     else
8691       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8692         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8693     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8694         .addReg(newval).addReg(ShiftReg);
8695     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8696         .addReg(oldval).addReg(ShiftReg);
8697     if (is8bit)
8698       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8699     else {
8700       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8701       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8702         .addReg(Mask3Reg).addImm(65535);
8703     }
8704     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8705         .addReg(Mask2Reg).addReg(ShiftReg);
8706     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8707         .addReg(NewVal2Reg).addReg(MaskReg);
8708     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8709         .addReg(OldVal2Reg).addReg(MaskReg);
8710
8711     BB = loop1MBB;
8712     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8713         .addReg(ZeroReg).addReg(PtrReg);
8714     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8715         .addReg(TmpDestReg).addReg(MaskReg);
8716     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8717         .addReg(TmpReg).addReg(OldVal3Reg);
8718     BuildMI(BB, dl, TII->get(PPC::BCC))
8719         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8720     BB->addSuccessor(loop2MBB);
8721     BB->addSuccessor(midMBB);
8722
8723     BB = loop2MBB;
8724     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8725         .addReg(TmpDestReg).addReg(MaskReg);
8726     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8727         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8728     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8729         .addReg(ZeroReg).addReg(PtrReg);
8730     BuildMI(BB, dl, TII->get(PPC::BCC))
8731       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8732     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8733     BB->addSuccessor(loop1MBB);
8734     BB->addSuccessor(exitMBB);
8735
8736     BB = midMBB;
8737     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8738       .addReg(ZeroReg).addReg(PtrReg);
8739     BB->addSuccessor(exitMBB);
8740
8741     //  exitMBB:
8742     //   ...
8743     BB = exitMBB;
8744     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8745       .addReg(ShiftReg);
8746   } else if (MI->getOpcode() == PPC::FADDrtz) {
8747     // This pseudo performs an FADD with rounding mode temporarily forced
8748     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8749     // is not modeled at the SelectionDAG level.
8750     unsigned Dest = MI->getOperand(0).getReg();
8751     unsigned Src1 = MI->getOperand(1).getReg();
8752     unsigned Src2 = MI->getOperand(2).getReg();
8753     DebugLoc dl   = MI->getDebugLoc();
8754
8755     MachineRegisterInfo &RegInfo = F->getRegInfo();
8756     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8757
8758     // Save FPSCR value.
8759     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8760
8761     // Set rounding mode to round-to-zero.
8762     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8763     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8764
8765     // Perform addition.
8766     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8767
8768     // Restore FPSCR value.
8769     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8770   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8771              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8772              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8773              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8774     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8775                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8776                       PPC::ANDIo8 : PPC::ANDIo;
8777     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8778                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8779
8780     MachineRegisterInfo &RegInfo = F->getRegInfo();
8781     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8782                                                   &PPC::GPRCRegClass :
8783                                                   &PPC::G8RCRegClass);
8784
8785     DebugLoc dl   = MI->getDebugLoc();
8786     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8787       .addReg(MI->getOperand(1).getReg()).addImm(1);
8788     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8789             MI->getOperand(0).getReg())
8790       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8791   } else {
8792     llvm_unreachable("Unexpected instr type to insert");
8793   }
8794
8795   MI->eraseFromParent();   // The pseudo instruction is gone now.
8796   return BB;
8797 }
8798
8799 //===----------------------------------------------------------------------===//
8800 // Target Optimization Hooks
8801 //===----------------------------------------------------------------------===//
8802
8803 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8804                                             DAGCombinerInfo &DCI,
8805                                             unsigned &RefinementSteps,
8806                                             bool &UseOneConstNR) const {
8807   EVT VT = Operand.getValueType();
8808   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8809       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8810       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8811       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8812       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8813       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8814     // Convergence is quadratic, so we essentially double the number of digits
8815     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8816     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8817     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8818     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8819     if (VT.getScalarType() == MVT::f64)
8820       ++RefinementSteps;
8821     UseOneConstNR = true;
8822     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8823   }
8824   return SDValue();
8825 }
8826
8827 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8828                                             DAGCombinerInfo &DCI,
8829                                             unsigned &RefinementSteps) const {
8830   EVT VT = Operand.getValueType();
8831   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8832       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8833       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8834       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8835       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8836       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8837     // Convergence is quadratic, so we essentially double the number of digits
8838     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8839     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8840     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8841     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8842     if (VT.getScalarType() == MVT::f64)
8843       ++RefinementSteps;
8844     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8845   }
8846   return SDValue();
8847 }
8848
8849 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8850   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8851   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8852   // enabled for division), this functionality is redundant with the default
8853   // combiner logic (once the division -> reciprocal/multiply transformation
8854   // has taken place). As a result, this matters more for older cores than for
8855   // newer ones.
8856
8857   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8858   // reciprocal if there are two or more FDIVs (for embedded cores with only
8859   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8860   switch (Subtarget.getDarwinDirective()) {
8861   default:
8862     return NumUsers > 2;
8863   case PPC::DIR_440:
8864   case PPC::DIR_A2:
8865   case PPC::DIR_E500mc:
8866   case PPC::DIR_E5500:
8867     return NumUsers > 1;
8868   }
8869 }
8870
8871 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8872                             unsigned Bytes, int Dist,
8873                             SelectionDAG &DAG) {
8874   if (VT.getSizeInBits() / 8 != Bytes)
8875     return false;
8876
8877   SDValue BaseLoc = Base->getBasePtr();
8878   if (Loc.getOpcode() == ISD::FrameIndex) {
8879     if (BaseLoc.getOpcode() != ISD::FrameIndex)
8880       return false;
8881     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8882     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
8883     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8884     int FS  = MFI->getObjectSize(FI);
8885     int BFS = MFI->getObjectSize(BFI);
8886     if (FS != BFS || FS != (int)Bytes) return false;
8887     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8888   }
8889
8890   // Handle X+C
8891   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8892       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8893     return true;
8894
8895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8896   const GlobalValue *GV1 = nullptr;
8897   const GlobalValue *GV2 = nullptr;
8898   int64_t Offset1 = 0;
8899   int64_t Offset2 = 0;
8900   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8901   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8902   if (isGA1 && isGA2 && GV1 == GV2)
8903     return Offset1 == (Offset2 + Dist*Bytes);
8904   return false;
8905 }
8906
8907 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8908 // not enforce equality of the chain operands.
8909 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8910                             unsigned Bytes, int Dist,
8911                             SelectionDAG &DAG) {
8912   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8913     EVT VT = LS->getMemoryVT();
8914     SDValue Loc = LS->getBasePtr();
8915     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8916   }
8917
8918   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8919     EVT VT;
8920     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8921     default: return false;
8922     case Intrinsic::ppc_qpx_qvlfd:
8923     case Intrinsic::ppc_qpx_qvlfda:
8924       VT = MVT::v4f64;
8925       break;
8926     case Intrinsic::ppc_qpx_qvlfs:
8927     case Intrinsic::ppc_qpx_qvlfsa:
8928       VT = MVT::v4f32;
8929       break;
8930     case Intrinsic::ppc_qpx_qvlfcd:
8931     case Intrinsic::ppc_qpx_qvlfcda:
8932       VT = MVT::v2f64;
8933       break;
8934     case Intrinsic::ppc_qpx_qvlfcs:
8935     case Intrinsic::ppc_qpx_qvlfcsa:
8936       VT = MVT::v2f32;
8937       break;
8938     case Intrinsic::ppc_qpx_qvlfiwa:
8939     case Intrinsic::ppc_qpx_qvlfiwz:
8940     case Intrinsic::ppc_altivec_lvx:
8941     case Intrinsic::ppc_altivec_lvxl:
8942     case Intrinsic::ppc_vsx_lxvw4x:
8943       VT = MVT::v4i32;
8944       break;
8945     case Intrinsic::ppc_vsx_lxvd2x:
8946       VT = MVT::v2f64;
8947       break;
8948     case Intrinsic::ppc_altivec_lvebx:
8949       VT = MVT::i8;
8950       break;
8951     case Intrinsic::ppc_altivec_lvehx:
8952       VT = MVT::i16;
8953       break;
8954     case Intrinsic::ppc_altivec_lvewx:
8955       VT = MVT::i32;
8956       break;
8957     }
8958
8959     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8960   }
8961
8962   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8963     EVT VT;
8964     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8965     default: return false;
8966     case Intrinsic::ppc_qpx_qvstfd:
8967     case Intrinsic::ppc_qpx_qvstfda:
8968       VT = MVT::v4f64;
8969       break;
8970     case Intrinsic::ppc_qpx_qvstfs:
8971     case Intrinsic::ppc_qpx_qvstfsa:
8972       VT = MVT::v4f32;
8973       break;
8974     case Intrinsic::ppc_qpx_qvstfcd:
8975     case Intrinsic::ppc_qpx_qvstfcda:
8976       VT = MVT::v2f64;
8977       break;
8978     case Intrinsic::ppc_qpx_qvstfcs:
8979     case Intrinsic::ppc_qpx_qvstfcsa:
8980       VT = MVT::v2f32;
8981       break;
8982     case Intrinsic::ppc_qpx_qvstfiw:
8983     case Intrinsic::ppc_qpx_qvstfiwa:
8984     case Intrinsic::ppc_altivec_stvx:
8985     case Intrinsic::ppc_altivec_stvxl:
8986     case Intrinsic::ppc_vsx_stxvw4x:
8987       VT = MVT::v4i32;
8988       break;
8989     case Intrinsic::ppc_vsx_stxvd2x:
8990       VT = MVT::v2f64;
8991       break;
8992     case Intrinsic::ppc_altivec_stvebx:
8993       VT = MVT::i8;
8994       break;
8995     case Intrinsic::ppc_altivec_stvehx:
8996       VT = MVT::i16;
8997       break;
8998     case Intrinsic::ppc_altivec_stvewx:
8999       VT = MVT::i32;
9000       break;
9001     }
9002
9003     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9004   }
9005
9006   return false;
9007 }
9008
9009 // Return true is there is a nearyby consecutive load to the one provided
9010 // (regardless of alignment). We search up and down the chain, looking though
9011 // token factors and other loads (but nothing else). As a result, a true result
9012 // indicates that it is safe to create a new consecutive load adjacent to the
9013 // load provided.
9014 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9015   SDValue Chain = LD->getChain();
9016   EVT VT = LD->getMemoryVT();
9017
9018   SmallSet<SDNode *, 16> LoadRoots;
9019   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9020   SmallSet<SDNode *, 16> Visited;
9021
9022   // First, search up the chain, branching to follow all token-factor operands.
9023   // If we find a consecutive load, then we're done, otherwise, record all
9024   // nodes just above the top-level loads and token factors.
9025   while (!Queue.empty()) {
9026     SDNode *ChainNext = Queue.pop_back_val();
9027     if (!Visited.insert(ChainNext).second)
9028       continue;
9029
9030     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9031       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9032         return true;
9033
9034       if (!Visited.count(ChainLD->getChain().getNode()))
9035         Queue.push_back(ChainLD->getChain().getNode());
9036     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9037       for (const SDUse &O : ChainNext->ops())
9038         if (!Visited.count(O.getNode()))
9039           Queue.push_back(O.getNode());
9040     } else
9041       LoadRoots.insert(ChainNext);
9042   }
9043
9044   // Second, search down the chain, starting from the top-level nodes recorded
9045   // in the first phase. These top-level nodes are the nodes just above all
9046   // loads and token factors. Starting with their uses, recursively look though
9047   // all loads (just the chain uses) and token factors to find a consecutive
9048   // load.
9049   Visited.clear();
9050   Queue.clear();
9051
9052   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9053        IE = LoadRoots.end(); I != IE; ++I) {
9054     Queue.push_back(*I);
9055        
9056     while (!Queue.empty()) {
9057       SDNode *LoadRoot = Queue.pop_back_val();
9058       if (!Visited.insert(LoadRoot).second)
9059         continue;
9060
9061       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9062         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9063           return true;
9064
9065       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9066            UE = LoadRoot->use_end(); UI != UE; ++UI)
9067         if (((isa<MemSDNode>(*UI) &&
9068             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9069             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9070           Queue.push_back(*UI);
9071     }
9072   }
9073
9074   return false;
9075 }
9076
9077 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9078                                                   DAGCombinerInfo &DCI) const {
9079   SelectionDAG &DAG = DCI.DAG;
9080   SDLoc dl(N);
9081
9082   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9083   // If we're tracking CR bits, we need to be careful that we don't have:
9084   //   trunc(binary-ops(zext(x), zext(y)))
9085   // or
9086   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9087   // such that we're unnecessarily moving things into GPRs when it would be
9088   // better to keep them in CR bits.
9089
9090   // Note that trunc here can be an actual i1 trunc, or can be the effective
9091   // truncation that comes from a setcc or select_cc.
9092   if (N->getOpcode() == ISD::TRUNCATE &&
9093       N->getValueType(0) != MVT::i1)
9094     return SDValue();
9095
9096   if (N->getOperand(0).getValueType() != MVT::i32 &&
9097       N->getOperand(0).getValueType() != MVT::i64)
9098     return SDValue();
9099
9100   if (N->getOpcode() == ISD::SETCC ||
9101       N->getOpcode() == ISD::SELECT_CC) {
9102     // If we're looking at a comparison, then we need to make sure that the
9103     // high bits (all except for the first) don't matter the result.
9104     ISD::CondCode CC =
9105       cast<CondCodeSDNode>(N->getOperand(
9106         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9107     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9108
9109     if (ISD::isSignedIntSetCC(CC)) {
9110       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9111           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9112         return SDValue();
9113     } else if (ISD::isUnsignedIntSetCC(CC)) {
9114       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9115                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9116           !DAG.MaskedValueIsZero(N->getOperand(1),
9117                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9118         return SDValue();
9119     } else {
9120       // This is neither a signed nor an unsigned comparison, just make sure
9121       // that the high bits are equal.
9122       APInt Op1Zero, Op1One;
9123       APInt Op2Zero, Op2One;
9124       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9125       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9126
9127       // We don't really care about what is known about the first bit (if
9128       // anything), so clear it in all masks prior to comparing them.
9129       Op1Zero.clearBit(0); Op1One.clearBit(0);
9130       Op2Zero.clearBit(0); Op2One.clearBit(0);
9131
9132       if (Op1Zero != Op2Zero || Op1One != Op2One)
9133         return SDValue();
9134     }
9135   }
9136
9137   // We now know that the higher-order bits are irrelevant, we just need to
9138   // make sure that all of the intermediate operations are bit operations, and
9139   // all inputs are extensions.
9140   if (N->getOperand(0).getOpcode() != ISD::AND &&
9141       N->getOperand(0).getOpcode() != ISD::OR  &&
9142       N->getOperand(0).getOpcode() != ISD::XOR &&
9143       N->getOperand(0).getOpcode() != ISD::SELECT &&
9144       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9145       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9146       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9147       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9148       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9149     return SDValue();
9150
9151   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9152       N->getOperand(1).getOpcode() != ISD::AND &&
9153       N->getOperand(1).getOpcode() != ISD::OR  &&
9154       N->getOperand(1).getOpcode() != ISD::XOR &&
9155       N->getOperand(1).getOpcode() != ISD::SELECT &&
9156       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9157       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9158       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9159       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9160       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9161     return SDValue();
9162
9163   SmallVector<SDValue, 4> Inputs;
9164   SmallVector<SDValue, 8> BinOps, PromOps;
9165   SmallPtrSet<SDNode *, 16> Visited;
9166
9167   for (unsigned i = 0; i < 2; ++i) {
9168     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9169           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9170           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9171           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9172         isa<ConstantSDNode>(N->getOperand(i)))
9173       Inputs.push_back(N->getOperand(i));
9174     else
9175       BinOps.push_back(N->getOperand(i));
9176
9177     if (N->getOpcode() == ISD::TRUNCATE)
9178       break;
9179   }
9180
9181   // Visit all inputs, collect all binary operations (and, or, xor and
9182   // select) that are all fed by extensions. 
9183   while (!BinOps.empty()) {
9184     SDValue BinOp = BinOps.back();
9185     BinOps.pop_back();
9186
9187     if (!Visited.insert(BinOp.getNode()).second)
9188       continue;
9189
9190     PromOps.push_back(BinOp);
9191
9192     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9193       // The condition of the select is not promoted.
9194       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9195         continue;
9196       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9197         continue;
9198
9199       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9200             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9201             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9202            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9203           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9204         Inputs.push_back(BinOp.getOperand(i)); 
9205       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9206                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9207                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9208                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9209                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9210                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9211                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9212                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9213                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9214         BinOps.push_back(BinOp.getOperand(i));
9215       } else {
9216         // We have an input that is not an extension or another binary
9217         // operation; we'll abort this transformation.
9218         return SDValue();
9219       }
9220     }
9221   }
9222
9223   // Make sure that this is a self-contained cluster of operations (which
9224   // is not quite the same thing as saying that everything has only one
9225   // use).
9226   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9227     if (isa<ConstantSDNode>(Inputs[i]))
9228       continue;
9229
9230     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9231                               UE = Inputs[i].getNode()->use_end();
9232          UI != UE; ++UI) {
9233       SDNode *User = *UI;
9234       if (User != N && !Visited.count(User))
9235         return SDValue();
9236
9237       // Make sure that we're not going to promote the non-output-value
9238       // operand(s) or SELECT or SELECT_CC.
9239       // FIXME: Although we could sometimes handle this, and it does occur in
9240       // practice that one of the condition inputs to the select is also one of
9241       // the outputs, we currently can't deal with this.
9242       if (User->getOpcode() == ISD::SELECT) {
9243         if (User->getOperand(0) == Inputs[i])
9244           return SDValue();
9245       } else if (User->getOpcode() == ISD::SELECT_CC) {
9246         if (User->getOperand(0) == Inputs[i] ||
9247             User->getOperand(1) == Inputs[i])
9248           return SDValue();
9249       }
9250     }
9251   }
9252
9253   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9254     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9255                               UE = PromOps[i].getNode()->use_end();
9256          UI != UE; ++UI) {
9257       SDNode *User = *UI;
9258       if (User != N && !Visited.count(User))
9259         return SDValue();
9260
9261       // Make sure that we're not going to promote the non-output-value
9262       // operand(s) or SELECT or SELECT_CC.
9263       // FIXME: Although we could sometimes handle this, and it does occur in
9264       // practice that one of the condition inputs to the select is also one of
9265       // the outputs, we currently can't deal with this.
9266       if (User->getOpcode() == ISD::SELECT) {
9267         if (User->getOperand(0) == PromOps[i])
9268           return SDValue();
9269       } else if (User->getOpcode() == ISD::SELECT_CC) {
9270         if (User->getOperand(0) == PromOps[i] ||
9271             User->getOperand(1) == PromOps[i])
9272           return SDValue();
9273       }
9274     }
9275   }
9276
9277   // Replace all inputs with the extension operand.
9278   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9279     // Constants may have users outside the cluster of to-be-promoted nodes,
9280     // and so we need to replace those as we do the promotions.
9281     if (isa<ConstantSDNode>(Inputs[i]))
9282       continue;
9283     else
9284       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9285   }
9286
9287   // Replace all operations (these are all the same, but have a different
9288   // (i1) return type). DAG.getNode will validate that the types of
9289   // a binary operator match, so go through the list in reverse so that
9290   // we've likely promoted both operands first. Any intermediate truncations or
9291   // extensions disappear.
9292   while (!PromOps.empty()) {
9293     SDValue PromOp = PromOps.back();
9294     PromOps.pop_back();
9295
9296     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9297         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9298         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9299         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9300       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9301           PromOp.getOperand(0).getValueType() != MVT::i1) {
9302         // The operand is not yet ready (see comment below).
9303         PromOps.insert(PromOps.begin(), PromOp);
9304         continue;
9305       }
9306
9307       SDValue RepValue = PromOp.getOperand(0);
9308       if (isa<ConstantSDNode>(RepValue))
9309         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9310
9311       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9312       continue;
9313     }
9314
9315     unsigned C;
9316     switch (PromOp.getOpcode()) {
9317     default:             C = 0; break;
9318     case ISD::SELECT:    C = 1; break;
9319     case ISD::SELECT_CC: C = 2; break;
9320     }
9321
9322     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9323          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9324         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9325          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9326       // The to-be-promoted operands of this node have not yet been
9327       // promoted (this should be rare because we're going through the
9328       // list backward, but if one of the operands has several users in
9329       // this cluster of to-be-promoted nodes, it is possible).
9330       PromOps.insert(PromOps.begin(), PromOp);
9331       continue;
9332     }
9333
9334     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9335                                 PromOp.getNode()->op_end());
9336
9337     // If there are any constant inputs, make sure they're replaced now.
9338     for (unsigned i = 0; i < 2; ++i)
9339       if (isa<ConstantSDNode>(Ops[C+i]))
9340         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9341
9342     DAG.ReplaceAllUsesOfValueWith(PromOp,
9343       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9344   }
9345
9346   // Now we're left with the initial truncation itself.
9347   if (N->getOpcode() == ISD::TRUNCATE)
9348     return N->getOperand(0);
9349
9350   // Otherwise, this is a comparison. The operands to be compared have just
9351   // changed type (to i1), but everything else is the same.
9352   return SDValue(N, 0);
9353 }
9354
9355 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9356                                                   DAGCombinerInfo &DCI) const {
9357   SelectionDAG &DAG = DCI.DAG;
9358   SDLoc dl(N);
9359
9360   // If we're tracking CR bits, we need to be careful that we don't have:
9361   //   zext(binary-ops(trunc(x), trunc(y)))
9362   // or
9363   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9364   // such that we're unnecessarily moving things into CR bits that can more
9365   // efficiently stay in GPRs. Note that if we're not certain that the high
9366   // bits are set as required by the final extension, we still may need to do
9367   // some masking to get the proper behavior.
9368
9369   // This same functionality is important on PPC64 when dealing with
9370   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9371   // the return values of functions. Because it is so similar, it is handled
9372   // here as well.
9373
9374   if (N->getValueType(0) != MVT::i32 &&
9375       N->getValueType(0) != MVT::i64)
9376     return SDValue();
9377
9378   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9379         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9380     return SDValue();
9381
9382   if (N->getOperand(0).getOpcode() != ISD::AND &&
9383       N->getOperand(0).getOpcode() != ISD::OR  &&
9384       N->getOperand(0).getOpcode() != ISD::XOR &&
9385       N->getOperand(0).getOpcode() != ISD::SELECT &&
9386       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9387     return SDValue();
9388
9389   SmallVector<SDValue, 4> Inputs;
9390   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9391   SmallPtrSet<SDNode *, 16> Visited;
9392
9393   // Visit all inputs, collect all binary operations (and, or, xor and
9394   // select) that are all fed by truncations. 
9395   while (!BinOps.empty()) {
9396     SDValue BinOp = BinOps.back();
9397     BinOps.pop_back();
9398
9399     if (!Visited.insert(BinOp.getNode()).second)
9400       continue;
9401
9402     PromOps.push_back(BinOp);
9403
9404     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9405       // The condition of the select is not promoted.
9406       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9407         continue;
9408       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9409         continue;
9410
9411       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9412           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9413         Inputs.push_back(BinOp.getOperand(i)); 
9414       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9415                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9416                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9417                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9418                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9419         BinOps.push_back(BinOp.getOperand(i));
9420       } else {
9421         // We have an input that is not a truncation or another binary
9422         // operation; we'll abort this transformation.
9423         return SDValue();
9424       }
9425     }
9426   }
9427
9428   // The operands of a select that must be truncated when the select is
9429   // promoted because the operand is actually part of the to-be-promoted set.
9430   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9431
9432   // Make sure that this is a self-contained cluster of operations (which
9433   // is not quite the same thing as saying that everything has only one
9434   // use).
9435   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9436     if (isa<ConstantSDNode>(Inputs[i]))
9437       continue;
9438
9439     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9440                               UE = Inputs[i].getNode()->use_end();
9441          UI != UE; ++UI) {
9442       SDNode *User = *UI;
9443       if (User != N && !Visited.count(User))
9444         return SDValue();
9445
9446       // If we're going to promote the non-output-value operand(s) or SELECT or
9447       // SELECT_CC, record them for truncation.
9448       if (User->getOpcode() == ISD::SELECT) {
9449         if (User->getOperand(0) == Inputs[i])
9450           SelectTruncOp[0].insert(std::make_pair(User,
9451                                     User->getOperand(0).getValueType()));
9452       } else if (User->getOpcode() == ISD::SELECT_CC) {
9453         if (User->getOperand(0) == Inputs[i])
9454           SelectTruncOp[0].insert(std::make_pair(User,
9455                                     User->getOperand(0).getValueType()));
9456         if (User->getOperand(1) == Inputs[i])
9457           SelectTruncOp[1].insert(std::make_pair(User,
9458                                     User->getOperand(1).getValueType()));
9459       }
9460     }
9461   }
9462
9463   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9464     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9465                               UE = PromOps[i].getNode()->use_end();
9466          UI != UE; ++UI) {
9467       SDNode *User = *UI;
9468       if (User != N && !Visited.count(User))
9469         return SDValue();
9470
9471       // If we're going to promote the non-output-value operand(s) or SELECT or
9472       // SELECT_CC, record them for truncation.
9473       if (User->getOpcode() == ISD::SELECT) {
9474         if (User->getOperand(0) == PromOps[i])
9475           SelectTruncOp[0].insert(std::make_pair(User,
9476                                     User->getOperand(0).getValueType()));
9477       } else if (User->getOpcode() == ISD::SELECT_CC) {
9478         if (User->getOperand(0) == PromOps[i])
9479           SelectTruncOp[0].insert(std::make_pair(User,
9480                                     User->getOperand(0).getValueType()));
9481         if (User->getOperand(1) == PromOps[i])
9482           SelectTruncOp[1].insert(std::make_pair(User,
9483                                     User->getOperand(1).getValueType()));
9484       }
9485     }
9486   }
9487
9488   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9489   bool ReallyNeedsExt = false;
9490   if (N->getOpcode() != ISD::ANY_EXTEND) {
9491     // If all of the inputs are not already sign/zero extended, then
9492     // we'll still need to do that at the end.
9493     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9494       if (isa<ConstantSDNode>(Inputs[i]))
9495         continue;
9496
9497       unsigned OpBits =
9498         Inputs[i].getOperand(0).getValueSizeInBits();
9499       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9500
9501       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9502            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9503                                   APInt::getHighBitsSet(OpBits,
9504                                                         OpBits-PromBits))) ||
9505           (N->getOpcode() == ISD::SIGN_EXTEND &&
9506            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9507              (OpBits-(PromBits-1)))) {
9508         ReallyNeedsExt = true;
9509         break;
9510       }
9511     }
9512   }
9513
9514   // Replace all inputs, either with the truncation operand, or a
9515   // truncation or extension to the final output type.
9516   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9517     // Constant inputs need to be replaced with the to-be-promoted nodes that
9518     // use them because they might have users outside of the cluster of
9519     // promoted nodes.
9520     if (isa<ConstantSDNode>(Inputs[i]))
9521       continue;
9522
9523     SDValue InSrc = Inputs[i].getOperand(0);
9524     if (Inputs[i].getValueType() == N->getValueType(0))
9525       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9526     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9527       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9528         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9529     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9530       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9531         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9532     else
9533       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9534         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9535   }
9536
9537   // Replace all operations (these are all the same, but have a different
9538   // (promoted) return type). DAG.getNode will validate that the types of
9539   // a binary operator match, so go through the list in reverse so that
9540   // we've likely promoted both operands first.
9541   while (!PromOps.empty()) {
9542     SDValue PromOp = PromOps.back();
9543     PromOps.pop_back();
9544
9545     unsigned C;
9546     switch (PromOp.getOpcode()) {
9547     default:             C = 0; break;
9548     case ISD::SELECT:    C = 1; break;
9549     case ISD::SELECT_CC: C = 2; break;
9550     }
9551
9552     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9553          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9554         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9555          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9556       // The to-be-promoted operands of this node have not yet been
9557       // promoted (this should be rare because we're going through the
9558       // list backward, but if one of the operands has several users in
9559       // this cluster of to-be-promoted nodes, it is possible).
9560       PromOps.insert(PromOps.begin(), PromOp);
9561       continue;
9562     }
9563
9564     // For SELECT and SELECT_CC nodes, we do a similar check for any
9565     // to-be-promoted comparison inputs.
9566     if (PromOp.getOpcode() == ISD::SELECT ||
9567         PromOp.getOpcode() == ISD::SELECT_CC) {
9568       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9569            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9570           (SelectTruncOp[1].count(PromOp.getNode()) &&
9571            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9572         PromOps.insert(PromOps.begin(), PromOp);
9573         continue;
9574       }
9575     }
9576
9577     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9578                                 PromOp.getNode()->op_end());
9579
9580     // If this node has constant inputs, then they'll need to be promoted here.
9581     for (unsigned i = 0; i < 2; ++i) {
9582       if (!isa<ConstantSDNode>(Ops[C+i]))
9583         continue;
9584       if (Ops[C+i].getValueType() == N->getValueType(0))
9585         continue;
9586
9587       if (N->getOpcode() == ISD::SIGN_EXTEND)
9588         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9589       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9590         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9591       else
9592         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9593     }
9594
9595     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9596     // truncate them again to the original value type.
9597     if (PromOp.getOpcode() == ISD::SELECT ||
9598         PromOp.getOpcode() == ISD::SELECT_CC) {
9599       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9600       if (SI0 != SelectTruncOp[0].end())
9601         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9602       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9603       if (SI1 != SelectTruncOp[1].end())
9604         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9605     }
9606
9607     DAG.ReplaceAllUsesOfValueWith(PromOp,
9608       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9609   }
9610
9611   // Now we're left with the initial extension itself.
9612   if (!ReallyNeedsExt)
9613     return N->getOperand(0);
9614
9615   // To zero extend, just mask off everything except for the first bit (in the
9616   // i1 case).
9617   if (N->getOpcode() == ISD::ZERO_EXTEND)
9618     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9619                        DAG.getConstant(APInt::getLowBitsSet(
9620                                          N->getValueSizeInBits(0), PromBits),
9621                                        N->getValueType(0)));
9622
9623   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9624          "Invalid extension type");
9625   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9626   SDValue ShiftCst =
9627     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9628   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9629                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9630                                  N->getOperand(0), ShiftCst), ShiftCst);
9631 }
9632
9633 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9634                                               DAGCombinerInfo &DCI) const {
9635   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9636           N->getOpcode() == ISD::UINT_TO_FP) &&
9637          "Need an int -> FP conversion node here");
9638
9639   if (!Subtarget.has64BitSupport())
9640     return SDValue();
9641
9642   SelectionDAG &DAG = DCI.DAG;
9643   SDLoc dl(N);
9644   SDValue Op(N, 0);
9645
9646   // Don't handle ppc_fp128 here or i1 conversions.
9647   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9648     return SDValue();
9649   if (Op.getOperand(0).getValueType() == MVT::i1)
9650     return SDValue();
9651
9652   // For i32 intermediate values, unfortunately, the conversion functions
9653   // leave the upper 32 bits of the value are undefined. Within the set of
9654   // scalar instructions, we have no method for zero- or sign-extending the
9655   // value. Thus, we cannot handle i32 intermediate values here.
9656   if (Op.getOperand(0).getValueType() == MVT::i32)
9657     return SDValue();
9658
9659   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9660          "UINT_TO_FP is supported only with FPCVT");
9661
9662   // If we have FCFIDS, then use it when converting to single-precision.
9663   // Otherwise, convert to double-precision and then round.
9664   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9665                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9666                                                             : PPCISD::FCFIDS)
9667                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9668                                                             : PPCISD::FCFID);
9669   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9670                   ? MVT::f32
9671                   : MVT::f64;
9672
9673   // If we're converting from a float, to an int, and back to a float again,
9674   // then we don't need the store/load pair at all.
9675   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9676        Subtarget.hasFPCVT()) ||
9677       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9678     SDValue Src = Op.getOperand(0).getOperand(0);
9679     if (Src.getValueType() == MVT::f32) {
9680       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9681       DCI.AddToWorklist(Src.getNode());
9682     }
9683
9684     unsigned FCTOp =
9685       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9686                                                         PPCISD::FCTIDUZ;
9687
9688     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9689     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9690
9691     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9692       FP = DAG.getNode(ISD::FP_ROUND, dl,
9693                        MVT::f32, FP, DAG.getIntPtrConstant(0));
9694       DCI.AddToWorklist(FP.getNode());
9695     }
9696
9697     return FP;
9698   }
9699
9700   return SDValue();
9701 }
9702
9703 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9704 // builtins) into loads with swaps.
9705 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9706                                               DAGCombinerInfo &DCI) const {
9707   SelectionDAG &DAG = DCI.DAG;
9708   SDLoc dl(N);
9709   SDValue Chain;
9710   SDValue Base;
9711   MachineMemOperand *MMO;
9712
9713   switch (N->getOpcode()) {
9714   default:
9715     llvm_unreachable("Unexpected opcode for little endian VSX load");
9716   case ISD::LOAD: {
9717     LoadSDNode *LD = cast<LoadSDNode>(N);
9718     Chain = LD->getChain();
9719     Base = LD->getBasePtr();
9720     MMO = LD->getMemOperand();
9721     // If the MMO suggests this isn't a load of a full vector, leave
9722     // things alone.  For a built-in, we have to make the change for
9723     // correctness, so if there is a size problem that will be a bug.
9724     if (MMO->getSize() < 16)
9725       return SDValue();
9726     break;
9727   }
9728   case ISD::INTRINSIC_W_CHAIN: {
9729     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9730     Chain = Intrin->getChain();
9731     Base = Intrin->getBasePtr();
9732     MMO = Intrin->getMemOperand();
9733     break;
9734   }
9735   }
9736
9737   MVT VecTy = N->getValueType(0).getSimpleVT();
9738   SDValue LoadOps[] = { Chain, Base };
9739   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9740                                          DAG.getVTList(VecTy, MVT::Other),
9741                                          LoadOps, VecTy, MMO);
9742   DCI.AddToWorklist(Load.getNode());
9743   Chain = Load.getValue(1);
9744   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9745                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9746   DCI.AddToWorklist(Swap.getNode());
9747   return Swap;
9748 }
9749
9750 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9751 // builtins) into stores with swaps.
9752 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9753                                                DAGCombinerInfo &DCI) const {
9754   SelectionDAG &DAG = DCI.DAG;
9755   SDLoc dl(N);
9756   SDValue Chain;
9757   SDValue Base;
9758   unsigned SrcOpnd;
9759   MachineMemOperand *MMO;
9760
9761   switch (N->getOpcode()) {
9762   default:
9763     llvm_unreachable("Unexpected opcode for little endian VSX store");
9764   case ISD::STORE: {
9765     StoreSDNode *ST = cast<StoreSDNode>(N);
9766     Chain = ST->getChain();
9767     Base = ST->getBasePtr();
9768     MMO = ST->getMemOperand();
9769     SrcOpnd = 1;
9770     // If the MMO suggests this isn't a store of a full vector, leave
9771     // things alone.  For a built-in, we have to make the change for
9772     // correctness, so if there is a size problem that will be a bug.
9773     if (MMO->getSize() < 16)
9774       return SDValue();
9775     break;
9776   }
9777   case ISD::INTRINSIC_VOID: {
9778     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9779     Chain = Intrin->getChain();
9780     // Intrin->getBasePtr() oddly does not get what we want.
9781     Base = Intrin->getOperand(3);
9782     MMO = Intrin->getMemOperand();
9783     SrcOpnd = 2;
9784     break;
9785   }
9786   }
9787
9788   SDValue Src = N->getOperand(SrcOpnd);
9789   MVT VecTy = Src.getValueType().getSimpleVT();
9790   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9791                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9792   DCI.AddToWorklist(Swap.getNode());
9793   Chain = Swap.getValue(1);
9794   SDValue StoreOps[] = { Chain, Swap, Base };
9795   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9796                                           DAG.getVTList(MVT::Other),
9797                                           StoreOps, VecTy, MMO);
9798   DCI.AddToWorklist(Store.getNode());
9799   return Store;
9800 }
9801
9802 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9803                                              DAGCombinerInfo &DCI) const {
9804   SelectionDAG &DAG = DCI.DAG;
9805   SDLoc dl(N);
9806   switch (N->getOpcode()) {
9807   default: break;
9808   case PPCISD::SHL:
9809     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9810       if (C->isNullValue())   // 0 << V -> 0.
9811         return N->getOperand(0);
9812     }
9813     break;
9814   case PPCISD::SRL:
9815     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9816       if (C->isNullValue())   // 0 >>u V -> 0.
9817         return N->getOperand(0);
9818     }
9819     break;
9820   case PPCISD::SRA:
9821     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9822       if (C->isNullValue() ||   //  0 >>s V -> 0.
9823           C->isAllOnesValue())    // -1 >>s V -> -1.
9824         return N->getOperand(0);
9825     }
9826     break;
9827   case ISD::SIGN_EXTEND:
9828   case ISD::ZERO_EXTEND:
9829   case ISD::ANY_EXTEND: 
9830     return DAGCombineExtBoolTrunc(N, DCI);
9831   case ISD::TRUNCATE:
9832   case ISD::SETCC:
9833   case ISD::SELECT_CC:
9834     return DAGCombineTruncBoolExt(N, DCI);
9835   case ISD::SINT_TO_FP:
9836   case ISD::UINT_TO_FP:
9837     return combineFPToIntToFP(N, DCI);
9838   case ISD::STORE: {
9839     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9840     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9841         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9842         N->getOperand(1).getValueType() == MVT::i32 &&
9843         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9844       SDValue Val = N->getOperand(1).getOperand(0);
9845       if (Val.getValueType() == MVT::f32) {
9846         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9847         DCI.AddToWorklist(Val.getNode());
9848       }
9849       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9850       DCI.AddToWorklist(Val.getNode());
9851
9852       SDValue Ops[] = {
9853         N->getOperand(0), Val, N->getOperand(2),
9854         DAG.getValueType(N->getOperand(1).getValueType())
9855       };
9856
9857       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9858               DAG.getVTList(MVT::Other), Ops,
9859               cast<StoreSDNode>(N)->getMemoryVT(),
9860               cast<StoreSDNode>(N)->getMemOperand());
9861       DCI.AddToWorklist(Val.getNode());
9862       return Val;
9863     }
9864
9865     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9866     if (cast<StoreSDNode>(N)->isUnindexed() &&
9867         N->getOperand(1).getOpcode() == ISD::BSWAP &&
9868         N->getOperand(1).getNode()->hasOneUse() &&
9869         (N->getOperand(1).getValueType() == MVT::i32 ||
9870          N->getOperand(1).getValueType() == MVT::i16 ||
9871          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9872           N->getOperand(1).getValueType() == MVT::i64))) {
9873       SDValue BSwapOp = N->getOperand(1).getOperand(0);
9874       // Do an any-extend to 32-bits if this is a half-word input.
9875       if (BSwapOp.getValueType() == MVT::i16)
9876         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9877
9878       SDValue Ops[] = {
9879         N->getOperand(0), BSwapOp, N->getOperand(2),
9880         DAG.getValueType(N->getOperand(1).getValueType())
9881       };
9882       return
9883         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9884                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9885                                 cast<StoreSDNode>(N)->getMemOperand());
9886     }
9887
9888     // For little endian, VSX stores require generating xxswapd/lxvd2x.
9889     EVT VT = N->getOperand(1).getValueType();
9890     if (VT.isSimple()) {
9891       MVT StoreVT = VT.getSimpleVT();
9892       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9893           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9894            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9895         return expandVSXStoreForLE(N, DCI);
9896     }
9897     break;
9898   }
9899   case ISD::LOAD: {
9900     LoadSDNode *LD = cast<LoadSDNode>(N);
9901     EVT VT = LD->getValueType(0);
9902
9903     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9904     if (VT.isSimple()) {
9905       MVT LoadVT = VT.getSimpleVT();
9906       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9907           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9908            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9909         return expandVSXLoadForLE(N, DCI);
9910     }
9911
9912     EVT MemVT = LD->getMemoryVT();
9913     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9914     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9915     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9916     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9917     if (LD->isUnindexed() && VT.isVector() &&
9918         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9919           // P8 and later hardware should just use LOAD.
9920           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9921                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9922          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9923           LD->getAlignment() >= ScalarABIAlignment)) &&
9924         LD->getAlignment() < ABIAlignment) {
9925       // This is a type-legal unaligned Altivec or QPX load.
9926       SDValue Chain = LD->getChain();
9927       SDValue Ptr = LD->getBasePtr();
9928       bool isLittleEndian = Subtarget.isLittleEndian();
9929
9930       // This implements the loading of unaligned vectors as described in
9931       // the venerable Apple Velocity Engine overview. Specifically:
9932       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9933       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9934       //
9935       // The general idea is to expand a sequence of one or more unaligned
9936       // loads into an alignment-based permutation-control instruction (lvsl
9937       // or lvsr), a series of regular vector loads (which always truncate
9938       // their input address to an aligned address), and a series of
9939       // permutations.  The results of these permutations are the requested
9940       // loaded values.  The trick is that the last "extra" load is not taken
9941       // from the address you might suspect (sizeof(vector) bytes after the
9942       // last requested load), but rather sizeof(vector) - 1 bytes after the
9943       // last requested vector. The point of this is to avoid a page fault if
9944       // the base address happened to be aligned. This works because if the
9945       // base address is aligned, then adding less than a full vector length
9946       // will cause the last vector in the sequence to be (re)loaded.
9947       // Otherwise, the next vector will be fetched as you might suspect was
9948       // necessary.
9949
9950       // We might be able to reuse the permutation generation from
9951       // a different base address offset from this one by an aligned amount.
9952       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9953       // optimization later.
9954       Intrinsic::ID Intr, IntrLD, IntrPerm;
9955       MVT PermCntlTy, PermTy, LDTy;
9956       if (Subtarget.hasAltivec()) {
9957         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
9958                                  Intrinsic::ppc_altivec_lvsl;
9959         IntrLD = Intrinsic::ppc_altivec_lvx;
9960         IntrPerm = Intrinsic::ppc_altivec_vperm;
9961         PermCntlTy = MVT::v16i8;
9962         PermTy = MVT::v4i32;
9963         LDTy = MVT::v4i32;
9964       } else {
9965         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9966                                        Intrinsic::ppc_qpx_qvlpcls;
9967         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9968                                        Intrinsic::ppc_qpx_qvlfs;
9969         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9970         PermCntlTy = MVT::v4f64;
9971         PermTy = MVT::v4f64;
9972         LDTy = MemVT.getSimpleVT();
9973       }
9974
9975       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9976
9977       // Create the new MMO for the new base load. It is like the original MMO,
9978       // but represents an area in memory almost twice the vector size centered
9979       // on the original address. If the address is unaligned, we might start
9980       // reading up to (sizeof(vector)-1) bytes below the address of the
9981       // original unaligned load.
9982       MachineFunction &MF = DAG.getMachineFunction();
9983       MachineMemOperand *BaseMMO =
9984         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9985                                 2*MemVT.getStoreSize()-1);
9986
9987       // Create the new base load.
9988       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9989       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9990       SDValue BaseLoad =
9991         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9992                                 DAG.getVTList(PermTy, MVT::Other),
9993                                 BaseLoadOps, LDTy, BaseMMO);
9994
9995       // Note that the value of IncOffset (which is provided to the next
9996       // load's pointer info offset value, and thus used to calculate the
9997       // alignment), and the value of IncValue (which is actually used to
9998       // increment the pointer value) are different! This is because we
9999       // require the next load to appear to be aligned, even though it
10000       // is actually offset from the base pointer by a lesser amount.
10001       int IncOffset = VT.getSizeInBits() / 8;
10002       int IncValue = IncOffset;
10003
10004       // Walk (both up and down) the chain looking for another load at the real
10005       // (aligned) offset (the alignment of the other load does not matter in
10006       // this case). If found, then do not use the offset reduction trick, as
10007       // that will prevent the loads from being later combined (as they would
10008       // otherwise be duplicates).
10009       if (!findConsecutiveLoad(LD, DAG))
10010         --IncValue;
10011
10012       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
10013       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10014
10015       MachineMemOperand *ExtraMMO =
10016         MF.getMachineMemOperand(LD->getMemOperand(),
10017                                 1, 2*MemVT.getStoreSize()-1);
10018       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10019       SDValue ExtraLoad =
10020         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10021                                 DAG.getVTList(PermTy, MVT::Other),
10022                                 ExtraLoadOps, LDTy, ExtraMMO);
10023
10024       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10025         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10026
10027       // Because vperm has a big-endian bias, we must reverse the order
10028       // of the input vectors and complement the permute control vector
10029       // when generating little endian code.  We have already handled the
10030       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10031       // and ExtraLoad here.
10032       SDValue Perm;
10033       if (isLittleEndian)
10034         Perm = BuildIntrinsicOp(IntrPerm,
10035                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10036       else
10037         Perm = BuildIntrinsicOp(IntrPerm,
10038                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10039
10040       if (VT != PermTy)
10041         Perm = Subtarget.hasAltivec() ?
10042                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10043                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10044                                DAG.getTargetConstant(1, MVT::i64));
10045                                // second argument is 1 because this rounding
10046                                // is always exact.
10047
10048       // The output of the permutation is our loaded result, the TokenFactor is
10049       // our new chain.
10050       DCI.CombineTo(N, Perm, TF);
10051       return SDValue(N, 0);
10052     }
10053     }
10054     break;
10055     case ISD::INTRINSIC_WO_CHAIN: {
10056       bool isLittleEndian = Subtarget.isLittleEndian();
10057       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10058       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10059                                            : Intrinsic::ppc_altivec_lvsl);
10060       if ((IID == Intr ||
10061            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10062            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10063         N->getOperand(1)->getOpcode() == ISD::ADD) {
10064         SDValue Add = N->getOperand(1);
10065
10066         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10067                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10068
10069         if (DAG.MaskedValueIsZero(
10070                 Add->getOperand(1),
10071                 APInt::getAllOnesValue(Bits /* alignment */)
10072                     .zext(
10073                         Add.getValueType().getScalarType().getSizeInBits()))) {
10074           SDNode *BasePtr = Add->getOperand(0).getNode();
10075           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10076                                     UE = BasePtr->use_end();
10077                UI != UE; ++UI) {
10078             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10079                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10080               // We've found another LVSL/LVSR, and this address is an aligned
10081               // multiple of that one. The results will be the same, so use the
10082               // one we've just found instead.
10083
10084               return SDValue(*UI, 0);
10085             }
10086           }
10087         }
10088
10089         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10090           SDNode *BasePtr = Add->getOperand(0).getNode();
10091           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10092                UE = BasePtr->use_end(); UI != UE; ++UI) {
10093             if (UI->getOpcode() == ISD::ADD &&
10094                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10095                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10096                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10097                 (1ULL << Bits) == 0) {
10098               SDNode *OtherAdd = *UI;
10099               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10100                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10101                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10102                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10103                   return SDValue(*VI, 0);
10104                 }
10105               }
10106             }
10107           }
10108         }
10109       }
10110     }
10111
10112     break;
10113   case ISD::INTRINSIC_W_CHAIN: {
10114     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10115     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10116       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10117       default:
10118         break;
10119       case Intrinsic::ppc_vsx_lxvw4x:
10120       case Intrinsic::ppc_vsx_lxvd2x:
10121         return expandVSXLoadForLE(N, DCI);
10122       }
10123     }
10124     break;
10125   }
10126   case ISD::INTRINSIC_VOID: {
10127     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10128     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10129       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10130       default:
10131         break;
10132       case Intrinsic::ppc_vsx_stxvw4x:
10133       case Intrinsic::ppc_vsx_stxvd2x:
10134         return expandVSXStoreForLE(N, DCI);
10135       }
10136     }
10137     break;
10138   }
10139   case ISD::BSWAP:
10140     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10141     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10142         N->getOperand(0).hasOneUse() &&
10143         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10144          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10145           N->getValueType(0) == MVT::i64))) {
10146       SDValue Load = N->getOperand(0);
10147       LoadSDNode *LD = cast<LoadSDNode>(Load);
10148       // Create the byte-swapping load.
10149       SDValue Ops[] = {
10150         LD->getChain(),    // Chain
10151         LD->getBasePtr(),  // Ptr
10152         DAG.getValueType(N->getValueType(0)) // VT
10153       };
10154       SDValue BSLoad =
10155         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10156                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10157                                               MVT::i64 : MVT::i32, MVT::Other),
10158                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10159
10160       // If this is an i16 load, insert the truncate.
10161       SDValue ResVal = BSLoad;
10162       if (N->getValueType(0) == MVT::i16)
10163         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10164
10165       // First, combine the bswap away.  This makes the value produced by the
10166       // load dead.
10167       DCI.CombineTo(N, ResVal);
10168
10169       // Next, combine the load away, we give it a bogus result value but a real
10170       // chain result.  The result value is dead because the bswap is dead.
10171       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10172
10173       // Return N so it doesn't get rechecked!
10174       return SDValue(N, 0);
10175     }
10176
10177     break;
10178   case PPCISD::VCMP: {
10179     // If a VCMPo node already exists with exactly the same operands as this
10180     // node, use its result instead of this node (VCMPo computes both a CR6 and
10181     // a normal output).
10182     //
10183     if (!N->getOperand(0).hasOneUse() &&
10184         !N->getOperand(1).hasOneUse() &&
10185         !N->getOperand(2).hasOneUse()) {
10186
10187       // Scan all of the users of the LHS, looking for VCMPo's that match.
10188       SDNode *VCMPoNode = nullptr;
10189
10190       SDNode *LHSN = N->getOperand(0).getNode();
10191       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10192            UI != E; ++UI)
10193         if (UI->getOpcode() == PPCISD::VCMPo &&
10194             UI->getOperand(1) == N->getOperand(1) &&
10195             UI->getOperand(2) == N->getOperand(2) &&
10196             UI->getOperand(0) == N->getOperand(0)) {
10197           VCMPoNode = *UI;
10198           break;
10199         }
10200
10201       // If there is no VCMPo node, or if the flag value has a single use, don't
10202       // transform this.
10203       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10204         break;
10205
10206       // Look at the (necessarily single) use of the flag value.  If it has a
10207       // chain, this transformation is more complex.  Note that multiple things
10208       // could use the value result, which we should ignore.
10209       SDNode *FlagUser = nullptr;
10210       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10211            FlagUser == nullptr; ++UI) {
10212         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10213         SDNode *User = *UI;
10214         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10215           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10216             FlagUser = User;
10217             break;
10218           }
10219         }
10220       }
10221
10222       // If the user is a MFOCRF instruction, we know this is safe.
10223       // Otherwise we give up for right now.
10224       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10225         return SDValue(VCMPoNode, 0);
10226     }
10227     break;
10228   }
10229   case ISD::BRCOND: {
10230     SDValue Cond = N->getOperand(1);
10231     SDValue Target = N->getOperand(2);
10232  
10233     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10234         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10235           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10236
10237       // We now need to make the intrinsic dead (it cannot be instruction
10238       // selected).
10239       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10240       assert(Cond.getNode()->hasOneUse() &&
10241              "Counter decrement has more than one use");
10242
10243       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10244                          N->getOperand(0), Target);
10245     }
10246   }
10247   break;
10248   case ISD::BR_CC: {
10249     // If this is a branch on an altivec predicate comparison, lower this so
10250     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10251     // lowering is done pre-legalize, because the legalizer lowers the predicate
10252     // compare down to code that is difficult to reassemble.
10253     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10254     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10255
10256     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10257     // value. If so, pass-through the AND to get to the intrinsic.
10258     if (LHS.getOpcode() == ISD::AND &&
10259         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10260         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10261           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10262         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10263         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10264           isZero())
10265       LHS = LHS.getOperand(0);
10266
10267     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10268         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10269           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10270         isa<ConstantSDNode>(RHS)) {
10271       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10272              "Counter decrement comparison is not EQ or NE");
10273
10274       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10275       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10276                     (CC == ISD::SETNE && !Val);
10277
10278       // We now need to make the intrinsic dead (it cannot be instruction
10279       // selected).
10280       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10281       assert(LHS.getNode()->hasOneUse() &&
10282              "Counter decrement has more than one use");
10283
10284       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10285                          N->getOperand(0), N->getOperand(4));
10286     }
10287
10288     int CompareOpc;
10289     bool isDot;
10290
10291     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10292         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10293         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10294       assert(isDot && "Can't compare against a vector result!");
10295
10296       // If this is a comparison against something other than 0/1, then we know
10297       // that the condition is never/always true.
10298       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10299       if (Val != 0 && Val != 1) {
10300         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10301           return N->getOperand(0);
10302         // Always !=, turn it into an unconditional branch.
10303         return DAG.getNode(ISD::BR, dl, MVT::Other,
10304                            N->getOperand(0), N->getOperand(4));
10305       }
10306
10307       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10308
10309       // Create the PPCISD altivec 'dot' comparison node.
10310       SDValue Ops[] = {
10311         LHS.getOperand(2),  // LHS of compare
10312         LHS.getOperand(3),  // RHS of compare
10313         DAG.getConstant(CompareOpc, MVT::i32)
10314       };
10315       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10316       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10317
10318       // Unpack the result based on how the target uses it.
10319       PPC::Predicate CompOpc;
10320       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10321       default:  // Can't happen, don't crash on invalid number though.
10322       case 0:   // Branch on the value of the EQ bit of CR6.
10323         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10324         break;
10325       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10326         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10327         break;
10328       case 2:   // Branch on the value of the LT bit of CR6.
10329         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10330         break;
10331       case 3:   // Branch on the inverted value of the LT bit of CR6.
10332         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10333         break;
10334       }
10335
10336       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10337                          DAG.getConstant(CompOpc, MVT::i32),
10338                          DAG.getRegister(PPC::CR6, MVT::i32),
10339                          N->getOperand(4), CompNode.getValue(1));
10340     }
10341     break;
10342   }
10343   }
10344
10345   return SDValue();
10346 }
10347
10348 SDValue
10349 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10350                                   SelectionDAG &DAG,
10351                                   std::vector<SDNode *> *Created) const {
10352   // fold (sdiv X, pow2)
10353   EVT VT = N->getValueType(0);
10354   if (VT == MVT::i64 && !Subtarget.isPPC64())
10355     return SDValue();
10356   if ((VT != MVT::i32 && VT != MVT::i64) ||
10357       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10358     return SDValue();
10359
10360   SDLoc DL(N);
10361   SDValue N0 = N->getOperand(0);
10362
10363   bool IsNegPow2 = (-Divisor).isPowerOf2();
10364   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10365   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10366
10367   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10368   if (Created)
10369     Created->push_back(Op.getNode());
10370
10371   if (IsNegPow2) {
10372     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10373     if (Created)
10374       Created->push_back(Op.getNode());
10375   }
10376
10377   return Op;
10378 }
10379
10380 //===----------------------------------------------------------------------===//
10381 // Inline Assembly Support
10382 //===----------------------------------------------------------------------===//
10383
10384 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10385                                                       APInt &KnownZero,
10386                                                       APInt &KnownOne,
10387                                                       const SelectionDAG &DAG,
10388                                                       unsigned Depth) const {
10389   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10390   switch (Op.getOpcode()) {
10391   default: break;
10392   case PPCISD::LBRX: {
10393     // lhbrx is known to have the top bits cleared out.
10394     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10395       KnownZero = 0xFFFF0000;
10396     break;
10397   }
10398   case ISD::INTRINSIC_WO_CHAIN: {
10399     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10400     default: break;
10401     case Intrinsic::ppc_altivec_vcmpbfp_p:
10402     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10403     case Intrinsic::ppc_altivec_vcmpequb_p:
10404     case Intrinsic::ppc_altivec_vcmpequh_p:
10405     case Intrinsic::ppc_altivec_vcmpequw_p:
10406     case Intrinsic::ppc_altivec_vcmpequd_p:
10407     case Intrinsic::ppc_altivec_vcmpgefp_p:
10408     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10409     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10410     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10411     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10412     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10413     case Intrinsic::ppc_altivec_vcmpgtub_p:
10414     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10415     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10416     case Intrinsic::ppc_altivec_vcmpgtud_p:
10417       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10418       break;
10419     }
10420   }
10421   }
10422 }
10423
10424 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10425   switch (Subtarget.getDarwinDirective()) {
10426   default: break;
10427   case PPC::DIR_970:
10428   case PPC::DIR_PWR4:
10429   case PPC::DIR_PWR5:
10430   case PPC::DIR_PWR5X:
10431   case PPC::DIR_PWR6:
10432   case PPC::DIR_PWR6X:
10433   case PPC::DIR_PWR7:
10434   case PPC::DIR_PWR8: {
10435     if (!ML)
10436       break;
10437
10438     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10439
10440     // For small loops (between 5 and 8 instructions), align to a 32-byte
10441     // boundary so that the entire loop fits in one instruction-cache line.
10442     uint64_t LoopSize = 0;
10443     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10444       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10445         LoopSize += TII->GetInstSizeInBytes(J);
10446
10447     if (LoopSize > 16 && LoopSize <= 32)
10448       return 5;
10449
10450     break;
10451   }
10452   }
10453
10454   return TargetLowering::getPrefLoopAlignment(ML);
10455 }
10456
10457 /// getConstraintType - Given a constraint, return the type of
10458 /// constraint it is for this target.
10459 PPCTargetLowering::ConstraintType
10460 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10461   if (Constraint.size() == 1) {
10462     switch (Constraint[0]) {
10463     default: break;
10464     case 'b':
10465     case 'r':
10466     case 'f':
10467     case 'v':
10468     case 'y':
10469       return C_RegisterClass;
10470     case 'Z':
10471       // FIXME: While Z does indicate a memory constraint, it specifically
10472       // indicates an r+r address (used in conjunction with the 'y' modifier
10473       // in the replacement string). Currently, we're forcing the base
10474       // register to be r0 in the asm printer (which is interpreted as zero)
10475       // and forming the complete address in the second register. This is
10476       // suboptimal.
10477       return C_Memory;
10478     }
10479   } else if (Constraint == "wc") { // individual CR bits.
10480     return C_RegisterClass;
10481   } else if (Constraint == "wa" || Constraint == "wd" ||
10482              Constraint == "wf" || Constraint == "ws") {
10483     return C_RegisterClass; // VSX registers.
10484   }
10485   return TargetLowering::getConstraintType(Constraint);
10486 }
10487
10488 /// Examine constraint type and operand type and determine a weight value.
10489 /// This object must already have been set up with the operand type
10490 /// and the current alternative constraint selected.
10491 TargetLowering::ConstraintWeight
10492 PPCTargetLowering::getSingleConstraintMatchWeight(
10493     AsmOperandInfo &info, const char *constraint) const {
10494   ConstraintWeight weight = CW_Invalid;
10495   Value *CallOperandVal = info.CallOperandVal;
10496     // If we don't have a value, we can't do a match,
10497     // but allow it at the lowest weight.
10498   if (!CallOperandVal)
10499     return CW_Default;
10500   Type *type = CallOperandVal->getType();
10501
10502   // Look at the constraint type.
10503   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10504     return CW_Register; // an individual CR bit.
10505   else if ((StringRef(constraint) == "wa" ||
10506             StringRef(constraint) == "wd" ||
10507             StringRef(constraint) == "wf") &&
10508            type->isVectorTy())
10509     return CW_Register;
10510   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10511     return CW_Register;
10512
10513   switch (*constraint) {
10514   default:
10515     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10516     break;
10517   case 'b':
10518     if (type->isIntegerTy())
10519       weight = CW_Register;
10520     break;
10521   case 'f':
10522     if (type->isFloatTy())
10523       weight = CW_Register;
10524     break;
10525   case 'd':
10526     if (type->isDoubleTy())
10527       weight = CW_Register;
10528     break;
10529   case 'v':
10530     if (type->isVectorTy())
10531       weight = CW_Register;
10532     break;
10533   case 'y':
10534     weight = CW_Register;
10535     break;
10536   case 'Z':
10537     weight = CW_Memory;
10538     break;
10539   }
10540   return weight;
10541 }
10542
10543 std::pair<unsigned, const TargetRegisterClass *>
10544 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10545                                                 const std::string &Constraint,
10546                                                 MVT VT) const {
10547   if (Constraint.size() == 1) {
10548     // GCC RS6000 Constraint Letters
10549     switch (Constraint[0]) {
10550     case 'b':   // R1-R31
10551       if (VT == MVT::i64 && Subtarget.isPPC64())
10552         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10553       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10554     case 'r':   // R0-R31
10555       if (VT == MVT::i64 && Subtarget.isPPC64())
10556         return std::make_pair(0U, &PPC::G8RCRegClass);
10557       return std::make_pair(0U, &PPC::GPRCRegClass);
10558     case 'f':
10559       if (VT == MVT::f32 || VT == MVT::i32)
10560         return std::make_pair(0U, &PPC::F4RCRegClass);
10561       if (VT == MVT::f64 || VT == MVT::i64)
10562         return std::make_pair(0U, &PPC::F8RCRegClass);
10563       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10564         return std::make_pair(0U, &PPC::QFRCRegClass);
10565       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10566         return std::make_pair(0U, &PPC::QSRCRegClass);
10567       break;
10568     case 'v':
10569       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10570         return std::make_pair(0U, &PPC::QFRCRegClass);
10571       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10572         return std::make_pair(0U, &PPC::QSRCRegClass);
10573       return std::make_pair(0U, &PPC::VRRCRegClass);
10574     case 'y':   // crrc
10575       return std::make_pair(0U, &PPC::CRRCRegClass);
10576     }
10577   } else if (Constraint == "wc") { // an individual CR bit.
10578     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10579   } else if (Constraint == "wa" || Constraint == "wd" ||
10580              Constraint == "wf") {
10581     return std::make_pair(0U, &PPC::VSRCRegClass);
10582   } else if (Constraint == "ws") {
10583     return std::make_pair(0U, &PPC::VSFRCRegClass);
10584   }
10585
10586   std::pair<unsigned, const TargetRegisterClass *> R =
10587       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10588
10589   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10590   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10591   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10592   // register.
10593   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10594   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10595   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10596       PPC::GPRCRegClass.contains(R.first))
10597     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10598                             PPC::sub_32, &PPC::G8RCRegClass),
10599                           &PPC::G8RCRegClass);
10600
10601   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10602   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10603     R.first = PPC::CR0;
10604     R.second = &PPC::CRRCRegClass;
10605   }
10606
10607   return R;
10608 }
10609
10610
10611 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10612 /// vector.  If it is invalid, don't add anything to Ops.
10613 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10614                                                      std::string &Constraint,
10615                                                      std::vector<SDValue>&Ops,
10616                                                      SelectionDAG &DAG) const {
10617   SDValue Result;
10618
10619   // Only support length 1 constraints.
10620   if (Constraint.length() > 1) return;
10621
10622   char Letter = Constraint[0];
10623   switch (Letter) {
10624   default: break;
10625   case 'I':
10626   case 'J':
10627   case 'K':
10628   case 'L':
10629   case 'M':
10630   case 'N':
10631   case 'O':
10632   case 'P': {
10633     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10634     if (!CST) return; // Must be an immediate to match.
10635     int64_t Value = CST->getSExtValue();
10636     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10637                          // numbers are printed as such.
10638     switch (Letter) {
10639     default: llvm_unreachable("Unknown constraint letter!");
10640     case 'I':  // "I" is a signed 16-bit constant.
10641       if (isInt<16>(Value))
10642         Result = DAG.getTargetConstant(Value, TCVT);
10643       break;
10644     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10645       if (isShiftedUInt<16, 16>(Value))
10646         Result = DAG.getTargetConstant(Value, TCVT);
10647       break;
10648     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10649       if (isShiftedInt<16, 16>(Value))
10650         Result = DAG.getTargetConstant(Value, TCVT);
10651       break;
10652     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10653       if (isUInt<16>(Value))
10654         Result = DAG.getTargetConstant(Value, TCVT);
10655       break;
10656     case 'M':  // "M" is a constant that is greater than 31.
10657       if (Value > 31)
10658         Result = DAG.getTargetConstant(Value, TCVT);
10659       break;
10660     case 'N':  // "N" is a positive constant that is an exact power of two.
10661       if (Value > 0 && isPowerOf2_64(Value))
10662         Result = DAG.getTargetConstant(Value, TCVT);
10663       break;
10664     case 'O':  // "O" is the constant zero.
10665       if (Value == 0)
10666         Result = DAG.getTargetConstant(Value, TCVT);
10667       break;
10668     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10669       if (isInt<16>(-Value))
10670         Result = DAG.getTargetConstant(Value, TCVT);
10671       break;
10672     }
10673     break;
10674   }
10675   }
10676
10677   if (Result.getNode()) {
10678     Ops.push_back(Result);
10679     return;
10680   }
10681
10682   // Handle standard constraint letters.
10683   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10684 }
10685
10686 // isLegalAddressingMode - Return true if the addressing mode represented
10687 // by AM is legal for this target, for a load/store of the specified type.
10688 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10689                                               Type *Ty) const {
10690   // PPC does not allow r+i addressing modes for vectors!
10691   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10692     return false;
10693
10694   // PPC allows a sign-extended 16-bit immediate field.
10695   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10696     return false;
10697
10698   // No global is ever allowed as a base.
10699   if (AM.BaseGV)
10700     return false;
10701
10702   // PPC only support r+r,
10703   switch (AM.Scale) {
10704   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10705     break;
10706   case 1:
10707     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10708       return false;
10709     // Otherwise we have r+r or r+i.
10710     break;
10711   case 2:
10712     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10713       return false;
10714     // Allow 2*r as r+r.
10715     break;
10716   default:
10717     // No other scales are supported.
10718     return false;
10719   }
10720
10721   return true;
10722 }
10723
10724 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10725                                            SelectionDAG &DAG) const {
10726   MachineFunction &MF = DAG.getMachineFunction();
10727   MachineFrameInfo *MFI = MF.getFrameInfo();
10728   MFI->setReturnAddressIsTaken(true);
10729
10730   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10731     return SDValue();
10732
10733   SDLoc dl(Op);
10734   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10735
10736   // Make sure the function does not optimize away the store of the RA to
10737   // the stack.
10738   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10739   FuncInfo->setLRStoreRequired();
10740   bool isPPC64 = Subtarget.isPPC64();
10741
10742   if (Depth > 0) {
10743     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10744     SDValue Offset =
10745         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10746                         isPPC64 ? MVT::i64 : MVT::i32);
10747     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10748                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10749                                    FrameAddr, Offset),
10750                        MachinePointerInfo(), false, false, false, 0);
10751   }
10752
10753   // Just load the return address off the stack.
10754   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10755   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10756                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10757 }
10758
10759 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10760                                           SelectionDAG &DAG) const {
10761   SDLoc dl(Op);
10762   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10763
10764   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10765   bool isPPC64 = PtrVT == MVT::i64;
10766
10767   MachineFunction &MF = DAG.getMachineFunction();
10768   MachineFrameInfo *MFI = MF.getFrameInfo();
10769   MFI->setFrameAddressIsTaken(true);
10770
10771   // Naked functions never have a frame pointer, and so we use r1. For all
10772   // other functions, this decision must be delayed until during PEI.
10773   unsigned FrameReg;
10774   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10775     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10776   else
10777     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10778
10779   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10780                                          PtrVT);
10781   while (Depth--)
10782     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10783                             FrameAddr, MachinePointerInfo(), false, false,
10784                             false, 0);
10785   return FrameAddr;
10786 }
10787
10788 // FIXME? Maybe this could be a TableGen attribute on some registers and
10789 // this table could be generated automatically from RegInfo.
10790 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10791                                               EVT VT) const {
10792   bool isPPC64 = Subtarget.isPPC64();
10793   bool isDarwinABI = Subtarget.isDarwinABI();
10794
10795   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10796       (!isPPC64 && VT != MVT::i32))
10797     report_fatal_error("Invalid register global variable type");
10798
10799   bool is64Bit = isPPC64 && VT == MVT::i64;
10800   unsigned Reg = StringSwitch<unsigned>(RegName)
10801                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10802                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10803                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10804                                   (is64Bit ? PPC::X13 : PPC::R13))
10805                    .Default(0);
10806
10807   if (Reg)
10808     return Reg;
10809   report_fatal_error("Invalid register name global variable");
10810 }
10811
10812 bool
10813 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10814   // The PowerPC target isn't yet aware of offsets.
10815   return false;
10816 }
10817
10818 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10819                                            const CallInst &I,
10820                                            unsigned Intrinsic) const {
10821
10822   switch (Intrinsic) {
10823   case Intrinsic::ppc_qpx_qvlfd:
10824   case Intrinsic::ppc_qpx_qvlfs:
10825   case Intrinsic::ppc_qpx_qvlfcd:
10826   case Intrinsic::ppc_qpx_qvlfcs:
10827   case Intrinsic::ppc_qpx_qvlfiwa:
10828   case Intrinsic::ppc_qpx_qvlfiwz:
10829   case Intrinsic::ppc_altivec_lvx:
10830   case Intrinsic::ppc_altivec_lvxl:
10831   case Intrinsic::ppc_altivec_lvebx:
10832   case Intrinsic::ppc_altivec_lvehx:
10833   case Intrinsic::ppc_altivec_lvewx:
10834   case Intrinsic::ppc_vsx_lxvd2x:
10835   case Intrinsic::ppc_vsx_lxvw4x: {
10836     EVT VT;
10837     switch (Intrinsic) {
10838     case Intrinsic::ppc_altivec_lvebx:
10839       VT = MVT::i8;
10840       break;
10841     case Intrinsic::ppc_altivec_lvehx:
10842       VT = MVT::i16;
10843       break;
10844     case Intrinsic::ppc_altivec_lvewx:
10845       VT = MVT::i32;
10846       break;
10847     case Intrinsic::ppc_vsx_lxvd2x:
10848       VT = MVT::v2f64;
10849       break;
10850     case Intrinsic::ppc_qpx_qvlfd:
10851       VT = MVT::v4f64;
10852       break;
10853     case Intrinsic::ppc_qpx_qvlfs:
10854       VT = MVT::v4f32;
10855       break;
10856     case Intrinsic::ppc_qpx_qvlfcd:
10857       VT = MVT::v2f64;
10858       break;
10859     case Intrinsic::ppc_qpx_qvlfcs:
10860       VT = MVT::v2f32;
10861       break;
10862     default:
10863       VT = MVT::v4i32;
10864       break;
10865     }
10866
10867     Info.opc = ISD::INTRINSIC_W_CHAIN;
10868     Info.memVT = VT;
10869     Info.ptrVal = I.getArgOperand(0);
10870     Info.offset = -VT.getStoreSize()+1;
10871     Info.size = 2*VT.getStoreSize()-1;
10872     Info.align = 1;
10873     Info.vol = false;
10874     Info.readMem = true;
10875     Info.writeMem = false;
10876     return true;
10877   }
10878   case Intrinsic::ppc_qpx_qvlfda:
10879   case Intrinsic::ppc_qpx_qvlfsa:
10880   case Intrinsic::ppc_qpx_qvlfcda:
10881   case Intrinsic::ppc_qpx_qvlfcsa:
10882   case Intrinsic::ppc_qpx_qvlfiwaa:
10883   case Intrinsic::ppc_qpx_qvlfiwza: {
10884     EVT VT;
10885     switch (Intrinsic) {
10886     case Intrinsic::ppc_qpx_qvlfda:
10887       VT = MVT::v4f64;
10888       break;
10889     case Intrinsic::ppc_qpx_qvlfsa:
10890       VT = MVT::v4f32;
10891       break;
10892     case Intrinsic::ppc_qpx_qvlfcda:
10893       VT = MVT::v2f64;
10894       break;
10895     case Intrinsic::ppc_qpx_qvlfcsa:
10896       VT = MVT::v2f32;
10897       break;
10898     default:
10899       VT = MVT::v4i32;
10900       break;
10901     }
10902
10903     Info.opc = ISD::INTRINSIC_W_CHAIN;
10904     Info.memVT = VT;
10905     Info.ptrVal = I.getArgOperand(0);
10906     Info.offset = 0;
10907     Info.size = VT.getStoreSize();
10908     Info.align = 1;
10909     Info.vol = false;
10910     Info.readMem = true;
10911     Info.writeMem = false;
10912     return true;
10913   }
10914   case Intrinsic::ppc_qpx_qvstfd:
10915   case Intrinsic::ppc_qpx_qvstfs:
10916   case Intrinsic::ppc_qpx_qvstfcd:
10917   case Intrinsic::ppc_qpx_qvstfcs:
10918   case Intrinsic::ppc_qpx_qvstfiw:
10919   case Intrinsic::ppc_altivec_stvx:
10920   case Intrinsic::ppc_altivec_stvxl:
10921   case Intrinsic::ppc_altivec_stvebx:
10922   case Intrinsic::ppc_altivec_stvehx:
10923   case Intrinsic::ppc_altivec_stvewx:
10924   case Intrinsic::ppc_vsx_stxvd2x:
10925   case Intrinsic::ppc_vsx_stxvw4x: {
10926     EVT VT;
10927     switch (Intrinsic) {
10928     case Intrinsic::ppc_altivec_stvebx:
10929       VT = MVT::i8;
10930       break;
10931     case Intrinsic::ppc_altivec_stvehx:
10932       VT = MVT::i16;
10933       break;
10934     case Intrinsic::ppc_altivec_stvewx:
10935       VT = MVT::i32;
10936       break;
10937     case Intrinsic::ppc_vsx_stxvd2x:
10938       VT = MVT::v2f64;
10939       break;
10940     case Intrinsic::ppc_qpx_qvstfd:
10941       VT = MVT::v4f64;
10942       break;
10943     case Intrinsic::ppc_qpx_qvstfs:
10944       VT = MVT::v4f32;
10945       break;
10946     case Intrinsic::ppc_qpx_qvstfcd:
10947       VT = MVT::v2f64;
10948       break;
10949     case Intrinsic::ppc_qpx_qvstfcs:
10950       VT = MVT::v2f32;
10951       break;
10952     default:
10953       VT = MVT::v4i32;
10954       break;
10955     }
10956
10957     Info.opc = ISD::INTRINSIC_VOID;
10958     Info.memVT = VT;
10959     Info.ptrVal = I.getArgOperand(1);
10960     Info.offset = -VT.getStoreSize()+1;
10961     Info.size = 2*VT.getStoreSize()-1;
10962     Info.align = 1;
10963     Info.vol = false;
10964     Info.readMem = false;
10965     Info.writeMem = true;
10966     return true;
10967   }
10968   case Intrinsic::ppc_qpx_qvstfda:
10969   case Intrinsic::ppc_qpx_qvstfsa:
10970   case Intrinsic::ppc_qpx_qvstfcda:
10971   case Intrinsic::ppc_qpx_qvstfcsa:
10972   case Intrinsic::ppc_qpx_qvstfiwa: {
10973     EVT VT;
10974     switch (Intrinsic) {
10975     case Intrinsic::ppc_qpx_qvstfda:
10976       VT = MVT::v4f64;
10977       break;
10978     case Intrinsic::ppc_qpx_qvstfsa:
10979       VT = MVT::v4f32;
10980       break;
10981     case Intrinsic::ppc_qpx_qvstfcda:
10982       VT = MVT::v2f64;
10983       break;
10984     case Intrinsic::ppc_qpx_qvstfcsa:
10985       VT = MVT::v2f32;
10986       break;
10987     default:
10988       VT = MVT::v4i32;
10989       break;
10990     }
10991
10992     Info.opc = ISD::INTRINSIC_VOID;
10993     Info.memVT = VT;
10994     Info.ptrVal = I.getArgOperand(1);
10995     Info.offset = 0;
10996     Info.size = VT.getStoreSize();
10997     Info.align = 1;
10998     Info.vol = false;
10999     Info.readMem = false;
11000     Info.writeMem = true;
11001     return true;
11002   }
11003   default:
11004     break;
11005   }
11006
11007   return false;
11008 }
11009
11010 /// getOptimalMemOpType - Returns the target specific optimal type for load
11011 /// and store operations as a result of memset, memcpy, and memmove
11012 /// lowering. If DstAlign is zero that means it's safe to destination
11013 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11014 /// means there isn't a need to check it against alignment requirement,
11015 /// probably because the source does not need to be loaded. If 'IsMemset' is
11016 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11017 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11018 /// source is constant so it does not need to be loaded.
11019 /// It returns EVT::Other if the type should be determined using generic
11020 /// target-independent logic.
11021 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11022                                            unsigned DstAlign, unsigned SrcAlign,
11023                                            bool IsMemset, bool ZeroMemset,
11024                                            bool MemcpyStrSrc,
11025                                            MachineFunction &MF) const {
11026   const Function *F = MF.getFunction();
11027   // When expanding a memset, require at least two QPX instructions to cover
11028   // the cost of loading the value to be stored from the constant pool.
11029   if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11030      (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11031       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11032     return MVT::v4f64;
11033   }
11034
11035   // We should use Altivec/VSX loads and stores when available. For unaligned
11036   // addresses, unaligned VSX loads are only fast starting with the P8.
11037   if (Subtarget.hasAltivec() && Size >= 16 &&
11038       (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11039        ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11040     return MVT::v4i32;
11041
11042   if (Subtarget.isPPC64()) {
11043     return MVT::i64;
11044   }
11045
11046   return MVT::i32;
11047 }
11048
11049 /// \brief Returns true if it is beneficial to convert a load of a constant
11050 /// to just the constant itself.
11051 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11052                                                           Type *Ty) const {
11053   assert(Ty->isIntegerTy());
11054
11055   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11056   if (BitSize == 0 || BitSize > 64)
11057     return false;
11058   return true;
11059 }
11060
11061 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11062   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11063     return false;
11064   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11065   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11066   return NumBits1 == 64 && NumBits2 == 32;
11067 }
11068
11069 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11070   if (!VT1.isInteger() || !VT2.isInteger())
11071     return false;
11072   unsigned NumBits1 = VT1.getSizeInBits();
11073   unsigned NumBits2 = VT2.getSizeInBits();
11074   return NumBits1 == 64 && NumBits2 == 32;
11075 }
11076
11077 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11078   // Generally speaking, zexts are not free, but they are free when they can be
11079   // folded with other operations.
11080   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11081     EVT MemVT = LD->getMemoryVT();
11082     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11083          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11084         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11085          LD->getExtensionType() == ISD::ZEXTLOAD))
11086       return true;
11087   }
11088
11089   // FIXME: Add other cases...
11090   //  - 32-bit shifts with a zext to i64
11091   //  - zext after ctlz, bswap, etc.
11092   //  - zext after and by a constant mask
11093
11094   return TargetLowering::isZExtFree(Val, VT2);
11095 }
11096
11097 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11098   assert(VT.isFloatingPoint());
11099   return true;
11100 }
11101
11102 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11103   return isInt<16>(Imm) || isUInt<16>(Imm);
11104 }
11105
11106 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11107   return isInt<16>(Imm) || isUInt<16>(Imm);
11108 }
11109
11110 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11111                                                        unsigned,
11112                                                        unsigned,
11113                                                        bool *Fast) const {
11114   if (DisablePPCUnaligned)
11115     return false;
11116
11117   // PowerPC supports unaligned memory access for simple non-vector types.
11118   // Although accessing unaligned addresses is not as efficient as accessing
11119   // aligned addresses, it is generally more efficient than manual expansion,
11120   // and generally only traps for software emulation when crossing page
11121   // boundaries.
11122
11123   if (!VT.isSimple())
11124     return false;
11125
11126   if (VT.getSimpleVT().isVector()) {
11127     if (Subtarget.hasVSX()) {
11128       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11129           VT != MVT::v4f32 && VT != MVT::v4i32)
11130         return false;
11131     } else {
11132       return false;
11133     }
11134   }
11135
11136   if (VT == MVT::ppcf128)
11137     return false;
11138
11139   if (Fast)
11140     *Fast = true;
11141
11142   return true;
11143 }
11144
11145 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11146   VT = VT.getScalarType();
11147
11148   if (!VT.isSimple())
11149     return false;
11150
11151   switch (VT.getSimpleVT().SimpleTy) {
11152   case MVT::f32:
11153   case MVT::f64:
11154     return true;
11155   default:
11156     break;
11157   }
11158
11159   return false;
11160 }
11161
11162 const MCPhysReg *
11163 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11164   // LR is a callee-save register, but we must treat it as clobbered by any call
11165   // site. Hence we include LR in the scratch registers, which are in turn added
11166   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11167   // to CTR, which is used by any indirect call.
11168   static const MCPhysReg ScratchRegs[] = {
11169     PPC::X12, PPC::LR8, PPC::CTR8, 0
11170   };
11171
11172   return ScratchRegs;
11173 }
11174
11175 bool
11176 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11177                      EVT VT , unsigned DefinedValues) const {
11178   if (VT == MVT::v2i64)
11179     return false;
11180
11181   if (Subtarget.hasQPX()) {
11182     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11183       return true;
11184   }
11185
11186   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11187 }
11188
11189 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11190   if (DisableILPPref || Subtarget.enableMachineScheduler())
11191     return TargetLowering::getSchedulingPreference(N);
11192
11193   return Sched::ILP;
11194 }
11195
11196 // Create a fast isel object.
11197 FastISel *
11198 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11199                                   const TargetLibraryInfo *LibInfo) const {
11200   return PPC::createFastISel(FuncInfo, LibInfo);
11201 }