Allow memory intrinsics to be tail calls
[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::MFVSR:           return "PPCISD::MFVSR";
1000   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1001   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1002   case PPCISD::VCMP:            return "PPCISD::VCMP";
1003   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1004   case PPCISD::LBRX:            return "PPCISD::LBRX";
1005   case PPCISD::STBRX:           return "PPCISD::STBRX";
1006   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1007   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1008   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1009   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1010   case PPCISD::BDZ:             return "PPCISD::BDZ";
1011   case PPCISD::MFFS:            return "PPCISD::MFFS";
1012   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1013   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1014   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1015   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1016   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1017   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1018   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1019   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1020   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1021   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1022   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1023   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1024   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1025   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1026   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1027   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1028   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1029   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1030   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1031   case PPCISD::SC:              return "PPCISD::SC";
1032   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1033   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1034   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1035   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1036   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1037   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1038   }
1039 }
1040
1041 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1042   if (!VT.isVector())
1043     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1044
1045   if (Subtarget.hasQPX())
1046     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1047
1048   return VT.changeVectorElementTypeToInteger();
1049 }
1050
1051 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1052   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1053   return true;
1054 }
1055
1056 //===----------------------------------------------------------------------===//
1057 // Node matching predicates, for use by the tblgen matching code.
1058 //===----------------------------------------------------------------------===//
1059
1060 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1061 static bool isFloatingPointZero(SDValue Op) {
1062   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1063     return CFP->getValueAPF().isZero();
1064   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1065     // Maybe this has already been legalized into the constant pool?
1066     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1067       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1068         return CFP->getValueAPF().isZero();
1069   }
1070   return false;
1071 }
1072
1073 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1074 /// true if Op is undef or if it matches the specified value.
1075 static bool isConstantOrUndef(int Op, int Val) {
1076   return Op < 0 || Op == Val;
1077 }
1078
1079 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1080 /// VPKUHUM instruction.
1081 /// The ShuffleKind distinguishes between big-endian operations with
1082 /// two different inputs (0), either-endian operations with two identical
1083 /// inputs (1), and little-endian operantion with two different inputs (2).
1084 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1085 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1086                                SelectionDAG &DAG) {
1087   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1088   if (ShuffleKind == 0) {
1089     if (IsLE)
1090       return false;
1091     for (unsigned i = 0; i != 16; ++i)
1092       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1093         return false;
1094   } else if (ShuffleKind == 2) {
1095     if (!IsLE)
1096       return false;
1097     for (unsigned i = 0; i != 16; ++i)
1098       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1099         return false;
1100   } else if (ShuffleKind == 1) {
1101     unsigned j = IsLE ? 0 : 1;
1102     for (unsigned i = 0; i != 8; ++i)
1103       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1104           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1105         return false;
1106   }
1107   return true;
1108 }
1109
1110 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1111 /// VPKUWUM instruction.
1112 /// The ShuffleKind distinguishes between big-endian operations with
1113 /// two different inputs (0), either-endian operations with two identical
1114 /// inputs (1), and little-endian operantion with two different inputs (2).
1115 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1116 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1117                                SelectionDAG &DAG) {
1118   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1119   if (ShuffleKind == 0) {
1120     if (IsLE)
1121       return false;
1122     for (unsigned i = 0; i != 16; i += 2)
1123       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1124           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1125         return false;
1126   } else if (ShuffleKind == 2) {
1127     if (!IsLE)
1128       return false;
1129     for (unsigned i = 0; i != 16; i += 2)
1130       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1131           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1132         return false;
1133   } else if (ShuffleKind == 1) {
1134     unsigned j = IsLE ? 0 : 2;
1135     for (unsigned i = 0; i != 8; i += 2)
1136       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1137           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1138           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1139           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1140         return false;
1141   }
1142   return true;
1143 }
1144
1145 /// isVMerge - Common function, used to match vmrg* shuffles.
1146 ///
1147 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1148                      unsigned LHSStart, unsigned RHSStart) {
1149   if (N->getValueType(0) != MVT::v16i8)
1150     return false;
1151   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1152          "Unsupported merge size!");
1153
1154   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1155     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1156       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1157                              LHSStart+j+i*UnitSize) ||
1158           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1159                              RHSStart+j+i*UnitSize))
1160         return false;
1161     }
1162   return true;
1163 }
1164
1165 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1166 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1167 /// The ShuffleKind distinguishes between big-endian merges with two 
1168 /// different inputs (0), either-endian merges with two identical inputs (1),
1169 /// and little-endian merges with two different inputs (2).  For the latter,
1170 /// the input operands are swapped (see PPCInstrAltivec.td).
1171 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1172                              unsigned ShuffleKind, SelectionDAG &DAG) {
1173   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1174     if (ShuffleKind == 1) // unary
1175       return isVMerge(N, UnitSize, 0, 0);
1176     else if (ShuffleKind == 2) // swapped
1177       return isVMerge(N, UnitSize, 0, 16);
1178     else
1179       return false;
1180   } else {
1181     if (ShuffleKind == 1) // unary
1182       return isVMerge(N, UnitSize, 8, 8);
1183     else if (ShuffleKind == 0) // normal
1184       return isVMerge(N, UnitSize, 8, 24);
1185     else
1186       return false;
1187   }
1188 }
1189
1190 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1191 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1192 /// The ShuffleKind distinguishes between big-endian merges with two 
1193 /// different inputs (0), either-endian merges with two identical inputs (1),
1194 /// and little-endian merges with two different inputs (2).  For the latter,
1195 /// the input operands are swapped (see PPCInstrAltivec.td).
1196 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1197                              unsigned ShuffleKind, SelectionDAG &DAG) {
1198   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1199     if (ShuffleKind == 1) // unary
1200       return isVMerge(N, UnitSize, 8, 8);
1201     else if (ShuffleKind == 2) // swapped
1202       return isVMerge(N, UnitSize, 8, 24);
1203     else
1204       return false;
1205   } else {
1206     if (ShuffleKind == 1) // unary
1207       return isVMerge(N, UnitSize, 0, 0);
1208     else if (ShuffleKind == 0) // normal
1209       return isVMerge(N, UnitSize, 0, 16);
1210     else
1211       return false;
1212   }
1213 }
1214
1215
1216 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1217 /// amount, otherwise return -1.
1218 /// The ShuffleKind distinguishes between big-endian operations with two 
1219 /// different inputs (0), either-endian operations with two identical inputs
1220 /// (1), and little-endian operations with two different inputs (2).  For the
1221 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1222 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1223                              SelectionDAG &DAG) {
1224   if (N->getValueType(0) != MVT::v16i8)
1225     return -1;
1226
1227   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1228
1229   // Find the first non-undef value in the shuffle mask.
1230   unsigned i;
1231   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1232     /*search*/;
1233
1234   if (i == 16) return -1;  // all undef.
1235
1236   // Otherwise, check to see if the rest of the elements are consecutively
1237   // numbered from this value.
1238   unsigned ShiftAmt = SVOp->getMaskElt(i);
1239   if (ShiftAmt < i) return -1;
1240
1241   ShiftAmt -= i;
1242   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1243
1244   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1245     // Check the rest of the elements to see if they are consecutive.
1246     for (++i; i != 16; ++i)
1247       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1248         return -1;
1249   } else if (ShuffleKind == 1) {
1250     // Check the rest of the elements to see if they are consecutive.
1251     for (++i; i != 16; ++i)
1252       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1253         return -1;
1254   } else
1255     return -1;
1256
1257   if (ShuffleKind == 2 && isLE)
1258     ShiftAmt = 16 - ShiftAmt;
1259
1260   return ShiftAmt;
1261 }
1262
1263 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1264 /// specifies a splat of a single element that is suitable for input to
1265 /// VSPLTB/VSPLTH/VSPLTW.
1266 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1267   assert(N->getValueType(0) == MVT::v16i8 &&
1268          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1269
1270   // This is a splat operation if each element of the permute is the same, and
1271   // if the value doesn't reference the second vector.
1272   unsigned ElementBase = N->getMaskElt(0);
1273
1274   // FIXME: Handle UNDEF elements too!
1275   if (ElementBase >= 16)
1276     return false;
1277
1278   // Check that the indices are consecutive, in the case of a multi-byte element
1279   // splatted with a v16i8 mask.
1280   for (unsigned i = 1; i != EltSize; ++i)
1281     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1282       return false;
1283
1284   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1285     if (N->getMaskElt(i) < 0) continue;
1286     for (unsigned j = 0; j != EltSize; ++j)
1287       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1288         return false;
1289   }
1290   return true;
1291 }
1292
1293 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1294 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1295 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1296                                 SelectionDAG &DAG) {
1297   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1298   assert(isSplatShuffleMask(SVOp, EltSize));
1299   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1300     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1301   else
1302     return SVOp->getMaskElt(0) / EltSize;
1303 }
1304
1305 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1306 /// by using a vspltis[bhw] instruction of the specified element size, return
1307 /// the constant being splatted.  The ByteSize field indicates the number of
1308 /// bytes of each element [124] -> [bhw].
1309 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1310   SDValue OpVal(nullptr, 0);
1311
1312   // If ByteSize of the splat is bigger than the element size of the
1313   // build_vector, then we have a case where we are checking for a splat where
1314   // multiple elements of the buildvector are folded together into a single
1315   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1316   unsigned EltSize = 16/N->getNumOperands();
1317   if (EltSize < ByteSize) {
1318     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1319     SDValue UniquedVals[4];
1320     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1321
1322     // See if all of the elements in the buildvector agree across.
1323     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1324       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1325       // If the element isn't a constant, bail fully out.
1326       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1327
1328
1329       if (!UniquedVals[i&(Multiple-1)].getNode())
1330         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1331       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1332         return SDValue();  // no match.
1333     }
1334
1335     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1336     // either constant or undef values that are identical for each chunk.  See
1337     // if these chunks can form into a larger vspltis*.
1338
1339     // Check to see if all of the leading entries are either 0 or -1.  If
1340     // neither, then this won't fit into the immediate field.
1341     bool LeadingZero = true;
1342     bool LeadingOnes = true;
1343     for (unsigned i = 0; i != Multiple-1; ++i) {
1344       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1345
1346       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1347       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1348     }
1349     // Finally, check the least significant entry.
1350     if (LeadingZero) {
1351       if (!UniquedVals[Multiple-1].getNode())
1352         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1353       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1354       if (Val < 16)
1355         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1356     }
1357     if (LeadingOnes) {
1358       if (!UniquedVals[Multiple-1].getNode())
1359         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1360       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1361       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1362         return DAG.getTargetConstant(Val, MVT::i32);
1363     }
1364
1365     return SDValue();
1366   }
1367
1368   // Check to see if this buildvec has a single non-undef value in its elements.
1369   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1370     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1371     if (!OpVal.getNode())
1372       OpVal = N->getOperand(i);
1373     else if (OpVal != N->getOperand(i))
1374       return SDValue();
1375   }
1376
1377   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1378
1379   unsigned ValSizeInBytes = EltSize;
1380   uint64_t Value = 0;
1381   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1382     Value = CN->getZExtValue();
1383   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1384     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1385     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1386   }
1387
1388   // If the splat value is larger than the element value, then we can never do
1389   // this splat.  The only case that we could fit the replicated bits into our
1390   // immediate field for would be zero, and we prefer to use vxor for it.
1391   if (ValSizeInBytes < ByteSize) return SDValue();
1392
1393   // If the element value is larger than the splat value, check if it consists
1394   // of a repeated bit pattern of size ByteSize.
1395   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1396     return SDValue();
1397
1398   // Properly sign extend the value.
1399   int MaskVal = SignExtend32(Value, ByteSize * 8);
1400
1401   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1402   if (MaskVal == 0) return SDValue();
1403
1404   // Finally, if this value fits in a 5 bit sext field, return it
1405   if (SignExtend32<5>(MaskVal) == MaskVal)
1406     return DAG.getTargetConstant(MaskVal, MVT::i32);
1407   return SDValue();
1408 }
1409
1410 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1411 /// amount, otherwise return -1.
1412 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1413   EVT VT = N->getValueType(0);
1414   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1415     return -1;
1416
1417   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1418
1419   // Find the first non-undef value in the shuffle mask.
1420   unsigned i;
1421   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1422     /*search*/;
1423
1424   if (i == 4) return -1;  // all undef.
1425
1426   // Otherwise, check to see if the rest of the elements are consecutively
1427   // numbered from this value.
1428   unsigned ShiftAmt = SVOp->getMaskElt(i);
1429   if (ShiftAmt < i) return -1;
1430   ShiftAmt -= i;
1431
1432   // Check the rest of the elements to see if they are consecutive.
1433   for (++i; i != 4; ++i)
1434     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1435       return -1;
1436
1437   return ShiftAmt;
1438 }
1439
1440 //===----------------------------------------------------------------------===//
1441 //  Addressing Mode Selection
1442 //===----------------------------------------------------------------------===//
1443
1444 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1445 /// or 64-bit immediate, and if the value can be accurately represented as a
1446 /// sign extension from a 16-bit value.  If so, this returns true and the
1447 /// immediate.
1448 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1449   if (!isa<ConstantSDNode>(N))
1450     return false;
1451
1452   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1453   if (N->getValueType(0) == MVT::i32)
1454     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1455   else
1456     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1457 }
1458 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1459   return isIntS16Immediate(Op.getNode(), Imm);
1460 }
1461
1462
1463 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1464 /// can be represented as an indexed [r+r] operation.  Returns false if it
1465 /// can be more efficiently represented with [r+imm].
1466 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1467                                             SDValue &Index,
1468                                             SelectionDAG &DAG) const {
1469   short imm = 0;
1470   if (N.getOpcode() == ISD::ADD) {
1471     if (isIntS16Immediate(N.getOperand(1), imm))
1472       return false;    // r+i
1473     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1474       return false;    // r+i
1475
1476     Base = N.getOperand(0);
1477     Index = N.getOperand(1);
1478     return true;
1479   } else if (N.getOpcode() == ISD::OR) {
1480     if (isIntS16Immediate(N.getOperand(1), imm))
1481       return false;    // r+i can fold it if we can.
1482
1483     // If this is an or of disjoint bitfields, we can codegen this as an add
1484     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1485     // disjoint.
1486     APInt LHSKnownZero, LHSKnownOne;
1487     APInt RHSKnownZero, RHSKnownOne;
1488     DAG.computeKnownBits(N.getOperand(0),
1489                          LHSKnownZero, LHSKnownOne);
1490
1491     if (LHSKnownZero.getBoolValue()) {
1492       DAG.computeKnownBits(N.getOperand(1),
1493                            RHSKnownZero, RHSKnownOne);
1494       // If all of the bits are known zero on the LHS or RHS, the add won't
1495       // carry.
1496       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1497         Base = N.getOperand(0);
1498         Index = N.getOperand(1);
1499         return true;
1500       }
1501     }
1502   }
1503
1504   return false;
1505 }
1506
1507 // If we happen to be doing an i64 load or store into a stack slot that has
1508 // less than a 4-byte alignment, then the frame-index elimination may need to
1509 // use an indexed load or store instruction (because the offset may not be a
1510 // multiple of 4). The extra register needed to hold the offset comes from the
1511 // register scavenger, and it is possible that the scavenger will need to use
1512 // an emergency spill slot. As a result, we need to make sure that a spill slot
1513 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1514 // stack slot.
1515 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1516   // FIXME: This does not handle the LWA case.
1517   if (VT != MVT::i64)
1518     return;
1519
1520   // NOTE: We'll exclude negative FIs here, which come from argument
1521   // lowering, because there are no known test cases triggering this problem
1522   // using packed structures (or similar). We can remove this exclusion if
1523   // we find such a test case. The reason why this is so test-case driven is
1524   // because this entire 'fixup' is only to prevent crashes (from the
1525   // register scavenger) on not-really-valid inputs. For example, if we have:
1526   //   %a = alloca i1
1527   //   %b = bitcast i1* %a to i64*
1528   //   store i64* a, i64 b
1529   // then the store should really be marked as 'align 1', but is not. If it
1530   // were marked as 'align 1' then the indexed form would have been
1531   // instruction-selected initially, and the problem this 'fixup' is preventing
1532   // won't happen regardless.
1533   if (FrameIdx < 0)
1534     return;
1535
1536   MachineFunction &MF = DAG.getMachineFunction();
1537   MachineFrameInfo *MFI = MF.getFrameInfo();
1538
1539   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1540   if (Align >= 4)
1541     return;
1542
1543   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1544   FuncInfo->setHasNonRISpills();
1545 }
1546
1547 /// Returns true if the address N can be represented by a base register plus
1548 /// a signed 16-bit displacement [r+imm], and if it is not better
1549 /// represented as reg+reg.  If Aligned is true, only accept displacements
1550 /// suitable for STD and friends, i.e. multiples of 4.
1551 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1552                                             SDValue &Base,
1553                                             SelectionDAG &DAG,
1554                                             bool Aligned) const {
1555   // FIXME dl should come from parent load or store, not from address
1556   SDLoc dl(N);
1557   // If this can be more profitably realized as r+r, fail.
1558   if (SelectAddressRegReg(N, Disp, Base, DAG))
1559     return false;
1560
1561   if (N.getOpcode() == ISD::ADD) {
1562     short imm = 0;
1563     if (isIntS16Immediate(N.getOperand(1), imm) &&
1564         (!Aligned || (imm & 3) == 0)) {
1565       Disp = DAG.getTargetConstant(imm, N.getValueType());
1566       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1567         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1568         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1569       } else {
1570         Base = N.getOperand(0);
1571       }
1572       return true; // [r+i]
1573     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1574       // Match LOAD (ADD (X, Lo(G))).
1575       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1576              && "Cannot handle constant offsets yet!");
1577       Disp = N.getOperand(1).getOperand(0);  // The global address.
1578       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1579              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1580              Disp.getOpcode() == ISD::TargetConstantPool ||
1581              Disp.getOpcode() == ISD::TargetJumpTable);
1582       Base = N.getOperand(0);
1583       return true;  // [&g+r]
1584     }
1585   } else if (N.getOpcode() == ISD::OR) {
1586     short imm = 0;
1587     if (isIntS16Immediate(N.getOperand(1), imm) &&
1588         (!Aligned || (imm & 3) == 0)) {
1589       // If this is an or of disjoint bitfields, we can codegen this as an add
1590       // (for better address arithmetic) if the LHS and RHS of the OR are
1591       // provably disjoint.
1592       APInt LHSKnownZero, LHSKnownOne;
1593       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1594
1595       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1596         // If all of the bits are known zero on the LHS or RHS, the add won't
1597         // carry.
1598         if (FrameIndexSDNode *FI =
1599               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1600           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1601           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1602         } else {
1603           Base = N.getOperand(0);
1604         }
1605         Disp = DAG.getTargetConstant(imm, N.getValueType());
1606         return true;
1607       }
1608     }
1609   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1610     // Loading from a constant address.
1611
1612     // If this address fits entirely in a 16-bit sext immediate field, codegen
1613     // this as "d, 0"
1614     short Imm;
1615     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1616       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1617       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1618                              CN->getValueType(0));
1619       return true;
1620     }
1621
1622     // Handle 32-bit sext immediates with LIS + addr mode.
1623     if ((CN->getValueType(0) == MVT::i32 ||
1624          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1625         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1626       int Addr = (int)CN->getZExtValue();
1627
1628       // Otherwise, break this down into an LIS + disp.
1629       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1630
1631       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1632       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1633       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1634       return true;
1635     }
1636   }
1637
1638   Disp = DAG.getTargetConstant(0, getPointerTy());
1639   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1640     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1641     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1642   } else
1643     Base = N;
1644   return true;      // [r+0]
1645 }
1646
1647 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1648 /// represented as an indexed [r+r] operation.
1649 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1650                                                 SDValue &Index,
1651                                                 SelectionDAG &DAG) const {
1652   // Check to see if we can easily represent this as an [r+r] address.  This
1653   // will fail if it thinks that the address is more profitably represented as
1654   // reg+imm, e.g. where imm = 0.
1655   if (SelectAddressRegReg(N, Base, Index, DAG))
1656     return true;
1657
1658   // If the operand is an addition, always emit this as [r+r], since this is
1659   // better (for code size, and execution, as the memop does the add for free)
1660   // than emitting an explicit add.
1661   if (N.getOpcode() == ISD::ADD) {
1662     Base = N.getOperand(0);
1663     Index = N.getOperand(1);
1664     return true;
1665   }
1666
1667   // Otherwise, do it the hard way, using R0 as the base register.
1668   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1669                          N.getValueType());
1670   Index = N;
1671   return true;
1672 }
1673
1674 /// getPreIndexedAddressParts - returns true by value, base pointer and
1675 /// offset pointer and addressing mode by reference if the node's address
1676 /// can be legally represented as pre-indexed load / store address.
1677 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1678                                                   SDValue &Offset,
1679                                                   ISD::MemIndexedMode &AM,
1680                                                   SelectionDAG &DAG) const {
1681   if (DisablePPCPreinc) return false;
1682
1683   bool isLoad = true;
1684   SDValue Ptr;
1685   EVT VT;
1686   unsigned Alignment;
1687   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1688     Ptr = LD->getBasePtr();
1689     VT = LD->getMemoryVT();
1690     Alignment = LD->getAlignment();
1691   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1692     Ptr = ST->getBasePtr();
1693     VT  = ST->getMemoryVT();
1694     Alignment = ST->getAlignment();
1695     isLoad = false;
1696   } else
1697     return false;
1698
1699   // PowerPC doesn't have preinc load/store instructions for vectors (except
1700   // for QPX, which does have preinc r+r forms).
1701   if (VT.isVector()) {
1702     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1703       return false;
1704     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1705       AM = ISD::PRE_INC;
1706       return true;
1707     }
1708   }
1709
1710   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1711
1712     // Common code will reject creating a pre-inc form if the base pointer
1713     // is a frame index, or if N is a store and the base pointer is either
1714     // the same as or a predecessor of the value being stored.  Check for
1715     // those situations here, and try with swapped Base/Offset instead.
1716     bool Swap = false;
1717
1718     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1719       Swap = true;
1720     else if (!isLoad) {
1721       SDValue Val = cast<StoreSDNode>(N)->getValue();
1722       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1723         Swap = true;
1724     }
1725
1726     if (Swap)
1727       std::swap(Base, Offset);
1728
1729     AM = ISD::PRE_INC;
1730     return true;
1731   }
1732
1733   // LDU/STU can only handle immediates that are a multiple of 4.
1734   if (VT != MVT::i64) {
1735     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1736       return false;
1737   } else {
1738     // LDU/STU need an address with at least 4-byte alignment.
1739     if (Alignment < 4)
1740       return false;
1741
1742     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1743       return false;
1744   }
1745
1746   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1747     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1748     // sext i32 to i64 when addr mode is r+i.
1749     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1750         LD->getExtensionType() == ISD::SEXTLOAD &&
1751         isa<ConstantSDNode>(Offset))
1752       return false;
1753   }
1754
1755   AM = ISD::PRE_INC;
1756   return true;
1757 }
1758
1759 //===----------------------------------------------------------------------===//
1760 //  LowerOperation implementation
1761 //===----------------------------------------------------------------------===//
1762
1763 /// GetLabelAccessInfo - Return true if we should reference labels using a
1764 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1765 static bool GetLabelAccessInfo(const TargetMachine &TM,
1766                                const PPCSubtarget &Subtarget,
1767                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1768                                const GlobalValue *GV = nullptr) {
1769   HiOpFlags = PPCII::MO_HA;
1770   LoOpFlags = PPCII::MO_LO;
1771
1772   // Don't use the pic base if not in PIC relocation model.
1773   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1774
1775   if (isPIC) {
1776     HiOpFlags |= PPCII::MO_PIC_FLAG;
1777     LoOpFlags |= PPCII::MO_PIC_FLAG;
1778   }
1779
1780   // If this is a reference to a global value that requires a non-lazy-ptr, make
1781   // sure that instruction lowering adds it.
1782   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1783     HiOpFlags |= PPCII::MO_NLP_FLAG;
1784     LoOpFlags |= PPCII::MO_NLP_FLAG;
1785
1786     if (GV->hasHiddenVisibility()) {
1787       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1788       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1789     }
1790   }
1791
1792   return isPIC;
1793 }
1794
1795 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1796                              SelectionDAG &DAG) {
1797   EVT PtrVT = HiPart.getValueType();
1798   SDValue Zero = DAG.getConstant(0, PtrVT);
1799   SDLoc DL(HiPart);
1800
1801   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1802   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1803
1804   // With PIC, the first instruction is actually "GR+hi(&G)".
1805   if (isPIC)
1806     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1807                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1808
1809   // Generate non-pic code that has direct accesses to the constant pool.
1810   // The address of the global is just (hi(&g)+lo(&g)).
1811   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1812 }
1813
1814 static void setUsesTOCBasePtr(MachineFunction &MF) {
1815   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1816   FuncInfo->setUsesTOCBasePtr();
1817 }
1818
1819 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1820   setUsesTOCBasePtr(DAG.getMachineFunction());
1821 }
1822
1823 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1824                            SDValue GA) {
1825   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1826   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1827                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1828
1829   SDValue Ops[] = { GA, Reg };
1830   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1831                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1832                                  MachinePointerInfo::getGOT(), 0, false, true,
1833                                  false, 0);
1834 }
1835
1836 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1837                                              SelectionDAG &DAG) const {
1838   EVT PtrVT = Op.getValueType();
1839   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1840   const Constant *C = CP->getConstVal();
1841
1842   // 64-bit SVR4 ABI code is always position-independent.
1843   // The actual address of the GlobalValue is stored in the TOC.
1844   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1845     setUsesTOCBasePtr(DAG);
1846     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1847     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1848   }
1849
1850   unsigned MOHiFlag, MOLoFlag;
1851   bool isPIC =
1852       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1853
1854   if (isPIC && Subtarget.isSVR4ABI()) {
1855     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1856                                            PPCII::MO_PIC_FLAG);
1857     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1858   }
1859
1860   SDValue CPIHi =
1861     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1862   SDValue CPILo =
1863     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1864   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1865 }
1866
1867 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1868   EVT PtrVT = Op.getValueType();
1869   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1870
1871   // 64-bit SVR4 ABI code is always position-independent.
1872   // The actual address of the GlobalValue is stored in the TOC.
1873   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1874     setUsesTOCBasePtr(DAG);
1875     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1876     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1877   }
1878
1879   unsigned MOHiFlag, MOLoFlag;
1880   bool isPIC =
1881       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1882
1883   if (isPIC && Subtarget.isSVR4ABI()) {
1884     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1885                                         PPCII::MO_PIC_FLAG);
1886     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1887   }
1888
1889   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1890   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1891   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1892 }
1893
1894 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1895                                              SelectionDAG &DAG) const {
1896   EVT PtrVT = Op.getValueType();
1897   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1898   const BlockAddress *BA = BASDN->getBlockAddress();
1899
1900   // 64-bit SVR4 ABI code is always position-independent.
1901   // The actual BlockAddress is stored in the TOC.
1902   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1903     setUsesTOCBasePtr(DAG);
1904     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1905     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1906   }
1907
1908   unsigned MOHiFlag, MOLoFlag;
1909   bool isPIC =
1910       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1911   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1912   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1913   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1914 }
1915
1916 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1917                                               SelectionDAG &DAG) const {
1918
1919   // FIXME: TLS addresses currently use medium model code sequences,
1920   // which is the most useful form.  Eventually support for small and
1921   // large models could be added if users need it, at the cost of
1922   // additional complexity.
1923   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1924   SDLoc dl(GA);
1925   const GlobalValue *GV = GA->getGlobal();
1926   EVT PtrVT = getPointerTy();
1927   bool is64bit = Subtarget.isPPC64();
1928   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1929   PICLevel::Level picLevel = M->getPICLevel();
1930
1931   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1932
1933   if (Model == TLSModel::LocalExec) {
1934     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1935                                                PPCII::MO_TPREL_HA);
1936     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1937                                                PPCII::MO_TPREL_LO);
1938     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1939                                      is64bit ? MVT::i64 : MVT::i32);
1940     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1941     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1942   }
1943
1944   if (Model == TLSModel::InitialExec) {
1945     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1946     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1947                                                 PPCII::MO_TLS);
1948     SDValue GOTPtr;
1949     if (is64bit) {
1950       setUsesTOCBasePtr(DAG);
1951       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1952       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1953                            PtrVT, GOTReg, TGA);
1954     } else
1955       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1956     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1957                                    PtrVT, TGA, GOTPtr);
1958     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1959   }
1960
1961   if (Model == TLSModel::GeneralDynamic) {
1962     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1963     SDValue GOTPtr;
1964     if (is64bit) {
1965       setUsesTOCBasePtr(DAG);
1966       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1967       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1968                                    GOTReg, TGA);
1969     } else {
1970       if (picLevel == PICLevel::Small)
1971         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1972       else
1973         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1974     }
1975     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1976                        GOTPtr, TGA, TGA);
1977   }
1978
1979   if (Model == TLSModel::LocalDynamic) {
1980     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1981     SDValue GOTPtr;
1982     if (is64bit) {
1983       setUsesTOCBasePtr(DAG);
1984       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1985       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1986                            GOTReg, TGA);
1987     } else {
1988       if (picLevel == PICLevel::Small)
1989         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1990       else
1991         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1992     }
1993     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
1994                                   PtrVT, GOTPtr, TGA, TGA);
1995     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
1996                                       PtrVT, TLSAddr, TGA);
1997     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1998   }
1999
2000   llvm_unreachable("Unknown TLS model!");
2001 }
2002
2003 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2004                                               SelectionDAG &DAG) const {
2005   EVT PtrVT = Op.getValueType();
2006   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2007   SDLoc DL(GSDN);
2008   const GlobalValue *GV = GSDN->getGlobal();
2009
2010   // 64-bit SVR4 ABI code is always position-independent.
2011   // The actual address of the GlobalValue is stored in the TOC.
2012   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2013     setUsesTOCBasePtr(DAG);
2014     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2015     return getTOCEntry(DAG, DL, true, GA);
2016   }
2017
2018   unsigned MOHiFlag, MOLoFlag;
2019   bool isPIC =
2020       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2021
2022   if (isPIC && Subtarget.isSVR4ABI()) {
2023     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2024                                             GSDN->getOffset(),
2025                                             PPCII::MO_PIC_FLAG);
2026     return getTOCEntry(DAG, DL, false, GA);
2027   }
2028
2029   SDValue GAHi =
2030     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2031   SDValue GALo =
2032     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2033
2034   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2035
2036   // If the global reference is actually to a non-lazy-pointer, we have to do an
2037   // extra load to get the address of the global.
2038   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2039     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2040                       false, false, false, 0);
2041   return Ptr;
2042 }
2043
2044 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2045   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2046   SDLoc dl(Op);
2047
2048   if (Op.getValueType() == MVT::v2i64) {
2049     // When the operands themselves are v2i64 values, we need to do something
2050     // special because VSX has no underlying comparison operations for these.
2051     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2052       // Equality can be handled by casting to the legal type for Altivec
2053       // comparisons, everything else needs to be expanded.
2054       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2055         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2056                  DAG.getSetCC(dl, MVT::v4i32,
2057                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2058                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2059                    CC));
2060       }
2061
2062       return SDValue();
2063     }
2064
2065     // We handle most of these in the usual way.
2066     return Op;
2067   }
2068
2069   // If we're comparing for equality to zero, expose the fact that this is
2070   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2071   // fold the new nodes.
2072   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2073     if (C->isNullValue() && CC == ISD::SETEQ) {
2074       EVT VT = Op.getOperand(0).getValueType();
2075       SDValue Zext = Op.getOperand(0);
2076       if (VT.bitsLT(MVT::i32)) {
2077         VT = MVT::i32;
2078         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2079       }
2080       unsigned Log2b = Log2_32(VT.getSizeInBits());
2081       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2082       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2083                                 DAG.getConstant(Log2b, MVT::i32));
2084       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2085     }
2086     // Leave comparisons against 0 and -1 alone for now, since they're usually
2087     // optimized.  FIXME: revisit this when we can custom lower all setcc
2088     // optimizations.
2089     if (C->isAllOnesValue() || C->isNullValue())
2090       return SDValue();
2091   }
2092
2093   // If we have an integer seteq/setne, turn it into a compare against zero
2094   // by xor'ing the rhs with the lhs, which is faster than setting a
2095   // condition register, reading it back out, and masking the correct bit.  The
2096   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2097   // the result to other bit-twiddling opportunities.
2098   EVT LHSVT = Op.getOperand(0).getValueType();
2099   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2100     EVT VT = Op.getValueType();
2101     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2102                                 Op.getOperand(1));
2103     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2104   }
2105   return SDValue();
2106 }
2107
2108 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2109                                       const PPCSubtarget &Subtarget) const {
2110   SDNode *Node = Op.getNode();
2111   EVT VT = Node->getValueType(0);
2112   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2113   SDValue InChain = Node->getOperand(0);
2114   SDValue VAListPtr = Node->getOperand(1);
2115   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2116   SDLoc dl(Node);
2117
2118   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2119
2120   // gpr_index
2121   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2122                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2123                                     false, false, false, 0);
2124   InChain = GprIndex.getValue(1);
2125
2126   if (VT == MVT::i64) {
2127     // Check if GprIndex is even
2128     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2129                                  DAG.getConstant(1, MVT::i32));
2130     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2131                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2132     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2133                                           DAG.getConstant(1, MVT::i32));
2134     // Align GprIndex to be even if it isn't
2135     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2136                            GprIndex);
2137   }
2138
2139   // fpr index is 1 byte after gpr
2140   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2141                                DAG.getConstant(1, MVT::i32));
2142
2143   // fpr
2144   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2145                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2146                                     false, false, false, 0);
2147   InChain = FprIndex.getValue(1);
2148
2149   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2150                                        DAG.getConstant(8, MVT::i32));
2151
2152   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2153                                         DAG.getConstant(4, MVT::i32));
2154
2155   // areas
2156   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2157                                      MachinePointerInfo(), false, false,
2158                                      false, 0);
2159   InChain = OverflowArea.getValue(1);
2160
2161   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2162                                     MachinePointerInfo(), false, false,
2163                                     false, 0);
2164   InChain = RegSaveArea.getValue(1);
2165
2166   // select overflow_area if index > 8
2167   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2168                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
2169
2170   // adjustment constant gpr_index * 4/8
2171   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2172                                     VT.isInteger() ? GprIndex : FprIndex,
2173                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
2174                                                     MVT::i32));
2175
2176   // OurReg = RegSaveArea + RegConstant
2177   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2178                                RegConstant);
2179
2180   // Floating types are 32 bytes into RegSaveArea
2181   if (VT.isFloatingPoint())
2182     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2183                          DAG.getConstant(32, MVT::i32));
2184
2185   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2186   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2187                                    VT.isInteger() ? GprIndex : FprIndex,
2188                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2189                                                    MVT::i32));
2190
2191   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2192                               VT.isInteger() ? VAListPtr : FprPtr,
2193                               MachinePointerInfo(SV),
2194                               MVT::i8, false, false, 0);
2195
2196   // determine if we should load from reg_save_area or overflow_area
2197   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2198
2199   // increase overflow_area by 4/8 if gpr/fpr > 8
2200   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2201                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2202                                           MVT::i32));
2203
2204   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2205                              OverflowAreaPlusN);
2206
2207   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2208                               OverflowAreaPtr,
2209                               MachinePointerInfo(),
2210                               MVT::i32, false, false, 0);
2211
2212   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2213                      false, false, false, 0);
2214 }
2215
2216 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2217                                        const PPCSubtarget &Subtarget) const {
2218   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2219
2220   // We have to copy the entire va_list struct:
2221   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2222   return DAG.getMemcpy(Op.getOperand(0), Op,
2223                        Op.getOperand(1), Op.getOperand(2),
2224                        DAG.getConstant(12, MVT::i32), 8, false, true, false,
2225                        MachinePointerInfo(), MachinePointerInfo());
2226 }
2227
2228 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2229                                                   SelectionDAG &DAG) const {
2230   return Op.getOperand(0);
2231 }
2232
2233 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2234                                                 SelectionDAG &DAG) const {
2235   SDValue Chain = Op.getOperand(0);
2236   SDValue Trmp = Op.getOperand(1); // trampoline
2237   SDValue FPtr = Op.getOperand(2); // nested function
2238   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2239   SDLoc dl(Op);
2240
2241   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2242   bool isPPC64 = (PtrVT == MVT::i64);
2243   Type *IntPtrTy =
2244     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2245                                                              *DAG.getContext());
2246
2247   TargetLowering::ArgListTy Args;
2248   TargetLowering::ArgListEntry Entry;
2249
2250   Entry.Ty = IntPtrTy;
2251   Entry.Node = Trmp; Args.push_back(Entry);
2252
2253   // TrampSize == (isPPC64 ? 48 : 40);
2254   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2255                                isPPC64 ? MVT::i64 : MVT::i32);
2256   Args.push_back(Entry);
2257
2258   Entry.Node = FPtr; Args.push_back(Entry);
2259   Entry.Node = Nest; Args.push_back(Entry);
2260
2261   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2262   TargetLowering::CallLoweringInfo CLI(DAG);
2263   CLI.setDebugLoc(dl).setChain(Chain)
2264     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2265                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2266                std::move(Args), 0);
2267
2268   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2269   return CallResult.second;
2270 }
2271
2272 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2273                                         const PPCSubtarget &Subtarget) const {
2274   MachineFunction &MF = DAG.getMachineFunction();
2275   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2276
2277   SDLoc dl(Op);
2278
2279   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2280     // vastart just stores the address of the VarArgsFrameIndex slot into the
2281     // memory location argument.
2282     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2283     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2284     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2285     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2286                         MachinePointerInfo(SV),
2287                         false, false, 0);
2288   }
2289
2290   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2291   // We suppose the given va_list is already allocated.
2292   //
2293   // typedef struct {
2294   //  char gpr;     /* index into the array of 8 GPRs
2295   //                 * stored in the register save area
2296   //                 * gpr=0 corresponds to r3,
2297   //                 * gpr=1 to r4, etc.
2298   //                 */
2299   //  char fpr;     /* index into the array of 8 FPRs
2300   //                 * stored in the register save area
2301   //                 * fpr=0 corresponds to f1,
2302   //                 * fpr=1 to f2, etc.
2303   //                 */
2304   //  char *overflow_arg_area;
2305   //                /* location on stack that holds
2306   //                 * the next overflow argument
2307   //                 */
2308   //  char *reg_save_area;
2309   //               /* where r3:r10 and f1:f8 (if saved)
2310   //                * are stored
2311   //                */
2312   // } va_list[1];
2313
2314
2315   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2316   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2317
2318
2319   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2320
2321   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2322                                             PtrVT);
2323   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2324                                  PtrVT);
2325
2326   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2327   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2328
2329   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2330   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2331
2332   uint64_t FPROffset = 1;
2333   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2334
2335   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2336
2337   // Store first byte : number of int regs
2338   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2339                                          Op.getOperand(1),
2340                                          MachinePointerInfo(SV),
2341                                          MVT::i8, false, false, 0);
2342   uint64_t nextOffset = FPROffset;
2343   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2344                                   ConstFPROffset);
2345
2346   // Store second byte : number of float regs
2347   SDValue secondStore =
2348     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2349                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2350                       false, false, 0);
2351   nextOffset += StackOffset;
2352   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2353
2354   // Store second word : arguments given on stack
2355   SDValue thirdStore =
2356     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2357                  MachinePointerInfo(SV, nextOffset),
2358                  false, false, 0);
2359   nextOffset += FrameOffset;
2360   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2361
2362   // Store third word : arguments given in registers
2363   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2364                       MachinePointerInfo(SV, nextOffset),
2365                       false, false, 0);
2366
2367 }
2368
2369 #include "PPCGenCallingConv.inc"
2370
2371 // Function whose sole purpose is to kill compiler warnings 
2372 // stemming from unused functions included from PPCGenCallingConv.inc.
2373 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2374   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2375 }
2376
2377 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2378                                       CCValAssign::LocInfo &LocInfo,
2379                                       ISD::ArgFlagsTy &ArgFlags,
2380                                       CCState &State) {
2381   return true;
2382 }
2383
2384 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2385                                              MVT &LocVT,
2386                                              CCValAssign::LocInfo &LocInfo,
2387                                              ISD::ArgFlagsTy &ArgFlags,
2388                                              CCState &State) {
2389   static const MCPhysReg ArgRegs[] = {
2390     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2391     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2392   };
2393   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2394
2395   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2396
2397   // Skip one register if the first unallocated register has an even register
2398   // number and there are still argument registers available which have not been
2399   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2400   // need to skip a register if RegNum is odd.
2401   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2402     State.AllocateReg(ArgRegs[RegNum]);
2403   }
2404
2405   // Always return false here, as this function only makes sure that the first
2406   // unallocated register has an odd register number and does not actually
2407   // allocate a register for the current argument.
2408   return false;
2409 }
2410
2411 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2412                                                MVT &LocVT,
2413                                                CCValAssign::LocInfo &LocInfo,
2414                                                ISD::ArgFlagsTy &ArgFlags,
2415                                                CCState &State) {
2416   static const MCPhysReg ArgRegs[] = {
2417     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2418     PPC::F8
2419   };
2420
2421   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2422
2423   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2424
2425   // If there is only one Floating-point register left we need to put both f64
2426   // values of a split ppc_fp128 value on the stack.
2427   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2428     State.AllocateReg(ArgRegs[RegNum]);
2429   }
2430
2431   // Always return false here, as this function only makes sure that the two f64
2432   // values a ppc_fp128 value is split into are both passed in registers or both
2433   // passed on the stack and does not actually allocate a register for the
2434   // current argument.
2435   return false;
2436 }
2437
2438 /// FPR - The set of FP registers that should be allocated for arguments,
2439 /// on Darwin.
2440 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2441                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2442                                 PPC::F11, PPC::F12, PPC::F13};
2443
2444 /// QFPR - The set of QPX registers that should be allocated for arguments.
2445 static const MCPhysReg QFPR[] = {
2446     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2447     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2448
2449 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2450 /// the stack.
2451 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2452                                        unsigned PtrByteSize) {
2453   unsigned ArgSize = ArgVT.getStoreSize();
2454   if (Flags.isByVal())
2455     ArgSize = Flags.getByValSize();
2456
2457   // Round up to multiples of the pointer size, except for array members,
2458   // which are always packed.
2459   if (!Flags.isInConsecutiveRegs())
2460     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2461
2462   return ArgSize;
2463 }
2464
2465 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2466 /// on the stack.
2467 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2468                                             ISD::ArgFlagsTy Flags,
2469                                             unsigned PtrByteSize) {
2470   unsigned Align = PtrByteSize;
2471
2472   // Altivec parameters are padded to a 16 byte boundary.
2473   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2474       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2475       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2476     Align = 16;
2477   // QPX vector types stored in double-precision are padded to a 32 byte
2478   // boundary.
2479   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2480     Align = 32;
2481
2482   // ByVal parameters are aligned as requested.
2483   if (Flags.isByVal()) {
2484     unsigned BVAlign = Flags.getByValAlign();
2485     if (BVAlign > PtrByteSize) {
2486       if (BVAlign % PtrByteSize != 0)
2487           llvm_unreachable(
2488             "ByVal alignment is not a multiple of the pointer size");
2489
2490       Align = BVAlign;
2491     }
2492   }
2493
2494   // Array members are always packed to their original alignment.
2495   if (Flags.isInConsecutiveRegs()) {
2496     // If the array member was split into multiple registers, the first
2497     // needs to be aligned to the size of the full type.  (Except for
2498     // ppcf128, which is only aligned as its f64 components.)
2499     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2500       Align = OrigVT.getStoreSize();
2501     else
2502       Align = ArgVT.getStoreSize();
2503   }
2504
2505   return Align;
2506 }
2507
2508 /// CalculateStackSlotUsed - Return whether this argument will use its
2509 /// stack slot (instead of being passed in registers).  ArgOffset,
2510 /// AvailableFPRs, and AvailableVRs must hold the current argument
2511 /// position, and will be updated to account for this argument.
2512 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2513                                    ISD::ArgFlagsTy Flags,
2514                                    unsigned PtrByteSize,
2515                                    unsigned LinkageSize,
2516                                    unsigned ParamAreaSize,
2517                                    unsigned &ArgOffset,
2518                                    unsigned &AvailableFPRs,
2519                                    unsigned &AvailableVRs, bool HasQPX) {
2520   bool UseMemory = false;
2521
2522   // Respect alignment of argument on the stack.
2523   unsigned Align =
2524     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2525   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2526   // If there's no space left in the argument save area, we must
2527   // use memory (this check also catches zero-sized arguments).
2528   if (ArgOffset >= LinkageSize + ParamAreaSize)
2529     UseMemory = true;
2530
2531   // Allocate argument on the stack.
2532   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2533   if (Flags.isInConsecutiveRegsLast())
2534     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2535   // If we overran the argument save area, we must use memory
2536   // (this check catches arguments passed partially in memory)
2537   if (ArgOffset > LinkageSize + ParamAreaSize)
2538     UseMemory = true;
2539
2540   // However, if the argument is actually passed in an FPR or a VR,
2541   // we don't use memory after all.
2542   if (!Flags.isByVal()) {
2543     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2544         // QPX registers overlap with the scalar FP registers.
2545         (HasQPX && (ArgVT == MVT::v4f32 ||
2546                     ArgVT == MVT::v4f64 ||
2547                     ArgVT == MVT::v4i1)))
2548       if (AvailableFPRs > 0) {
2549         --AvailableFPRs;
2550         return false;
2551       }
2552     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2553         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2554         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2555       if (AvailableVRs > 0) {
2556         --AvailableVRs;
2557         return false;
2558       }
2559   }
2560
2561   return UseMemory;
2562 }
2563
2564 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2565 /// ensure minimum alignment required for target.
2566 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2567                                      unsigned NumBytes) {
2568   unsigned TargetAlign = Lowering->getStackAlignment();
2569   unsigned AlignMask = TargetAlign - 1;
2570   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2571   return NumBytes;
2572 }
2573
2574 SDValue
2575 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2576                                         CallingConv::ID CallConv, bool isVarArg,
2577                                         const SmallVectorImpl<ISD::InputArg>
2578                                           &Ins,
2579                                         SDLoc dl, SelectionDAG &DAG,
2580                                         SmallVectorImpl<SDValue> &InVals)
2581                                           const {
2582   if (Subtarget.isSVR4ABI()) {
2583     if (Subtarget.isPPC64())
2584       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2585                                          dl, DAG, InVals);
2586     else
2587       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2588                                          dl, DAG, InVals);
2589   } else {
2590     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2591                                        dl, DAG, InVals);
2592   }
2593 }
2594
2595 SDValue
2596 PPCTargetLowering::LowerFormalArguments_32SVR4(
2597                                       SDValue Chain,
2598                                       CallingConv::ID CallConv, bool isVarArg,
2599                                       const SmallVectorImpl<ISD::InputArg>
2600                                         &Ins,
2601                                       SDLoc dl, SelectionDAG &DAG,
2602                                       SmallVectorImpl<SDValue> &InVals) const {
2603
2604   // 32-bit SVR4 ABI Stack Frame Layout:
2605   //              +-----------------------------------+
2606   //        +-->  |            Back chain             |
2607   //        |     +-----------------------------------+
2608   //        |     | Floating-point register save area |
2609   //        |     +-----------------------------------+
2610   //        |     |    General register save area     |
2611   //        |     +-----------------------------------+
2612   //        |     |          CR save word             |
2613   //        |     +-----------------------------------+
2614   //        |     |         VRSAVE save word          |
2615   //        |     +-----------------------------------+
2616   //        |     |         Alignment padding         |
2617   //        |     +-----------------------------------+
2618   //        |     |     Vector register save area     |
2619   //        |     +-----------------------------------+
2620   //        |     |       Local variable space        |
2621   //        |     +-----------------------------------+
2622   //        |     |        Parameter list area        |
2623   //        |     +-----------------------------------+
2624   //        |     |           LR save word            |
2625   //        |     +-----------------------------------+
2626   // SP-->  +---  |            Back chain             |
2627   //              +-----------------------------------+
2628   //
2629   // Specifications:
2630   //   System V Application Binary Interface PowerPC Processor Supplement
2631   //   AltiVec Technology Programming Interface Manual
2632
2633   MachineFunction &MF = DAG.getMachineFunction();
2634   MachineFrameInfo *MFI = MF.getFrameInfo();
2635   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2636
2637   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2638   // Potential tail calls could cause overwriting of argument stack slots.
2639   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2640                        (CallConv == CallingConv::Fast));
2641   unsigned PtrByteSize = 4;
2642
2643   // Assign locations to all of the incoming arguments.
2644   SmallVector<CCValAssign, 16> ArgLocs;
2645   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2646                  *DAG.getContext());
2647
2648   // Reserve space for the linkage area on the stack.
2649   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2650   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2651
2652   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2653
2654   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2655     CCValAssign &VA = ArgLocs[i];
2656
2657     // Arguments stored in registers.
2658     if (VA.isRegLoc()) {
2659       const TargetRegisterClass *RC;
2660       EVT ValVT = VA.getValVT();
2661
2662       switch (ValVT.getSimpleVT().SimpleTy) {
2663         default:
2664           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2665         case MVT::i1:
2666         case MVT::i32:
2667           RC = &PPC::GPRCRegClass;
2668           break;
2669         case MVT::f32:
2670           RC = &PPC::F4RCRegClass;
2671           break;
2672         case MVT::f64:
2673           if (Subtarget.hasVSX())
2674             RC = &PPC::VSFRCRegClass;
2675           else
2676             RC = &PPC::F8RCRegClass;
2677           break;
2678         case MVT::v16i8:
2679         case MVT::v8i16:
2680         case MVT::v4i32:
2681           RC = &PPC::VRRCRegClass;
2682           break;
2683         case MVT::v4f32:
2684           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2685           break;
2686         case MVT::v2f64:
2687         case MVT::v2i64:
2688           RC = &PPC::VSHRCRegClass;
2689           break;
2690         case MVT::v4f64:
2691           RC = &PPC::QFRCRegClass;
2692           break;
2693         case MVT::v4i1:
2694           RC = &PPC::QBRCRegClass;
2695           break;
2696       }
2697
2698       // Transform the arguments stored in physical registers into virtual ones.
2699       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2700       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2701                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2702
2703       if (ValVT == MVT::i1)
2704         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2705
2706       InVals.push_back(ArgValue);
2707     } else {
2708       // Argument stored in memory.
2709       assert(VA.isMemLoc());
2710
2711       unsigned ArgSize = VA.getLocVT().getStoreSize();
2712       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2713                                       isImmutable);
2714
2715       // Create load nodes to retrieve arguments from the stack.
2716       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2717       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2718                                    MachinePointerInfo(),
2719                                    false, false, false, 0));
2720     }
2721   }
2722
2723   // Assign locations to all of the incoming aggregate by value arguments.
2724   // Aggregates passed by value are stored in the local variable space of the
2725   // caller's stack frame, right above the parameter list area.
2726   SmallVector<CCValAssign, 16> ByValArgLocs;
2727   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2728                       ByValArgLocs, *DAG.getContext());
2729
2730   // Reserve stack space for the allocations in CCInfo.
2731   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2732
2733   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2734
2735   // Area that is at least reserved in the caller of this function.
2736   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2737   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2738
2739   // Set the size that is at least reserved in caller of this function.  Tail
2740   // call optimized function's reserved stack space needs to be aligned so that
2741   // taking the difference between two stack areas will result in an aligned
2742   // stack.
2743   MinReservedArea =
2744       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2745   FuncInfo->setMinReservedArea(MinReservedArea);
2746
2747   SmallVector<SDValue, 8> MemOps;
2748
2749   // If the function takes variable number of arguments, make a frame index for
2750   // the start of the first vararg value... for expansion of llvm.va_start.
2751   if (isVarArg) {
2752     static const MCPhysReg GPArgRegs[] = {
2753       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2754       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2755     };
2756     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2757
2758     static const MCPhysReg FPArgRegs[] = {
2759       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2760       PPC::F8
2761     };
2762     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2763     if (DisablePPCFloatInVariadic)
2764       NumFPArgRegs = 0;
2765
2766     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2767     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2768
2769     // Make room for NumGPArgRegs and NumFPArgRegs.
2770     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2771                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2772
2773     FuncInfo->setVarArgsStackOffset(
2774       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2775                              CCInfo.getNextStackOffset(), true));
2776
2777     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2778     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2779
2780     // The fixed integer arguments of a variadic function are stored to the
2781     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2782     // the result of va_next.
2783     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2784       // Get an existing live-in vreg, or add a new one.
2785       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2786       if (!VReg)
2787         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2788
2789       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2790       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2791                                    MachinePointerInfo(), false, false, 0);
2792       MemOps.push_back(Store);
2793       // Increment the address by four for the next argument to store
2794       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2795       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2796     }
2797
2798     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2799     // is set.
2800     // The double arguments are stored to the VarArgsFrameIndex
2801     // on the stack.
2802     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2803       // Get an existing live-in vreg, or add a new one.
2804       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2805       if (!VReg)
2806         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2807
2808       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2809       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2810                                    MachinePointerInfo(), false, false, 0);
2811       MemOps.push_back(Store);
2812       // Increment the address by eight for the next argument to store
2813       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2814                                          PtrVT);
2815       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2816     }
2817   }
2818
2819   if (!MemOps.empty())
2820     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2821
2822   return Chain;
2823 }
2824
2825 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2826 // value to MVT::i64 and then truncate to the correct register size.
2827 SDValue
2828 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2829                                      SelectionDAG &DAG, SDValue ArgVal,
2830                                      SDLoc dl) const {
2831   if (Flags.isSExt())
2832     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2833                          DAG.getValueType(ObjectVT));
2834   else if (Flags.isZExt())
2835     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2836                          DAG.getValueType(ObjectVT));
2837
2838   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2839 }
2840
2841 SDValue
2842 PPCTargetLowering::LowerFormalArguments_64SVR4(
2843                                       SDValue Chain,
2844                                       CallingConv::ID CallConv, bool isVarArg,
2845                                       const SmallVectorImpl<ISD::InputArg>
2846                                         &Ins,
2847                                       SDLoc dl, SelectionDAG &DAG,
2848                                       SmallVectorImpl<SDValue> &InVals) const {
2849   // TODO: add description of PPC stack frame format, or at least some docs.
2850   //
2851   bool isELFv2ABI = Subtarget.isELFv2ABI();
2852   bool isLittleEndian = Subtarget.isLittleEndian();
2853   MachineFunction &MF = DAG.getMachineFunction();
2854   MachineFrameInfo *MFI = MF.getFrameInfo();
2855   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2856
2857   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2858          "fastcc not supported on varargs functions");
2859
2860   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2861   // Potential tail calls could cause overwriting of argument stack slots.
2862   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2863                        (CallConv == CallingConv::Fast));
2864   unsigned PtrByteSize = 8;
2865   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2866
2867   static const MCPhysReg GPR[] = {
2868     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2869     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2870   };
2871   static const MCPhysReg VR[] = {
2872     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2873     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2874   };
2875   static const MCPhysReg VSRH[] = {
2876     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2877     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2878   };
2879
2880   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2881   const unsigned Num_FPR_Regs = 13;
2882   const unsigned Num_VR_Regs  = array_lengthof(VR);
2883   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2884
2885   // Do a first pass over the arguments to determine whether the ABI
2886   // guarantees that our caller has allocated the parameter save area
2887   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2888   // in the ELFv2 ABI, it is true if this is a vararg function or if
2889   // any parameter is located in a stack slot.
2890
2891   bool HasParameterArea = !isELFv2ABI || isVarArg;
2892   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2893   unsigned NumBytes = LinkageSize;
2894   unsigned AvailableFPRs = Num_FPR_Regs;
2895   unsigned AvailableVRs = Num_VR_Regs;
2896   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2897     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2898                                PtrByteSize, LinkageSize, ParamAreaSize,
2899                                NumBytes, AvailableFPRs, AvailableVRs,
2900                                Subtarget.hasQPX()))
2901       HasParameterArea = true;
2902
2903   // Add DAG nodes to load the arguments or copy them out of registers.  On
2904   // entry to a function on PPC, the arguments start after the linkage area,
2905   // although the first ones are often in registers.
2906
2907   unsigned ArgOffset = LinkageSize;
2908   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2909   unsigned &QFPR_idx = FPR_idx;
2910   SmallVector<SDValue, 8> MemOps;
2911   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2912   unsigned CurArgIdx = 0;
2913   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2914     SDValue ArgVal;
2915     bool needsLoad = false;
2916     EVT ObjectVT = Ins[ArgNo].VT;
2917     EVT OrigVT = Ins[ArgNo].ArgVT;
2918     unsigned ObjSize = ObjectVT.getStoreSize();
2919     unsigned ArgSize = ObjSize;
2920     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2921     if (Ins[ArgNo].isOrigArg()) {
2922       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2923       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2924     }
2925     // We re-align the argument offset for each argument, except when using the
2926     // fast calling convention, when we need to make sure we do that only when
2927     // we'll actually use a stack slot.
2928     unsigned CurArgOffset, Align;
2929     auto ComputeArgOffset = [&]() {
2930       /* Respect alignment of argument on the stack.  */
2931       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2932       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2933       CurArgOffset = ArgOffset;
2934     };
2935
2936     if (CallConv != CallingConv::Fast) {
2937       ComputeArgOffset();
2938
2939       /* Compute GPR index associated with argument offset.  */
2940       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2941       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2942     }
2943
2944     // FIXME the codegen can be much improved in some cases.
2945     // We do not have to keep everything in memory.
2946     if (Flags.isByVal()) {
2947       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2948
2949       if (CallConv == CallingConv::Fast)
2950         ComputeArgOffset();
2951
2952       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2953       ObjSize = Flags.getByValSize();
2954       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2955       // Empty aggregate parameters do not take up registers.  Examples:
2956       //   struct { } a;
2957       //   union  { } b;
2958       //   int c[0];
2959       // etc.  However, we have to provide a place-holder in InVals, so
2960       // pretend we have an 8-byte item at the current address for that
2961       // purpose.
2962       if (!ObjSize) {
2963         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2964         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2965         InVals.push_back(FIN);
2966         continue;
2967       }
2968
2969       // Create a stack object covering all stack doublewords occupied
2970       // by the argument.  If the argument is (fully or partially) on
2971       // the stack, or if the argument is fully in registers but the
2972       // caller has allocated the parameter save anyway, we can refer
2973       // directly to the caller's stack frame.  Otherwise, create a
2974       // local copy in our own frame.
2975       int FI;
2976       if (HasParameterArea ||
2977           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2978         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2979       else
2980         FI = MFI->CreateStackObject(ArgSize, Align, false);
2981       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2982
2983       // Handle aggregates smaller than 8 bytes.
2984       if (ObjSize < PtrByteSize) {
2985         // The value of the object is its address, which differs from the
2986         // address of the enclosing doubleword on big-endian systems.
2987         SDValue Arg = FIN;
2988         if (!isLittleEndian) {
2989           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2990           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2991         }
2992         InVals.push_back(Arg);
2993
2994         if (GPR_idx != Num_GPR_Regs) {
2995           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
2996           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2997           SDValue Store;
2998
2999           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3000             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3001                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3002             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3003                                       MachinePointerInfo(FuncArg),
3004                                       ObjType, false, false, 0);
3005           } else {
3006             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3007             // store the whole register as-is to the parameter save area
3008             // slot.
3009             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3010                                  MachinePointerInfo(FuncArg),
3011                                  false, false, 0);
3012           }
3013
3014           MemOps.push_back(Store);
3015         }
3016         // Whether we copied from a register or not, advance the offset
3017         // into the parameter save area by a full doubleword.
3018         ArgOffset += PtrByteSize;
3019         continue;
3020       }
3021
3022       // The value of the object is its address, which is the address of
3023       // its first stack doubleword.
3024       InVals.push_back(FIN);
3025
3026       // Store whatever pieces of the object are in registers to memory.
3027       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3028         if (GPR_idx == Num_GPR_Regs)
3029           break;
3030
3031         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3032         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3033         SDValue Addr = FIN;
3034         if (j) {
3035           SDValue Off = DAG.getConstant(j, PtrVT);
3036           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3037         }
3038         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3039                                      MachinePointerInfo(FuncArg, j),
3040                                      false, false, 0);
3041         MemOps.push_back(Store);
3042         ++GPR_idx;
3043       }
3044       ArgOffset += ArgSize;
3045       continue;
3046     }
3047
3048     switch (ObjectVT.getSimpleVT().SimpleTy) {
3049     default: llvm_unreachable("Unhandled argument type!");
3050     case MVT::i1:
3051     case MVT::i32:
3052     case MVT::i64:
3053       // These can be scalar arguments or elements of an integer array type
3054       // passed directly.  Clang may use those instead of "byval" aggregate
3055       // types to avoid forcing arguments to memory unnecessarily.
3056       if (GPR_idx != Num_GPR_Regs) {
3057         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3058         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3059
3060         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3061           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3062           // value to MVT::i64 and then truncate to the correct register size.
3063           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3064       } else {
3065         if (CallConv == CallingConv::Fast)
3066           ComputeArgOffset();
3067
3068         needsLoad = true;
3069         ArgSize = PtrByteSize;
3070       }
3071       if (CallConv != CallingConv::Fast || needsLoad)
3072         ArgOffset += 8;
3073       break;
3074
3075     case MVT::f32:
3076     case MVT::f64:
3077       // These can be scalar arguments or elements of a float array type
3078       // passed directly.  The latter are used to implement ELFv2 homogenous
3079       // float aggregates.
3080       if (FPR_idx != Num_FPR_Regs) {
3081         unsigned VReg;
3082
3083         if (ObjectVT == MVT::f32)
3084           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3085         else
3086           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3087                                                 ? &PPC::VSFRCRegClass
3088                                                 : &PPC::F8RCRegClass);
3089
3090         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3091         ++FPR_idx;
3092       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3093         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3094         // once we support fp <-> gpr moves.
3095
3096         // This can only ever happen in the presence of f32 array types,
3097         // since otherwise we never run out of FPRs before running out
3098         // of GPRs.
3099         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3100         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3101
3102         if (ObjectVT == MVT::f32) {
3103           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3104             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3105                                  DAG.getConstant(32, MVT::i32));
3106           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3107         }
3108
3109         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3110       } else {
3111         if (CallConv == CallingConv::Fast)
3112           ComputeArgOffset();
3113
3114         needsLoad = true;
3115       }
3116
3117       // When passing an array of floats, the array occupies consecutive
3118       // space in the argument area; only round up to the next doubleword
3119       // at the end of the array.  Otherwise, each float takes 8 bytes.
3120       if (CallConv != CallingConv::Fast || needsLoad) {
3121         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3122         ArgOffset += ArgSize;
3123         if (Flags.isInConsecutiveRegsLast())
3124           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3125       }
3126       break;
3127     case MVT::v4f32:
3128     case MVT::v4i32:
3129     case MVT::v8i16:
3130     case MVT::v16i8:
3131     case MVT::v2f64:
3132     case MVT::v2i64:
3133       if (!Subtarget.hasQPX()) {
3134       // These can be scalar arguments or elements of a vector array type
3135       // passed directly.  The latter are used to implement ELFv2 homogenous
3136       // vector aggregates.
3137       if (VR_idx != Num_VR_Regs) {
3138         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3139                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3140                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3141         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3142         ++VR_idx;
3143       } else {
3144         if (CallConv == CallingConv::Fast)
3145           ComputeArgOffset();
3146
3147         needsLoad = true;
3148       }
3149       if (CallConv != CallingConv::Fast || needsLoad)
3150         ArgOffset += 16;
3151       break;
3152       } // not QPX
3153
3154       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3155              "Invalid QPX parameter type");
3156       /* fall through */
3157
3158     case MVT::v4f64:
3159     case MVT::v4i1:
3160       // QPX vectors are treated like their scalar floating-point subregisters
3161       // (except that they're larger).
3162       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3163       if (QFPR_idx != Num_QFPR_Regs) {
3164         const TargetRegisterClass *RC;
3165         switch (ObjectVT.getSimpleVT().SimpleTy) {
3166         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3167         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3168         default:         RC = &PPC::QBRCRegClass; break;
3169         }
3170
3171         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3172         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3173         ++QFPR_idx;
3174       } else {
3175         if (CallConv == CallingConv::Fast)
3176           ComputeArgOffset();
3177         needsLoad = true;
3178       }
3179       if (CallConv != CallingConv::Fast || needsLoad)
3180         ArgOffset += Sz;
3181       break;
3182     }
3183
3184     // We need to load the argument to a virtual register if we determined
3185     // above that we ran out of physical registers of the appropriate type.
3186     if (needsLoad) {
3187       if (ObjSize < ArgSize && !isLittleEndian)
3188         CurArgOffset += ArgSize - ObjSize;
3189       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3190       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3191       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3192                            false, false, false, 0);
3193     }
3194
3195     InVals.push_back(ArgVal);
3196   }
3197
3198   // Area that is at least reserved in the caller of this function.
3199   unsigned MinReservedArea;
3200   if (HasParameterArea)
3201     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3202   else
3203     MinReservedArea = LinkageSize;
3204
3205   // Set the size that is at least reserved in caller of this function.  Tail
3206   // call optimized functions' reserved stack space needs to be aligned so that
3207   // taking the difference between two stack areas will result in an aligned
3208   // stack.
3209   MinReservedArea =
3210       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3211   FuncInfo->setMinReservedArea(MinReservedArea);
3212
3213   // If the function takes variable number of arguments, make a frame index for
3214   // the start of the first vararg value... for expansion of llvm.va_start.
3215   if (isVarArg) {
3216     int Depth = ArgOffset;
3217
3218     FuncInfo->setVarArgsFrameIndex(
3219       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3220     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3221
3222     // If this function is vararg, store any remaining integer argument regs
3223     // to their spots on the stack so that they may be loaded by deferencing the
3224     // result of va_next.
3225     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3226          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3227       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3228       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3229       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3230                                    MachinePointerInfo(), false, false, 0);
3231       MemOps.push_back(Store);
3232       // Increment the address by four for the next argument to store
3233       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3234       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3235     }
3236   }
3237
3238   if (!MemOps.empty())
3239     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3240
3241   return Chain;
3242 }
3243
3244 SDValue
3245 PPCTargetLowering::LowerFormalArguments_Darwin(
3246                                       SDValue Chain,
3247                                       CallingConv::ID CallConv, bool isVarArg,
3248                                       const SmallVectorImpl<ISD::InputArg>
3249                                         &Ins,
3250                                       SDLoc dl, SelectionDAG &DAG,
3251                                       SmallVectorImpl<SDValue> &InVals) const {
3252   // TODO: add description of PPC stack frame format, or at least some docs.
3253   //
3254   MachineFunction &MF = DAG.getMachineFunction();
3255   MachineFrameInfo *MFI = MF.getFrameInfo();
3256   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3257
3258   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3259   bool isPPC64 = PtrVT == MVT::i64;
3260   // Potential tail calls could cause overwriting of argument stack slots.
3261   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3262                        (CallConv == CallingConv::Fast));
3263   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3264   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3265   unsigned ArgOffset = LinkageSize;
3266   // Area that is at least reserved in caller of this function.
3267   unsigned MinReservedArea = ArgOffset;
3268
3269   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3270     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3271     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3272   };
3273   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3274     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3275     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3276   };
3277   static const MCPhysReg VR[] = {
3278     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3279     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3280   };
3281
3282   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3283   const unsigned Num_FPR_Regs = 13;
3284   const unsigned Num_VR_Regs  = array_lengthof( VR);
3285
3286   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3287
3288   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3289
3290   // In 32-bit non-varargs functions, the stack space for vectors is after the
3291   // stack space for non-vectors.  We do not use this space unless we have
3292   // too many vectors to fit in registers, something that only occurs in
3293   // constructed examples:), but we have to walk the arglist to figure
3294   // that out...for the pathological case, compute VecArgOffset as the
3295   // start of the vector parameter area.  Computing VecArgOffset is the
3296   // entire point of the following loop.
3297   unsigned VecArgOffset = ArgOffset;
3298   if (!isVarArg && !isPPC64) {
3299     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3300          ++ArgNo) {
3301       EVT ObjectVT = Ins[ArgNo].VT;
3302       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3303
3304       if (Flags.isByVal()) {
3305         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3306         unsigned ObjSize = Flags.getByValSize();
3307         unsigned ArgSize =
3308                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3309         VecArgOffset += ArgSize;
3310         continue;
3311       }
3312
3313       switch(ObjectVT.getSimpleVT().SimpleTy) {
3314       default: llvm_unreachable("Unhandled argument type!");
3315       case MVT::i1:
3316       case MVT::i32:
3317       case MVT::f32:
3318         VecArgOffset += 4;
3319         break;
3320       case MVT::i64:  // PPC64
3321       case MVT::f64:
3322         // FIXME: We are guaranteed to be !isPPC64 at this point.
3323         // Does MVT::i64 apply?
3324         VecArgOffset += 8;
3325         break;
3326       case MVT::v4f32:
3327       case MVT::v4i32:
3328       case MVT::v8i16:
3329       case MVT::v16i8:
3330         // Nothing to do, we're only looking at Nonvector args here.
3331         break;
3332       }
3333     }
3334   }
3335   // We've found where the vector parameter area in memory is.  Skip the
3336   // first 12 parameters; these don't use that memory.
3337   VecArgOffset = ((VecArgOffset+15)/16)*16;
3338   VecArgOffset += 12*16;
3339
3340   // Add DAG nodes to load the arguments or copy them out of registers.  On
3341   // entry to a function on PPC, the arguments start after the linkage area,
3342   // although the first ones are often in registers.
3343
3344   SmallVector<SDValue, 8> MemOps;
3345   unsigned nAltivecParamsAtEnd = 0;
3346   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3347   unsigned CurArgIdx = 0;
3348   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3349     SDValue ArgVal;
3350     bool needsLoad = false;
3351     EVT ObjectVT = Ins[ArgNo].VT;
3352     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3353     unsigned ArgSize = ObjSize;
3354     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3355     if (Ins[ArgNo].isOrigArg()) {
3356       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3357       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3358     }
3359     unsigned CurArgOffset = ArgOffset;
3360
3361     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3362     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3363         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3364       if (isVarArg || isPPC64) {
3365         MinReservedArea = ((MinReservedArea+15)/16)*16;
3366         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3367                                                   Flags,
3368                                                   PtrByteSize);
3369       } else  nAltivecParamsAtEnd++;
3370     } else
3371       // Calculate min reserved area.
3372       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3373                                                 Flags,
3374                                                 PtrByteSize);
3375
3376     // FIXME the codegen can be much improved in some cases.
3377     // We do not have to keep everything in memory.
3378     if (Flags.isByVal()) {
3379       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3380
3381       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3382       ObjSize = Flags.getByValSize();
3383       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3384       // Objects of size 1 and 2 are right justified, everything else is
3385       // left justified.  This means the memory address is adjusted forwards.
3386       if (ObjSize==1 || ObjSize==2) {
3387         CurArgOffset = CurArgOffset + (4 - ObjSize);
3388       }
3389       // The value of the object is its address.
3390       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3391       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3392       InVals.push_back(FIN);
3393       if (ObjSize==1 || ObjSize==2) {
3394         if (GPR_idx != Num_GPR_Regs) {
3395           unsigned VReg;
3396           if (isPPC64)
3397             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3398           else
3399             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3400           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3401           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3402           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3403                                             MachinePointerInfo(FuncArg),
3404                                             ObjType, false, false, 0);
3405           MemOps.push_back(Store);
3406           ++GPR_idx;
3407         }
3408
3409         ArgOffset += PtrByteSize;
3410
3411         continue;
3412       }
3413       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3414         // Store whatever pieces of the object are in registers
3415         // to memory.  ArgOffset will be the address of the beginning
3416         // of the object.
3417         if (GPR_idx != Num_GPR_Regs) {
3418           unsigned VReg;
3419           if (isPPC64)
3420             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3421           else
3422             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3423           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3424           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3425           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3426           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3427                                        MachinePointerInfo(FuncArg, j),
3428                                        false, false, 0);
3429           MemOps.push_back(Store);
3430           ++GPR_idx;
3431           ArgOffset += PtrByteSize;
3432         } else {
3433           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3434           break;
3435         }
3436       }
3437       continue;
3438     }
3439
3440     switch (ObjectVT.getSimpleVT().SimpleTy) {
3441     default: llvm_unreachable("Unhandled argument type!");
3442     case MVT::i1:
3443     case MVT::i32:
3444       if (!isPPC64) {
3445         if (GPR_idx != Num_GPR_Regs) {
3446           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3447           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3448
3449           if (ObjectVT == MVT::i1)
3450             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3451
3452           ++GPR_idx;
3453         } else {
3454           needsLoad = true;
3455           ArgSize = PtrByteSize;
3456         }
3457         // All int arguments reserve stack space in the Darwin ABI.
3458         ArgOffset += PtrByteSize;
3459         break;
3460       }
3461       // FALLTHROUGH
3462     case MVT::i64:  // PPC64
3463       if (GPR_idx != Num_GPR_Regs) {
3464         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3465         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3466
3467         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3468           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3469           // value to MVT::i64 and then truncate to the correct register size.
3470           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
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 += 8;
3479       break;
3480
3481     case MVT::f32:
3482     case MVT::f64:
3483       // Every 4 bytes of argument space consumes one of the GPRs available for
3484       // argument passing.
3485       if (GPR_idx != Num_GPR_Regs) {
3486         ++GPR_idx;
3487         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3488           ++GPR_idx;
3489       }
3490       if (FPR_idx != Num_FPR_Regs) {
3491         unsigned VReg;
3492
3493         if (ObjectVT == MVT::f32)
3494           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3495         else
3496           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3497
3498         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3499         ++FPR_idx;
3500       } else {
3501         needsLoad = true;
3502       }
3503
3504       // All FP arguments reserve stack space in the Darwin ABI.
3505       ArgOffset += isPPC64 ? 8 : ObjSize;
3506       break;
3507     case MVT::v4f32:
3508     case MVT::v4i32:
3509     case MVT::v8i16:
3510     case MVT::v16i8:
3511       // Note that vector arguments in registers don't reserve stack space,
3512       // except in varargs functions.
3513       if (VR_idx != Num_VR_Regs) {
3514         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3515         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3516         if (isVarArg) {
3517           while ((ArgOffset % 16) != 0) {
3518             ArgOffset += PtrByteSize;
3519             if (GPR_idx != Num_GPR_Regs)
3520               GPR_idx++;
3521           }
3522           ArgOffset += 16;
3523           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3524         }
3525         ++VR_idx;
3526       } else {
3527         if (!isVarArg && !isPPC64) {
3528           // Vectors go after all the nonvectors.
3529           CurArgOffset = VecArgOffset;
3530           VecArgOffset += 16;
3531         } else {
3532           // Vectors are aligned.
3533           ArgOffset = ((ArgOffset+15)/16)*16;
3534           CurArgOffset = ArgOffset;
3535           ArgOffset += 16;
3536         }
3537         needsLoad = true;
3538       }
3539       break;
3540     }
3541
3542     // We need to load the argument to a virtual register if we determined above
3543     // that we ran out of physical registers of the appropriate type.
3544     if (needsLoad) {
3545       int FI = MFI->CreateFixedObject(ObjSize,
3546                                       CurArgOffset + (ArgSize - ObjSize),
3547                                       isImmutable);
3548       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3549       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3550                            false, false, false, 0);
3551     }
3552
3553     InVals.push_back(ArgVal);
3554   }
3555
3556   // Allow for Altivec parameters at the end, if needed.
3557   if (nAltivecParamsAtEnd) {
3558     MinReservedArea = ((MinReservedArea+15)/16)*16;
3559     MinReservedArea += 16*nAltivecParamsAtEnd;
3560   }
3561
3562   // Area that is at least reserved in the caller of this function.
3563   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3564
3565   // Set the size that is at least reserved in caller of this function.  Tail
3566   // call optimized functions' reserved stack space needs to be aligned so that
3567   // taking the difference between two stack areas will result in an aligned
3568   // stack.
3569   MinReservedArea =
3570       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3571   FuncInfo->setMinReservedArea(MinReservedArea);
3572
3573   // If the function takes variable number of arguments, make a frame index for
3574   // the start of the first vararg value... for expansion of llvm.va_start.
3575   if (isVarArg) {
3576     int Depth = ArgOffset;
3577
3578     FuncInfo->setVarArgsFrameIndex(
3579       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3580                              Depth, true));
3581     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3582
3583     // If this function is vararg, store any remaining integer argument regs
3584     // to their spots on the stack so that they may be loaded by deferencing the
3585     // result of va_next.
3586     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3587       unsigned VReg;
3588
3589       if (isPPC64)
3590         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3591       else
3592         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3593
3594       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3595       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3596                                    MachinePointerInfo(), false, false, 0);
3597       MemOps.push_back(Store);
3598       // Increment the address by four for the next argument to store
3599       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3600       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3601     }
3602   }
3603
3604   if (!MemOps.empty())
3605     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3606
3607   return Chain;
3608 }
3609
3610 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3611 /// adjusted to accommodate the arguments for the tailcall.
3612 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3613                                    unsigned ParamSize) {
3614
3615   if (!isTailCall) return 0;
3616
3617   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3618   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3619   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3620   // Remember only if the new adjustement is bigger.
3621   if (SPDiff < FI->getTailCallSPDelta())
3622     FI->setTailCallSPDelta(SPDiff);
3623
3624   return SPDiff;
3625 }
3626
3627 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3628 /// for tail call optimization. Targets which want to do tail call
3629 /// optimization should implement this function.
3630 bool
3631 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3632                                                      CallingConv::ID CalleeCC,
3633                                                      bool isVarArg,
3634                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3635                                                      SelectionDAG& DAG) const {
3636   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3637     return false;
3638
3639   // Variable argument functions are not supported.
3640   if (isVarArg)
3641     return false;
3642
3643   MachineFunction &MF = DAG.getMachineFunction();
3644   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3645   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3646     // Functions containing by val parameters are not supported.
3647     for (unsigned i = 0; i != Ins.size(); i++) {
3648        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3649        if (Flags.isByVal()) return false;
3650     }
3651
3652     // Non-PIC/GOT tail calls are supported.
3653     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3654       return true;
3655
3656     // At the moment we can only do local tail calls (in same module, hidden
3657     // or protected) if we are generating PIC.
3658     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3659       return G->getGlobal()->hasHiddenVisibility()
3660           || G->getGlobal()->hasProtectedVisibility();
3661   }
3662
3663   return false;
3664 }
3665
3666 /// isCallCompatibleAddress - Return the immediate to use if the specified
3667 /// 32-bit value is representable in the immediate field of a BxA instruction.
3668 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3669   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3670   if (!C) return nullptr;
3671
3672   int Addr = C->getZExtValue();
3673   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3674       SignExtend32<26>(Addr) != Addr)
3675     return nullptr;  // Top 6 bits have to be sext of immediate.
3676
3677   return DAG.getConstant((int)C->getZExtValue() >> 2,
3678                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3679 }
3680
3681 namespace {
3682
3683 struct TailCallArgumentInfo {
3684   SDValue Arg;
3685   SDValue FrameIdxOp;
3686   int       FrameIdx;
3687
3688   TailCallArgumentInfo() : FrameIdx(0) {}
3689 };
3690
3691 }
3692
3693 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3694 static void
3695 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3696                                            SDValue Chain,
3697                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3698                    SmallVectorImpl<SDValue> &MemOpChains,
3699                    SDLoc dl) {
3700   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3701     SDValue Arg = TailCallArgs[i].Arg;
3702     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3703     int FI = TailCallArgs[i].FrameIdx;
3704     // Store relative to framepointer.
3705     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3706                                        MachinePointerInfo::getFixedStack(FI),
3707                                        false, false, 0));
3708   }
3709 }
3710
3711 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3712 /// the appropriate stack slot for the tail call optimized function call.
3713 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3714                                                MachineFunction &MF,
3715                                                SDValue Chain,
3716                                                SDValue OldRetAddr,
3717                                                SDValue OldFP,
3718                                                int SPDiff,
3719                                                bool isPPC64,
3720                                                bool isDarwinABI,
3721                                                SDLoc dl) {
3722   if (SPDiff) {
3723     // Calculate the new stack slot for the return address.
3724     int SlotSize = isPPC64 ? 8 : 4;
3725     const PPCFrameLowering *FL =
3726         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3727     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3728     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3729                                                           NewRetAddrLoc, true);
3730     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3731     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3732     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3733                          MachinePointerInfo::getFixedStack(NewRetAddr),
3734                          false, false, 0);
3735
3736     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3737     // slot as the FP is never overwritten.
3738     if (isDarwinABI) {
3739       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3740       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3741                                                           true);
3742       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3743       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3744                            MachinePointerInfo::getFixedStack(NewFPIdx),
3745                            false, false, 0);
3746     }
3747   }
3748   return Chain;
3749 }
3750
3751 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3752 /// the position of the argument.
3753 static void
3754 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3755                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3756                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3757   int Offset = ArgOffset + SPDiff;
3758   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3759   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3760   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3761   SDValue FIN = DAG.getFrameIndex(FI, VT);
3762   TailCallArgumentInfo Info;
3763   Info.Arg = Arg;
3764   Info.FrameIdxOp = FIN;
3765   Info.FrameIdx = FI;
3766   TailCallArguments.push_back(Info);
3767 }
3768
3769 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3770 /// stack slot. Returns the chain as result and the loaded frame pointers in
3771 /// LROpOut/FPOpout. Used when tail calling.
3772 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3773                                                         int SPDiff,
3774                                                         SDValue Chain,
3775                                                         SDValue &LROpOut,
3776                                                         SDValue &FPOpOut,
3777                                                         bool isDarwinABI,
3778                                                         SDLoc dl) const {
3779   if (SPDiff) {
3780     // Load the LR and FP stack slot for later adjusting.
3781     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3782     LROpOut = getReturnAddrFrameIndex(DAG);
3783     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3784                           false, false, false, 0);
3785     Chain = SDValue(LROpOut.getNode(), 1);
3786
3787     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3788     // slot as the FP is never overwritten.
3789     if (isDarwinABI) {
3790       FPOpOut = getFramePointerFrameIndex(DAG);
3791       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3792                             false, false, false, 0);
3793       Chain = SDValue(FPOpOut.getNode(), 1);
3794     }
3795   }
3796   return Chain;
3797 }
3798
3799 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3800 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3801 /// specified by the specific parameter attribute. The copy will be passed as
3802 /// a byval function parameter.
3803 /// Sometimes what we are copying is the end of a larger object, the part that
3804 /// does not fit in registers.
3805 static SDValue
3806 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3807                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3808                           SDLoc dl) {
3809   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3810   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3811                        false, false, false, MachinePointerInfo(),
3812                        MachinePointerInfo());
3813 }
3814
3815 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3816 /// tail calls.
3817 static void
3818 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3819                  SDValue Arg, SDValue PtrOff, int SPDiff,
3820                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3821                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3822                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3823                  SDLoc dl) {
3824   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3825   if (!isTailCall) {
3826     if (isVector) {
3827       SDValue StackPtr;
3828       if (isPPC64)
3829         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3830       else
3831         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3832       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3833                            DAG.getConstant(ArgOffset, PtrVT));
3834     }
3835     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3836                                        MachinePointerInfo(), false, false, 0));
3837   // Calculate and remember argument location.
3838   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3839                                   TailCallArguments);
3840 }
3841
3842 static
3843 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3844                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3845                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3846                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3847   MachineFunction &MF = DAG.getMachineFunction();
3848
3849   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3850   // might overwrite each other in case of tail call optimization.
3851   SmallVector<SDValue, 8> MemOpChains2;
3852   // Do not flag preceding copytoreg stuff together with the following stuff.
3853   InFlag = SDValue();
3854   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3855                                     MemOpChains2, dl);
3856   if (!MemOpChains2.empty())
3857     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3858
3859   // Store the return address to the appropriate stack slot.
3860   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3861                                         isPPC64, isDarwinABI, dl);
3862
3863   // Emit callseq_end just before tailcall node.
3864   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3865                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3866   InFlag = Chain.getValue(1);
3867 }
3868
3869 // Is this global address that of a function that can be called by name? (as
3870 // opposed to something that must hold a descriptor for an indirect call).
3871 static bool isFunctionGlobalAddress(SDValue Callee) {
3872   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3873     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3874         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3875       return false;
3876
3877     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3878   }
3879
3880   return false;
3881 }
3882
3883 static
3884 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3885                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3886                      bool isTailCall, bool IsPatchPoint,
3887                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3888                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3889                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3890
3891   bool isPPC64 = Subtarget.isPPC64();
3892   bool isSVR4ABI = Subtarget.isSVR4ABI();
3893   bool isELFv2ABI = Subtarget.isELFv2ABI();
3894
3895   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3896   NodeTys.push_back(MVT::Other);   // Returns a chain
3897   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3898
3899   unsigned CallOpc = PPCISD::CALL;
3900
3901   bool needIndirectCall = true;
3902   if (!isSVR4ABI || !isPPC64)
3903     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3904       // If this is an absolute destination address, use the munged value.
3905       Callee = SDValue(Dest, 0);
3906       needIndirectCall = false;
3907     }
3908
3909   if (isFunctionGlobalAddress(Callee)) {
3910     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3911     // A call to a TLS address is actually an indirect call to a
3912     // thread-specific pointer.
3913     unsigned OpFlags = 0;
3914     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3915          (Subtarget.getTargetTriple().isMacOSX() &&
3916           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3917          (G->getGlobal()->isDeclaration() ||
3918           G->getGlobal()->isWeakForLinker())) ||
3919         (Subtarget.isTargetELF() && !isPPC64 &&
3920          !G->getGlobal()->hasLocalLinkage() &&
3921          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3922       // PC-relative references to external symbols should go through $stub,
3923       // unless we're building with the leopard linker or later, which
3924       // automatically synthesizes these stubs.
3925       OpFlags = PPCII::MO_PLT_OR_STUB;
3926     }
3927
3928     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3929     // every direct call is) turn it into a TargetGlobalAddress /
3930     // TargetExternalSymbol node so that legalize doesn't hack it.
3931     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3932                                         Callee.getValueType(), 0, OpFlags);
3933     needIndirectCall = false;
3934   }
3935
3936   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3937     unsigned char OpFlags = 0;
3938
3939     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3940          (Subtarget.getTargetTriple().isMacOSX() &&
3941           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3942         (Subtarget.isTargetELF() && !isPPC64 &&
3943          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3944       // PC-relative references to external symbols should go through $stub,
3945       // unless we're building with the leopard linker or later, which
3946       // automatically synthesizes these stubs.
3947       OpFlags = PPCII::MO_PLT_OR_STUB;
3948     }
3949
3950     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3951                                          OpFlags);
3952     needIndirectCall = false;
3953   }
3954
3955   if (IsPatchPoint) {
3956     // We'll form an invalid direct call when lowering a patchpoint; the full
3957     // sequence for an indirect call is complicated, and many of the
3958     // instructions introduced might have side effects (and, thus, can't be
3959     // removed later). The call itself will be removed as soon as the
3960     // argument/return lowering is complete, so the fact that it has the wrong
3961     // kind of operands should not really matter.
3962     needIndirectCall = false;
3963   }
3964
3965   if (needIndirectCall) {
3966     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3967     // to do the call, we can't use PPCISD::CALL.
3968     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3969
3970     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3971       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3972       // entry point, but to the function descriptor (the function entry point
3973       // address is part of the function descriptor though).
3974       // The function descriptor is a three doubleword structure with the
3975       // following fields: function entry point, TOC base address and
3976       // environment pointer.
3977       // Thus for a call through a function pointer, the following actions need
3978       // to be performed:
3979       //   1. Save the TOC of the caller in the TOC save area of its stack
3980       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3981       //   2. Load the address of the function entry point from the function
3982       //      descriptor.
3983       //   3. Load the TOC of the callee from the function descriptor into r2.
3984       //   4. Load the environment pointer from the function descriptor into
3985       //      r11.
3986       //   5. Branch to the function entry point address.
3987       //   6. On return of the callee, the TOC of the caller needs to be
3988       //      restored (this is done in FinishCall()).
3989       //
3990       // The loads are scheduled at the beginning of the call sequence, and the
3991       // register copies are flagged together to ensure that no other
3992       // operations can be scheduled in between. E.g. without flagging the
3993       // copies together, a TOC access in the caller could be scheduled between
3994       // the assignment of the callee TOC and the branch to the callee, which
3995       // results in the TOC access going through the TOC of the callee instead
3996       // of going through the TOC of the caller, which leads to incorrect code.
3997
3998       // Load the address of the function entry point from the function
3999       // descriptor.
4000       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4001       if (LDChain.getValueType() == MVT::Glue)
4002         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4003
4004       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4005
4006       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4007       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4008                                         false, false, LoadsInv, 8);
4009
4010       // Load environment pointer into r11.
4011       SDValue PtrOff = DAG.getIntPtrConstant(16);
4012       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4013       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4014                                        MPI.getWithOffset(16), false, false,
4015                                        LoadsInv, 8);
4016
4017       SDValue TOCOff = DAG.getIntPtrConstant(8);
4018       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4019       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4020                                    MPI.getWithOffset(8), false, false,
4021                                    LoadsInv, 8);
4022
4023       setUsesTOCBasePtr(DAG);
4024       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4025                                         InFlag);
4026       Chain = TOCVal.getValue(0);
4027       InFlag = TOCVal.getValue(1);
4028
4029       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4030                                         InFlag);
4031
4032       Chain = EnvVal.getValue(0);
4033       InFlag = EnvVal.getValue(1);
4034
4035       MTCTROps[0] = Chain;
4036       MTCTROps[1] = LoadFuncPtr;
4037       MTCTROps[2] = InFlag;
4038     }
4039
4040     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4041                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4042     InFlag = Chain.getValue(1);
4043
4044     NodeTys.clear();
4045     NodeTys.push_back(MVT::Other);
4046     NodeTys.push_back(MVT::Glue);
4047     Ops.push_back(Chain);
4048     CallOpc = PPCISD::BCTRL;
4049     Callee.setNode(nullptr);
4050     // Add use of X11 (holding environment pointer)
4051     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4052       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4053     // Add CTR register as callee so a bctr can be emitted later.
4054     if (isTailCall)
4055       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4056   }
4057
4058   // If this is a direct call, pass the chain and the callee.
4059   if (Callee.getNode()) {
4060     Ops.push_back(Chain);
4061     Ops.push_back(Callee);
4062   }
4063   // If this is a tail call add stack pointer delta.
4064   if (isTailCall)
4065     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4066
4067   // Add argument registers to the end of the list so that they are known live
4068   // into the call.
4069   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4070     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4071                                   RegsToPass[i].second.getValueType()));
4072
4073   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4074   // into the call.
4075   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4076     setUsesTOCBasePtr(DAG);
4077     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4078   }
4079
4080   return CallOpc;
4081 }
4082
4083 static
4084 bool isLocalCall(const SDValue &Callee)
4085 {
4086   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4087     return !G->getGlobal()->isDeclaration() &&
4088            !G->getGlobal()->isWeakForLinker();
4089   return false;
4090 }
4091
4092 SDValue
4093 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4094                                    CallingConv::ID CallConv, bool isVarArg,
4095                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4096                                    SDLoc dl, SelectionDAG &DAG,
4097                                    SmallVectorImpl<SDValue> &InVals) const {
4098
4099   SmallVector<CCValAssign, 16> RVLocs;
4100   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4101                     *DAG.getContext());
4102   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4103
4104   // Copy all of the result registers out of their specified physreg.
4105   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4106     CCValAssign &VA = RVLocs[i];
4107     assert(VA.isRegLoc() && "Can only return in registers!");
4108
4109     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4110                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4111     Chain = Val.getValue(1);
4112     InFlag = Val.getValue(2);
4113
4114     switch (VA.getLocInfo()) {
4115     default: llvm_unreachable("Unknown loc info!");
4116     case CCValAssign::Full: break;
4117     case CCValAssign::AExt:
4118       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4119       break;
4120     case CCValAssign::ZExt:
4121       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4122                         DAG.getValueType(VA.getValVT()));
4123       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4124       break;
4125     case CCValAssign::SExt:
4126       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4127                         DAG.getValueType(VA.getValVT()));
4128       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4129       break;
4130     }
4131
4132     InVals.push_back(Val);
4133   }
4134
4135   return Chain;
4136 }
4137
4138 SDValue
4139 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4140                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4141                               SelectionDAG &DAG,
4142                               SmallVector<std::pair<unsigned, SDValue>, 8>
4143                                 &RegsToPass,
4144                               SDValue InFlag, SDValue Chain,
4145                               SDValue CallSeqStart, SDValue &Callee,
4146                               int SPDiff, unsigned NumBytes,
4147                               const SmallVectorImpl<ISD::InputArg> &Ins,
4148                               SmallVectorImpl<SDValue> &InVals,
4149                               ImmutableCallSite *CS) const {
4150
4151   std::vector<EVT> NodeTys;
4152   SmallVector<SDValue, 8> Ops;
4153   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4154                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4155                                  Ops, NodeTys, CS, Subtarget);
4156
4157   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4158   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4159     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4160
4161   // When performing tail call optimization the callee pops its arguments off
4162   // the stack. Account for this here so these bytes can be pushed back on in
4163   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4164   int BytesCalleePops =
4165     (CallConv == CallingConv::Fast &&
4166      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4167
4168   // Add a register mask operand representing the call-preserved registers.
4169   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4170   const uint32_t *Mask =
4171       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4172   assert(Mask && "Missing call preserved mask for calling convention");
4173   Ops.push_back(DAG.getRegisterMask(Mask));
4174
4175   if (InFlag.getNode())
4176     Ops.push_back(InFlag);
4177
4178   // Emit tail call.
4179   if (isTailCall) {
4180     assert(((Callee.getOpcode() == ISD::Register &&
4181              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4182             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4183             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4184             isa<ConstantSDNode>(Callee)) &&
4185     "Expecting an global address, external symbol, absolute value or register");
4186
4187     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4188   }
4189
4190   // Add a NOP immediately after the branch instruction when using the 64-bit
4191   // SVR4 ABI. At link time, if caller and callee are in a different module and
4192   // thus have a different TOC, the call will be replaced with a call to a stub
4193   // function which saves the current TOC, loads the TOC of the callee and
4194   // branches to the callee. The NOP will be replaced with a load instruction
4195   // which restores the TOC of the caller from the TOC save slot of the current
4196   // stack frame. If caller and callee belong to the same module (and have the
4197   // same TOC), the NOP will remain unchanged.
4198
4199   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4200       !IsPatchPoint) {
4201     if (CallOpc == PPCISD::BCTRL) {
4202       // This is a call through a function pointer.
4203       // Restore the caller TOC from the save area into R2.
4204       // See PrepareCall() for more information about calls through function
4205       // pointers in the 64-bit SVR4 ABI.
4206       // We are using a target-specific load with r2 hard coded, because the
4207       // result of a target-independent load would never go directly into r2,
4208       // since r2 is a reserved register (which prevents the register allocator
4209       // from allocating it), resulting in an additional register being
4210       // allocated and an unnecessary move instruction being generated.
4211       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4212
4213       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4214       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4215       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4216       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4217       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4218
4219       // The address needs to go after the chain input but before the flag (or
4220       // any other variadic arguments).
4221       Ops.insert(std::next(Ops.begin()), AddTOC);
4222     } else if ((CallOpc == PPCISD::CALL) &&
4223                (!isLocalCall(Callee) ||
4224                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4225       // Otherwise insert NOP for non-local calls.
4226       CallOpc = PPCISD::CALL_NOP;
4227   }
4228
4229   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4230   InFlag = Chain.getValue(1);
4231
4232   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4233                              DAG.getIntPtrConstant(BytesCalleePops, true),
4234                              InFlag, dl);
4235   if (!Ins.empty())
4236     InFlag = Chain.getValue(1);
4237
4238   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4239                          Ins, dl, DAG, InVals);
4240 }
4241
4242 SDValue
4243 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4244                              SmallVectorImpl<SDValue> &InVals) const {
4245   SelectionDAG &DAG                     = CLI.DAG;
4246   SDLoc &dl                             = CLI.DL;
4247   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4248   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4249   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4250   SDValue Chain                         = CLI.Chain;
4251   SDValue Callee                        = CLI.Callee;
4252   bool &isTailCall                      = CLI.IsTailCall;
4253   CallingConv::ID CallConv              = CLI.CallConv;
4254   bool isVarArg                         = CLI.IsVarArg;
4255   bool IsPatchPoint                     = CLI.IsPatchPoint;
4256   ImmutableCallSite *CS                 = CLI.CS;
4257
4258   if (isTailCall)
4259     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4260                                                    Ins, DAG);
4261
4262   if (!isTailCall && CS && CS->isMustTailCall())
4263     report_fatal_error("failed to perform tail call elimination on a call "
4264                        "site marked musttail");
4265
4266   if (Subtarget.isSVR4ABI()) {
4267     if (Subtarget.isPPC64())
4268       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4269                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4270                               dl, DAG, InVals, CS);
4271     else
4272       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4273                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4274                               dl, DAG, InVals, CS);
4275   }
4276
4277   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4278                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4279                           dl, DAG, InVals, CS);
4280 }
4281
4282 SDValue
4283 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4284                                     CallingConv::ID CallConv, bool isVarArg,
4285                                     bool isTailCall, bool IsPatchPoint,
4286                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4287                                     const SmallVectorImpl<SDValue> &OutVals,
4288                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4289                                     SDLoc dl, SelectionDAG &DAG,
4290                                     SmallVectorImpl<SDValue> &InVals,
4291                                     ImmutableCallSite *CS) const {
4292   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4293   // of the 32-bit SVR4 ABI stack frame layout.
4294
4295   assert((CallConv == CallingConv::C ||
4296           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4297
4298   unsigned PtrByteSize = 4;
4299
4300   MachineFunction &MF = DAG.getMachineFunction();
4301
4302   // Mark this function as potentially containing a function that contains a
4303   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4304   // and restoring the callers stack pointer in this functions epilog. This is
4305   // done because by tail calling the called function might overwrite the value
4306   // in this function's (MF) stack pointer stack slot 0(SP).
4307   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4308       CallConv == CallingConv::Fast)
4309     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4310
4311   // Count how many bytes are to be pushed on the stack, including the linkage
4312   // area, parameter list area and the part of the local variable space which
4313   // contains copies of aggregates which are passed by value.
4314
4315   // Assign locations to all of the outgoing arguments.
4316   SmallVector<CCValAssign, 16> ArgLocs;
4317   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4318                  *DAG.getContext());
4319
4320   // Reserve space for the linkage area on the stack.
4321   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4322                        PtrByteSize);
4323
4324   if (isVarArg) {
4325     // Handle fixed and variable vector arguments differently.
4326     // Fixed vector arguments go into registers as long as registers are
4327     // available. Variable vector arguments always go into memory.
4328     unsigned NumArgs = Outs.size();
4329
4330     for (unsigned i = 0; i != NumArgs; ++i) {
4331       MVT ArgVT = Outs[i].VT;
4332       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4333       bool Result;
4334
4335       if (Outs[i].IsFixed) {
4336         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4337                                CCInfo);
4338       } else {
4339         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4340                                       ArgFlags, CCInfo);
4341       }
4342
4343       if (Result) {
4344 #ifndef NDEBUG
4345         errs() << "Call operand #" << i << " has unhandled type "
4346              << EVT(ArgVT).getEVTString() << "\n";
4347 #endif
4348         llvm_unreachable(nullptr);
4349       }
4350     }
4351   } else {
4352     // All arguments are treated the same.
4353     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4354   }
4355
4356   // Assign locations to all of the outgoing aggregate by value arguments.
4357   SmallVector<CCValAssign, 16> ByValArgLocs;
4358   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4359                       ByValArgLocs, *DAG.getContext());
4360
4361   // Reserve stack space for the allocations in CCInfo.
4362   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4363
4364   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4365
4366   // Size of the linkage area, parameter list area and the part of the local
4367   // space variable where copies of aggregates which are passed by value are
4368   // stored.
4369   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4370
4371   // Calculate by how many bytes the stack has to be adjusted in case of tail
4372   // call optimization.
4373   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4374
4375   // Adjust the stack pointer for the new arguments...
4376   // These operations are automatically eliminated by the prolog/epilog pass
4377   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4378                                dl);
4379   SDValue CallSeqStart = Chain;
4380
4381   // Load the return address and frame pointer so it can be moved somewhere else
4382   // later.
4383   SDValue LROp, FPOp;
4384   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4385                                        dl);
4386
4387   // Set up a copy of the stack pointer for use loading and storing any
4388   // arguments that may not fit in the registers available for argument
4389   // passing.
4390   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4391
4392   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4393   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4394   SmallVector<SDValue, 8> MemOpChains;
4395
4396   bool seenFloatArg = false;
4397   // Walk the register/memloc assignments, inserting copies/loads.
4398   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4399        i != e;
4400        ++i) {
4401     CCValAssign &VA = ArgLocs[i];
4402     SDValue Arg = OutVals[i];
4403     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4404
4405     if (Flags.isByVal()) {
4406       // Argument is an aggregate which is passed by value, thus we need to
4407       // create a copy of it in the local variable space of the current stack
4408       // frame (which is the stack frame of the caller) and pass the address of
4409       // this copy to the callee.
4410       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4411       CCValAssign &ByValVA = ByValArgLocs[j++];
4412       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4413
4414       // Memory reserved in the local variable space of the callers stack frame.
4415       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4416
4417       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4418       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4419
4420       // Create a copy of the argument in the local area of the current
4421       // stack frame.
4422       SDValue MemcpyCall =
4423         CreateCopyOfByValArgument(Arg, PtrOff,
4424                                   CallSeqStart.getNode()->getOperand(0),
4425                                   Flags, DAG, dl);
4426
4427       // This must go outside the CALLSEQ_START..END.
4428       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4429                            CallSeqStart.getNode()->getOperand(1),
4430                            SDLoc(MemcpyCall));
4431       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4432                              NewCallSeqStart.getNode());
4433       Chain = CallSeqStart = NewCallSeqStart;
4434
4435       // Pass the address of the aggregate copy on the stack either in a
4436       // physical register or in the parameter list area of the current stack
4437       // frame to the callee.
4438       Arg = PtrOff;
4439     }
4440
4441     if (VA.isRegLoc()) {
4442       if (Arg.getValueType() == MVT::i1)
4443         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4444
4445       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4446       // Put argument in a physical register.
4447       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4448     } else {
4449       // Put argument in the parameter list area of the current stack frame.
4450       assert(VA.isMemLoc());
4451       unsigned LocMemOffset = VA.getLocMemOffset();
4452
4453       if (!isTailCall) {
4454         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4455         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4456
4457         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4458                                            MachinePointerInfo(),
4459                                            false, false, 0));
4460       } else {
4461         // Calculate and remember argument location.
4462         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4463                                  TailCallArguments);
4464       }
4465     }
4466   }
4467
4468   if (!MemOpChains.empty())
4469     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4470
4471   // Build a sequence of copy-to-reg nodes chained together with token chain
4472   // and flag operands which copy the outgoing args into the appropriate regs.
4473   SDValue InFlag;
4474   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4475     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4476                              RegsToPass[i].second, InFlag);
4477     InFlag = Chain.getValue(1);
4478   }
4479
4480   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4481   // registers.
4482   if (isVarArg) {
4483     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4484     SDValue Ops[] = { Chain, InFlag };
4485
4486     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4487                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4488
4489     InFlag = Chain.getValue(1);
4490   }
4491
4492   if (isTailCall)
4493     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4494                     false, TailCallArguments);
4495
4496   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4497                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4498                     NumBytes, Ins, InVals, CS);
4499 }
4500
4501 // Copy an argument into memory, being careful to do this outside the
4502 // call sequence for the call to which the argument belongs.
4503 SDValue
4504 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4505                                               SDValue CallSeqStart,
4506                                               ISD::ArgFlagsTy Flags,
4507                                               SelectionDAG &DAG,
4508                                               SDLoc dl) const {
4509   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4510                         CallSeqStart.getNode()->getOperand(0),
4511                         Flags, DAG, dl);
4512   // The MEMCPY must go outside the CALLSEQ_START..END.
4513   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4514                              CallSeqStart.getNode()->getOperand(1),
4515                              SDLoc(MemcpyCall));
4516   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4517                          NewCallSeqStart.getNode());
4518   return NewCallSeqStart;
4519 }
4520
4521 SDValue
4522 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4523                                     CallingConv::ID CallConv, bool isVarArg,
4524                                     bool isTailCall, bool IsPatchPoint,
4525                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4526                                     const SmallVectorImpl<SDValue> &OutVals,
4527                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4528                                     SDLoc dl, SelectionDAG &DAG,
4529                                     SmallVectorImpl<SDValue> &InVals,
4530                                     ImmutableCallSite *CS) const {
4531
4532   bool isELFv2ABI = Subtarget.isELFv2ABI();
4533   bool isLittleEndian = Subtarget.isLittleEndian();
4534   unsigned NumOps = Outs.size();
4535
4536   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4537   unsigned PtrByteSize = 8;
4538
4539   MachineFunction &MF = DAG.getMachineFunction();
4540
4541   // Mark this function as potentially containing a function that contains a
4542   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4543   // and restoring the callers stack pointer in this functions epilog. This is
4544   // done because by tail calling the called function might overwrite the value
4545   // in this function's (MF) stack pointer stack slot 0(SP).
4546   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4547       CallConv == CallingConv::Fast)
4548     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4549
4550   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4551          "fastcc not supported on varargs functions");
4552
4553   // Count how many bytes are to be pushed on the stack, including the linkage
4554   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4555   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4556   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4557   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4558   unsigned NumBytes = LinkageSize;
4559   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4560   unsigned &QFPR_idx = FPR_idx;
4561
4562   static const MCPhysReg GPR[] = {
4563     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4564     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4565   };
4566   static const MCPhysReg VR[] = {
4567     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4568     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4569   };
4570   static const MCPhysReg VSRH[] = {
4571     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4572     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4573   };
4574
4575   const unsigned NumGPRs = array_lengthof(GPR);
4576   const unsigned NumFPRs = 13;
4577   const unsigned NumVRs  = array_lengthof(VR);
4578   const unsigned NumQFPRs = NumFPRs;
4579
4580   // When using the fast calling convention, we don't provide backing for
4581   // arguments that will be in registers.
4582   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4583
4584   // Add up all the space actually used.
4585   for (unsigned i = 0; i != NumOps; ++i) {
4586     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4587     EVT ArgVT = Outs[i].VT;
4588     EVT OrigVT = Outs[i].ArgVT;
4589
4590     if (CallConv == CallingConv::Fast) {
4591       if (Flags.isByVal())
4592         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4593       else
4594         switch (ArgVT.getSimpleVT().SimpleTy) {
4595         default: llvm_unreachable("Unexpected ValueType for argument!");
4596         case MVT::i1:
4597         case MVT::i32:
4598         case MVT::i64:
4599           if (++NumGPRsUsed <= NumGPRs)
4600             continue;
4601           break;
4602         case MVT::v4i32:
4603         case MVT::v8i16:
4604         case MVT::v16i8:
4605         case MVT::v2f64:
4606         case MVT::v2i64:
4607           if (++NumVRsUsed <= NumVRs)
4608             continue;
4609           break;
4610         case MVT::v4f32:
4611           // When using QPX, this is handled like a FP register, otherwise, it
4612           // is an Altivec register.
4613           if (Subtarget.hasQPX()) {
4614             if (++NumFPRsUsed <= NumFPRs)
4615               continue;
4616           } else {
4617             if (++NumVRsUsed <= NumVRs)
4618               continue;
4619           }
4620           break;
4621         case MVT::f32:
4622         case MVT::f64:
4623         case MVT::v4f64: // QPX
4624         case MVT::v4i1:  // QPX
4625           if (++NumFPRsUsed <= NumFPRs)
4626             continue;
4627           break;
4628         }
4629     }
4630
4631     /* Respect alignment of argument on the stack.  */
4632     unsigned Align =
4633       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4634     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4635
4636     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4637     if (Flags.isInConsecutiveRegsLast())
4638       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4639   }
4640
4641   unsigned NumBytesActuallyUsed = NumBytes;
4642
4643   // The prolog code of the callee may store up to 8 GPR argument registers to
4644   // the stack, allowing va_start to index over them in memory if its varargs.
4645   // Because we cannot tell if this is needed on the caller side, we have to
4646   // conservatively assume that it is needed.  As such, make sure we have at
4647   // least enough stack space for the caller to store the 8 GPRs.
4648   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4649   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4650
4651   // Tail call needs the stack to be aligned.
4652   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4653       CallConv == CallingConv::Fast)
4654     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4655
4656   // Calculate by how many bytes the stack has to be adjusted in case of tail
4657   // call optimization.
4658   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4659
4660   // To protect arguments on the stack from being clobbered in a tail call,
4661   // force all the loads to happen before doing any other lowering.
4662   if (isTailCall)
4663     Chain = DAG.getStackArgumentTokenFactor(Chain);
4664
4665   // Adjust the stack pointer for the new arguments...
4666   // These operations are automatically eliminated by the prolog/epilog pass
4667   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4668                                dl);
4669   SDValue CallSeqStart = Chain;
4670
4671   // Load the return address and frame pointer so it can be move somewhere else
4672   // later.
4673   SDValue LROp, FPOp;
4674   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4675                                        dl);
4676
4677   // Set up a copy of the stack pointer for use loading and storing any
4678   // arguments that may not fit in the registers available for argument
4679   // passing.
4680   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4681
4682   // Figure out which arguments are going to go in registers, and which in
4683   // memory.  Also, if this is a vararg function, floating point operations
4684   // must be stored to our stack, and loaded into integer regs as well, if
4685   // any integer regs are available for argument passing.
4686   unsigned ArgOffset = LinkageSize;
4687
4688   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4689   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4690
4691   SmallVector<SDValue, 8> MemOpChains;
4692   for (unsigned i = 0; i != NumOps; ++i) {
4693     SDValue Arg = OutVals[i];
4694     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4695     EVT ArgVT = Outs[i].VT;
4696     EVT OrigVT = Outs[i].ArgVT;
4697
4698     // PtrOff will be used to store the current argument to the stack if a
4699     // register cannot be found for it.
4700     SDValue PtrOff;
4701
4702     // We re-align the argument offset for each argument, except when using the
4703     // fast calling convention, when we need to make sure we do that only when
4704     // we'll actually use a stack slot.
4705     auto ComputePtrOff = [&]() {
4706       /* Respect alignment of argument on the stack.  */
4707       unsigned Align =
4708         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4709       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4710
4711       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4712
4713       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4714     };
4715
4716     if (CallConv != CallingConv::Fast) {
4717       ComputePtrOff();
4718
4719       /* Compute GPR index associated with argument offset.  */
4720       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4721       GPR_idx = std::min(GPR_idx, NumGPRs);
4722     }
4723
4724     // Promote integers to 64-bit values.
4725     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4726       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4727       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4728       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4729     }
4730
4731     // FIXME memcpy is used way more than necessary.  Correctness first.
4732     // Note: "by value" is code for passing a structure by value, not
4733     // basic types.
4734     if (Flags.isByVal()) {
4735       // Note: Size includes alignment padding, so
4736       //   struct x { short a; char b; }
4737       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4738       // These are the proper values we need for right-justifying the
4739       // aggregate in a parameter register.
4740       unsigned Size = Flags.getByValSize();
4741
4742       // An empty aggregate parameter takes up no storage and no
4743       // registers.
4744       if (Size == 0)
4745         continue;
4746
4747       if (CallConv == CallingConv::Fast)
4748         ComputePtrOff();
4749
4750       // All aggregates smaller than 8 bytes must be passed right-justified.
4751       if (Size==1 || Size==2 || Size==4) {
4752         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4753         if (GPR_idx != NumGPRs) {
4754           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4755                                         MachinePointerInfo(), VT,
4756                                         false, false, false, 0);
4757           MemOpChains.push_back(Load.getValue(1));
4758           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4759
4760           ArgOffset += PtrByteSize;
4761           continue;
4762         }
4763       }
4764
4765       if (GPR_idx == NumGPRs && Size < 8) {
4766         SDValue AddPtr = PtrOff;
4767         if (!isLittleEndian) {
4768           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4769                                           PtrOff.getValueType());
4770           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4771         }
4772         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4773                                                           CallSeqStart,
4774                                                           Flags, DAG, dl);
4775         ArgOffset += PtrByteSize;
4776         continue;
4777       }
4778       // Copy entire object into memory.  There are cases where gcc-generated
4779       // code assumes it is there, even if it could be put entirely into
4780       // registers.  (This is not what the doc says.)
4781
4782       // FIXME: The above statement is likely due to a misunderstanding of the
4783       // documents.  All arguments must be copied into the parameter area BY
4784       // THE CALLEE in the event that the callee takes the address of any
4785       // formal argument.  That has not yet been implemented.  However, it is
4786       // reasonable to use the stack area as a staging area for the register
4787       // load.
4788
4789       // Skip this for small aggregates, as we will use the same slot for a
4790       // right-justified copy, below.
4791       if (Size >= 8)
4792         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4793                                                           CallSeqStart,
4794                                                           Flags, DAG, dl);
4795
4796       // When a register is available, pass a small aggregate right-justified.
4797       if (Size < 8 && GPR_idx != NumGPRs) {
4798         // The easiest way to get this right-justified in a register
4799         // is to copy the structure into the rightmost portion of a
4800         // local variable slot, then load the whole slot into the
4801         // register.
4802         // FIXME: The memcpy seems to produce pretty awful code for
4803         // small aggregates, particularly for packed ones.
4804         // FIXME: It would be preferable to use the slot in the
4805         // parameter save area instead of a new local variable.
4806         SDValue AddPtr = PtrOff;
4807         if (!isLittleEndian) {
4808           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4809           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4810         }
4811         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4812                                                           CallSeqStart,
4813                                                           Flags, DAG, dl);
4814
4815         // Load the slot into the register.
4816         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4817                                    MachinePointerInfo(),
4818                                    false, false, false, 0);
4819         MemOpChains.push_back(Load.getValue(1));
4820         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4821
4822         // Done with this argument.
4823         ArgOffset += PtrByteSize;
4824         continue;
4825       }
4826
4827       // For aggregates larger than PtrByteSize, copy the pieces of the
4828       // object that fit into registers from the parameter save area.
4829       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4830         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4831         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4832         if (GPR_idx != NumGPRs) {
4833           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4834                                      MachinePointerInfo(),
4835                                      false, false, false, 0);
4836           MemOpChains.push_back(Load.getValue(1));
4837           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4838           ArgOffset += PtrByteSize;
4839         } else {
4840           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4841           break;
4842         }
4843       }
4844       continue;
4845     }
4846
4847     switch (Arg.getSimpleValueType().SimpleTy) {
4848     default: llvm_unreachable("Unexpected ValueType for argument!");
4849     case MVT::i1:
4850     case MVT::i32:
4851     case MVT::i64:
4852       // These can be scalar arguments or elements of an integer array type
4853       // passed directly.  Clang may use those instead of "byval" aggregate
4854       // types to avoid forcing arguments to memory unnecessarily.
4855       if (GPR_idx != NumGPRs) {
4856         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4857       } else {
4858         if (CallConv == CallingConv::Fast)
4859           ComputePtrOff();
4860
4861         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4862                          true, isTailCall, false, MemOpChains,
4863                          TailCallArguments, dl);
4864         if (CallConv == CallingConv::Fast)
4865           ArgOffset += PtrByteSize;
4866       }
4867       if (CallConv != CallingConv::Fast)
4868         ArgOffset += PtrByteSize;
4869       break;
4870     case MVT::f32:
4871     case MVT::f64: {
4872       // These can be scalar arguments or elements of a float array type
4873       // passed directly.  The latter are used to implement ELFv2 homogenous
4874       // float aggregates.
4875
4876       // Named arguments go into FPRs first, and once they overflow, the
4877       // remaining arguments go into GPRs and then the parameter save area.
4878       // Unnamed arguments for vararg functions always go to GPRs and
4879       // then the parameter save area.  For now, put all arguments to vararg
4880       // routines always in both locations (FPR *and* GPR or stack slot).
4881       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4882       bool NeededLoad = false;
4883
4884       // First load the argument into the next available FPR.
4885       if (FPR_idx != NumFPRs)
4886         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4887
4888       // Next, load the argument into GPR or stack slot if needed.
4889       if (!NeedGPROrStack)
4890         ;
4891       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4892         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4893         // once we support fp <-> gpr moves.
4894
4895         // In the non-vararg case, this can only ever happen in the
4896         // presence of f32 array types, since otherwise we never run
4897         // out of FPRs before running out of GPRs.
4898         SDValue ArgVal;
4899
4900         // Double values are always passed in a single GPR.
4901         if (Arg.getValueType() != MVT::f32) {
4902           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4903
4904         // Non-array float values are extended and passed in a GPR.
4905         } else if (!Flags.isInConsecutiveRegs()) {
4906           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4907           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4908
4909         // If we have an array of floats, we collect every odd element
4910         // together with its predecessor into one GPR.
4911         } else if (ArgOffset % PtrByteSize != 0) {
4912           SDValue Lo, Hi;
4913           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4914           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4915           if (!isLittleEndian)
4916             std::swap(Lo, Hi);
4917           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4918
4919         // The final element, if even, goes into the first half of a GPR.
4920         } else if (Flags.isInConsecutiveRegsLast()) {
4921           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4922           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4923           if (!isLittleEndian)
4924             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4925                                  DAG.getConstant(32, MVT::i32));
4926
4927         // Non-final even elements are skipped; they will be handled
4928         // together the with subsequent argument on the next go-around.
4929         } else
4930           ArgVal = SDValue();
4931
4932         if (ArgVal.getNode())
4933           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4934       } else {
4935         if (CallConv == CallingConv::Fast)
4936           ComputePtrOff();
4937
4938         // Single-precision floating-point values are mapped to the
4939         // second (rightmost) word of the stack doubleword.
4940         if (Arg.getValueType() == MVT::f32 &&
4941             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4942           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4943           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4944         }
4945
4946         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4947                          true, isTailCall, false, MemOpChains,
4948                          TailCallArguments, dl);
4949
4950         NeededLoad = true;
4951       }
4952       // When passing an array of floats, the array occupies consecutive
4953       // space in the argument area; only round up to the next doubleword
4954       // at the end of the array.  Otherwise, each float takes 8 bytes.
4955       if (CallConv != CallingConv::Fast || NeededLoad) {
4956         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4957                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4958         if (Flags.isInConsecutiveRegsLast())
4959           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4960       }
4961       break;
4962     }
4963     case MVT::v4f32:
4964     case MVT::v4i32:
4965     case MVT::v8i16:
4966     case MVT::v16i8:
4967     case MVT::v2f64:
4968     case MVT::v2i64:
4969       if (!Subtarget.hasQPX()) {
4970       // These can be scalar arguments or elements of a vector array type
4971       // passed directly.  The latter are used to implement ELFv2 homogenous
4972       // vector aggregates.
4973
4974       // For a varargs call, named arguments go into VRs or on the stack as
4975       // usual; unnamed arguments always go to the stack or the corresponding
4976       // GPRs when within range.  For now, we always put the value in both
4977       // locations (or even all three).
4978       if (isVarArg) {
4979         // We could elide this store in the case where the object fits
4980         // entirely in R registers.  Maybe later.
4981         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4982                                      MachinePointerInfo(), false, false, 0);
4983         MemOpChains.push_back(Store);
4984         if (VR_idx != NumVRs) {
4985           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4986                                      MachinePointerInfo(),
4987                                      false, false, false, 0);
4988           MemOpChains.push_back(Load.getValue(1));
4989
4990           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4991                            Arg.getSimpleValueType() == MVT::v2i64) ?
4992                           VSRH[VR_idx] : VR[VR_idx];
4993           ++VR_idx;
4994
4995           RegsToPass.push_back(std::make_pair(VReg, Load));
4996         }
4997         ArgOffset += 16;
4998         for (unsigned i=0; i<16; i+=PtrByteSize) {
4999           if (GPR_idx == NumGPRs)
5000             break;
5001           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5002                                   DAG.getConstant(i, PtrVT));
5003           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5004                                      false, false, false, 0);
5005           MemOpChains.push_back(Load.getValue(1));
5006           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5007         }
5008         break;
5009       }
5010
5011       // Non-varargs Altivec params go into VRs or on the stack.
5012       if (VR_idx != NumVRs) {
5013         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5014                          Arg.getSimpleValueType() == MVT::v2i64) ?
5015                         VSRH[VR_idx] : VR[VR_idx];
5016         ++VR_idx;
5017
5018         RegsToPass.push_back(std::make_pair(VReg, Arg));
5019       } else {
5020         if (CallConv == CallingConv::Fast)
5021           ComputePtrOff();
5022
5023         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5024                          true, isTailCall, true, MemOpChains,
5025                          TailCallArguments, dl);
5026         if (CallConv == CallingConv::Fast)
5027           ArgOffset += 16;
5028       }
5029
5030       if (CallConv != CallingConv::Fast)
5031         ArgOffset += 16;
5032       break;
5033       } // not QPX
5034
5035       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5036              "Invalid QPX parameter type");
5037
5038       /* fall through */
5039     case MVT::v4f64:
5040     case MVT::v4i1: {
5041       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5042       if (isVarArg) {
5043         // We could elide this store in the case where the object fits
5044         // entirely in R registers.  Maybe later.
5045         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5046                                      MachinePointerInfo(), false, false, 0);
5047         MemOpChains.push_back(Store);
5048         if (QFPR_idx != NumQFPRs) {
5049           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5050                                      Store, PtrOff, MachinePointerInfo(),
5051                                      false, false, false, 0);
5052           MemOpChains.push_back(Load.getValue(1));
5053           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5054         }
5055         ArgOffset += (IsF32 ? 16 : 32);
5056         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5057           if (GPR_idx == NumGPRs)
5058             break;
5059           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5060                                   DAG.getConstant(i, PtrVT));
5061           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5062                                      false, false, false, 0);
5063           MemOpChains.push_back(Load.getValue(1));
5064           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5065         }
5066         break;
5067       }
5068
5069       // Non-varargs QPX params go into registers or on the stack.
5070       if (QFPR_idx != NumQFPRs) {
5071         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5072       } else {
5073         if (CallConv == CallingConv::Fast)
5074           ComputePtrOff();
5075
5076         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5077                          true, isTailCall, true, MemOpChains,
5078                          TailCallArguments, dl);
5079         if (CallConv == CallingConv::Fast)
5080           ArgOffset += (IsF32 ? 16 : 32);
5081       }
5082
5083       if (CallConv != CallingConv::Fast)
5084         ArgOffset += (IsF32 ? 16 : 32);
5085       break;
5086       }
5087     }
5088   }
5089
5090   assert(NumBytesActuallyUsed == ArgOffset);
5091   (void)NumBytesActuallyUsed;
5092
5093   if (!MemOpChains.empty())
5094     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5095
5096   // Check if this is an indirect call (MTCTR/BCTRL).
5097   // See PrepareCall() for more information about calls through function
5098   // pointers in the 64-bit SVR4 ABI.
5099   if (!isTailCall && !IsPatchPoint &&
5100       !isFunctionGlobalAddress(Callee) &&
5101       !isa<ExternalSymbolSDNode>(Callee)) {
5102     // Load r2 into a virtual register and store it to the TOC save area.
5103     setUsesTOCBasePtr(DAG);
5104     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5105     // TOC save area offset.
5106     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5107     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5108     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5109     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5110                          MachinePointerInfo::getStack(TOCSaveOffset),
5111                          false, false, 0);
5112     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5113     // This does not mean the MTCTR instruction must use R12; it's easier
5114     // to model this as an extra parameter, so do that.
5115     if (isELFv2ABI && !IsPatchPoint)
5116       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5117   }
5118
5119   // Build a sequence of copy-to-reg nodes chained together with token chain
5120   // and flag operands which copy the outgoing args into the appropriate regs.
5121   SDValue InFlag;
5122   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5123     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5124                              RegsToPass[i].second, InFlag);
5125     InFlag = Chain.getValue(1);
5126   }
5127
5128   if (isTailCall)
5129     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5130                     FPOp, true, TailCallArguments);
5131
5132   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5133                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5134                     NumBytes, Ins, InVals, CS);
5135 }
5136
5137 SDValue
5138 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5139                                     CallingConv::ID CallConv, bool isVarArg,
5140                                     bool isTailCall, bool IsPatchPoint,
5141                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5142                                     const SmallVectorImpl<SDValue> &OutVals,
5143                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5144                                     SDLoc dl, SelectionDAG &DAG,
5145                                     SmallVectorImpl<SDValue> &InVals,
5146                                     ImmutableCallSite *CS) const {
5147
5148   unsigned NumOps = Outs.size();
5149
5150   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5151   bool isPPC64 = PtrVT == MVT::i64;
5152   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5153
5154   MachineFunction &MF = DAG.getMachineFunction();
5155
5156   // Mark this function as potentially containing a function that contains a
5157   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5158   // and restoring the callers stack pointer in this functions epilog. This is
5159   // done because by tail calling the called function might overwrite the value
5160   // in this function's (MF) stack pointer stack slot 0(SP).
5161   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5162       CallConv == CallingConv::Fast)
5163     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5164
5165   // Count how many bytes are to be pushed on the stack, including the linkage
5166   // area, and parameter passing area.  We start with 24/48 bytes, which is
5167   // prereserved space for [SP][CR][LR][3 x unused].
5168   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5169   unsigned NumBytes = LinkageSize;
5170
5171   // Add up all the space actually used.
5172   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5173   // they all go in registers, but we must reserve stack space for them for
5174   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5175   // assigned stack space in order, with padding so Altivec parameters are
5176   // 16-byte aligned.
5177   unsigned nAltivecParamsAtEnd = 0;
5178   for (unsigned i = 0; i != NumOps; ++i) {
5179     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5180     EVT ArgVT = Outs[i].VT;
5181     // Varargs Altivec parameters are padded to a 16 byte boundary.
5182     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5183         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5184         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5185       if (!isVarArg && !isPPC64) {
5186         // Non-varargs Altivec parameters go after all the non-Altivec
5187         // parameters; handle those later so we know how much padding we need.
5188         nAltivecParamsAtEnd++;
5189         continue;
5190       }
5191       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5192       NumBytes = ((NumBytes+15)/16)*16;
5193     }
5194     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5195   }
5196
5197   // Allow for Altivec parameters at the end, if needed.
5198   if (nAltivecParamsAtEnd) {
5199     NumBytes = ((NumBytes+15)/16)*16;
5200     NumBytes += 16*nAltivecParamsAtEnd;
5201   }
5202
5203   // The prolog code of the callee may store up to 8 GPR argument registers to
5204   // the stack, allowing va_start to index over them in memory if its varargs.
5205   // Because we cannot tell if this is needed on the caller side, we have to
5206   // conservatively assume that it is needed.  As such, make sure we have at
5207   // least enough stack space for the caller to store the 8 GPRs.
5208   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5209
5210   // Tail call needs the stack to be aligned.
5211   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5212       CallConv == CallingConv::Fast)
5213     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5214
5215   // Calculate by how many bytes the stack has to be adjusted in case of tail
5216   // call optimization.
5217   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5218
5219   // To protect arguments on the stack from being clobbered in a tail call,
5220   // force all the loads to happen before doing any other lowering.
5221   if (isTailCall)
5222     Chain = DAG.getStackArgumentTokenFactor(Chain);
5223
5224   // Adjust the stack pointer for the new arguments...
5225   // These operations are automatically eliminated by the prolog/epilog pass
5226   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5227                                dl);
5228   SDValue CallSeqStart = Chain;
5229
5230   // Load the return address and frame pointer so it can be move somewhere else
5231   // later.
5232   SDValue LROp, FPOp;
5233   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5234                                        dl);
5235
5236   // Set up a copy of the stack pointer for use loading and storing any
5237   // arguments that may not fit in the registers available for argument
5238   // passing.
5239   SDValue StackPtr;
5240   if (isPPC64)
5241     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5242   else
5243     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5244
5245   // Figure out which arguments are going to go in registers, and which in
5246   // memory.  Also, if this is a vararg function, floating point operations
5247   // must be stored to our stack, and loaded into integer regs as well, if
5248   // any integer regs are available for argument passing.
5249   unsigned ArgOffset = LinkageSize;
5250   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5251
5252   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5253     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5254     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5255   };
5256   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5257     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5258     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5259   };
5260   static const MCPhysReg VR[] = {
5261     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5262     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5263   };
5264   const unsigned NumGPRs = array_lengthof(GPR_32);
5265   const unsigned NumFPRs = 13;
5266   const unsigned NumVRs  = array_lengthof(VR);
5267
5268   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5269
5270   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5271   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5272
5273   SmallVector<SDValue, 8> MemOpChains;
5274   for (unsigned i = 0; i != NumOps; ++i) {
5275     SDValue Arg = OutVals[i];
5276     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5277
5278     // PtrOff will be used to store the current argument to the stack if a
5279     // register cannot be found for it.
5280     SDValue PtrOff;
5281
5282     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5283
5284     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5285
5286     // On PPC64, promote integers to 64-bit values.
5287     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5288       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5289       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5290       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5291     }
5292
5293     // FIXME memcpy is used way more than necessary.  Correctness first.
5294     // Note: "by value" is code for passing a structure by value, not
5295     // basic types.
5296     if (Flags.isByVal()) {
5297       unsigned Size = Flags.getByValSize();
5298       // Very small objects are passed right-justified.  Everything else is
5299       // passed left-justified.
5300       if (Size==1 || Size==2) {
5301         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5302         if (GPR_idx != NumGPRs) {
5303           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5304                                         MachinePointerInfo(), VT,
5305                                         false, false, false, 0);
5306           MemOpChains.push_back(Load.getValue(1));
5307           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5308
5309           ArgOffset += PtrByteSize;
5310         } else {
5311           SDValue Const = DAG.getConstant(PtrByteSize - Size,
5312                                           PtrOff.getValueType());
5313           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5314           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5315                                                             CallSeqStart,
5316                                                             Flags, DAG, dl);
5317           ArgOffset += PtrByteSize;
5318         }
5319         continue;
5320       }
5321       // Copy entire object into memory.  There are cases where gcc-generated
5322       // code assumes it is there, even if it could be put entirely into
5323       // registers.  (This is not what the doc says.)
5324       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5325                                                         CallSeqStart,
5326                                                         Flags, DAG, dl);
5327
5328       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5329       // copy the pieces of the object that fit into registers from the
5330       // parameter save area.
5331       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5332         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5333         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5334         if (GPR_idx != NumGPRs) {
5335           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5336                                      MachinePointerInfo(),
5337                                      false, false, false, 0);
5338           MemOpChains.push_back(Load.getValue(1));
5339           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5340           ArgOffset += PtrByteSize;
5341         } else {
5342           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5343           break;
5344         }
5345       }
5346       continue;
5347     }
5348
5349     switch (Arg.getSimpleValueType().SimpleTy) {
5350     default: llvm_unreachable("Unexpected ValueType for argument!");
5351     case MVT::i1:
5352     case MVT::i32:
5353     case MVT::i64:
5354       if (GPR_idx != NumGPRs) {
5355         if (Arg.getValueType() == MVT::i1)
5356           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5357
5358         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5359       } else {
5360         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5361                          isPPC64, isTailCall, false, MemOpChains,
5362                          TailCallArguments, dl);
5363       }
5364       ArgOffset += PtrByteSize;
5365       break;
5366     case MVT::f32:
5367     case MVT::f64:
5368       if (FPR_idx != NumFPRs) {
5369         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5370
5371         if (isVarArg) {
5372           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5373                                        MachinePointerInfo(), false, false, 0);
5374           MemOpChains.push_back(Store);
5375
5376           // Float varargs are always shadowed in available integer registers
5377           if (GPR_idx != NumGPRs) {
5378             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5379                                        MachinePointerInfo(), false, false,
5380                                        false, 0);
5381             MemOpChains.push_back(Load.getValue(1));
5382             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5383           }
5384           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5385             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5386             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5387             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5388                                        MachinePointerInfo(),
5389                                        false, false, false, 0);
5390             MemOpChains.push_back(Load.getValue(1));
5391             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5392           }
5393         } else {
5394           // If we have any FPRs remaining, we may also have GPRs remaining.
5395           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5396           // GPRs.
5397           if (GPR_idx != NumGPRs)
5398             ++GPR_idx;
5399           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5400               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5401             ++GPR_idx;
5402         }
5403       } else
5404         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5405                          isPPC64, isTailCall, false, MemOpChains,
5406                          TailCallArguments, dl);
5407       if (isPPC64)
5408         ArgOffset += 8;
5409       else
5410         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5411       break;
5412     case MVT::v4f32:
5413     case MVT::v4i32:
5414     case MVT::v8i16:
5415     case MVT::v16i8:
5416       if (isVarArg) {
5417         // These go aligned on the stack, or in the corresponding R registers
5418         // when within range.  The Darwin PPC ABI doc claims they also go in
5419         // V registers; in fact gcc does this only for arguments that are
5420         // prototyped, not for those that match the ...  We do it for all
5421         // arguments, seems to work.
5422         while (ArgOffset % 16 !=0) {
5423           ArgOffset += PtrByteSize;
5424           if (GPR_idx != NumGPRs)
5425             GPR_idx++;
5426         }
5427         // We could elide this store in the case where the object fits
5428         // entirely in R registers.  Maybe later.
5429         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5430                             DAG.getConstant(ArgOffset, PtrVT));
5431         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5432                                      MachinePointerInfo(), false, false, 0);
5433         MemOpChains.push_back(Store);
5434         if (VR_idx != NumVRs) {
5435           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5436                                      MachinePointerInfo(),
5437                                      false, false, false, 0);
5438           MemOpChains.push_back(Load.getValue(1));
5439           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5440         }
5441         ArgOffset += 16;
5442         for (unsigned i=0; i<16; i+=PtrByteSize) {
5443           if (GPR_idx == NumGPRs)
5444             break;
5445           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5446                                   DAG.getConstant(i, PtrVT));
5447           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5448                                      false, false, false, 0);
5449           MemOpChains.push_back(Load.getValue(1));
5450           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5451         }
5452         break;
5453       }
5454
5455       // Non-varargs Altivec params generally go in registers, but have
5456       // stack space allocated at the end.
5457       if (VR_idx != NumVRs) {
5458         // Doesn't have GPR space allocated.
5459         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5460       } else if (nAltivecParamsAtEnd==0) {
5461         // We are emitting Altivec params in order.
5462         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5463                          isPPC64, isTailCall, true, MemOpChains,
5464                          TailCallArguments, dl);
5465         ArgOffset += 16;
5466       }
5467       break;
5468     }
5469   }
5470   // If all Altivec parameters fit in registers, as they usually do,
5471   // they get stack space following the non-Altivec parameters.  We
5472   // don't track this here because nobody below needs it.
5473   // If there are more Altivec parameters than fit in registers emit
5474   // the stores here.
5475   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5476     unsigned j = 0;
5477     // Offset is aligned; skip 1st 12 params which go in V registers.
5478     ArgOffset = ((ArgOffset+15)/16)*16;
5479     ArgOffset += 12*16;
5480     for (unsigned i = 0; i != NumOps; ++i) {
5481       SDValue Arg = OutVals[i];
5482       EVT ArgType = Outs[i].VT;
5483       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5484           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5485         if (++j > NumVRs) {
5486           SDValue PtrOff;
5487           // We are emitting Altivec params in order.
5488           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5489                            isPPC64, isTailCall, true, MemOpChains,
5490                            TailCallArguments, dl);
5491           ArgOffset += 16;
5492         }
5493       }
5494     }
5495   }
5496
5497   if (!MemOpChains.empty())
5498     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5499
5500   // On Darwin, R12 must contain the address of an indirect callee.  This does
5501   // not mean the MTCTR instruction must use R12; it's easier to model this as
5502   // an extra parameter, so do that.
5503   if (!isTailCall &&
5504       !isFunctionGlobalAddress(Callee) &&
5505       !isa<ExternalSymbolSDNode>(Callee) &&
5506       !isBLACompatibleAddress(Callee, DAG))
5507     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5508                                                    PPC::R12), Callee));
5509
5510   // Build a sequence of copy-to-reg nodes chained together with token chain
5511   // and flag operands which copy the outgoing args into the appropriate regs.
5512   SDValue InFlag;
5513   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5514     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5515                              RegsToPass[i].second, InFlag);
5516     InFlag = Chain.getValue(1);
5517   }
5518
5519   if (isTailCall)
5520     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5521                     FPOp, true, TailCallArguments);
5522
5523   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5524                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5525                     NumBytes, Ins, InVals, CS);
5526 }
5527
5528 bool
5529 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5530                                   MachineFunction &MF, bool isVarArg,
5531                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5532                                   LLVMContext &Context) const {
5533   SmallVector<CCValAssign, 16> RVLocs;
5534   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5535   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5536 }
5537
5538 SDValue
5539 PPCTargetLowering::LowerReturn(SDValue Chain,
5540                                CallingConv::ID CallConv, bool isVarArg,
5541                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5542                                const SmallVectorImpl<SDValue> &OutVals,
5543                                SDLoc dl, SelectionDAG &DAG) const {
5544
5545   SmallVector<CCValAssign, 16> RVLocs;
5546   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5547                  *DAG.getContext());
5548   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5549
5550   SDValue Flag;
5551   SmallVector<SDValue, 4> RetOps(1, Chain);
5552
5553   // Copy the result values into the output registers.
5554   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5555     CCValAssign &VA = RVLocs[i];
5556     assert(VA.isRegLoc() && "Can only return in registers!");
5557
5558     SDValue Arg = OutVals[i];
5559
5560     switch (VA.getLocInfo()) {
5561     default: llvm_unreachable("Unknown loc info!");
5562     case CCValAssign::Full: break;
5563     case CCValAssign::AExt:
5564       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5565       break;
5566     case CCValAssign::ZExt:
5567       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5568       break;
5569     case CCValAssign::SExt:
5570       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5571       break;
5572     }
5573
5574     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5575     Flag = Chain.getValue(1);
5576     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5577   }
5578
5579   RetOps[0] = Chain;  // Update chain.
5580
5581   // Add the flag if we have it.
5582   if (Flag.getNode())
5583     RetOps.push_back(Flag);
5584
5585   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5586 }
5587
5588 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5589                                    const PPCSubtarget &Subtarget) const {
5590   // When we pop the dynamic allocation we need to restore the SP link.
5591   SDLoc dl(Op);
5592
5593   // Get the corect type for pointers.
5594   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5595
5596   // Construct the stack pointer operand.
5597   bool isPPC64 = Subtarget.isPPC64();
5598   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5599   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5600
5601   // Get the operands for the STACKRESTORE.
5602   SDValue Chain = Op.getOperand(0);
5603   SDValue SaveSP = Op.getOperand(1);
5604
5605   // Load the old link SP.
5606   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5607                                    MachinePointerInfo(),
5608                                    false, false, false, 0);
5609
5610   // Restore the stack pointer.
5611   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5612
5613   // Store the old link SP.
5614   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5615                       false, false, 0);
5616 }
5617
5618
5619
5620 SDValue
5621 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5622   MachineFunction &MF = DAG.getMachineFunction();
5623   bool isPPC64 = Subtarget.isPPC64();
5624   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5625
5626   // Get current frame pointer save index.  The users of this index will be
5627   // primarily DYNALLOC instructions.
5628   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5629   int RASI = FI->getReturnAddrSaveIndex();
5630
5631   // If the frame pointer save index hasn't been defined yet.
5632   if (!RASI) {
5633     // Find out what the fix offset of the frame pointer save area.
5634     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5635     // Allocate the frame index for frame pointer save area.
5636     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5637     // Save the result.
5638     FI->setReturnAddrSaveIndex(RASI);
5639   }
5640   return DAG.getFrameIndex(RASI, PtrVT);
5641 }
5642
5643 SDValue
5644 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5645   MachineFunction &MF = DAG.getMachineFunction();
5646   bool isPPC64 = Subtarget.isPPC64();
5647   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5648
5649   // Get current frame pointer save index.  The users of this index will be
5650   // primarily DYNALLOC instructions.
5651   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5652   int FPSI = FI->getFramePointerSaveIndex();
5653
5654   // If the frame pointer save index hasn't been defined yet.
5655   if (!FPSI) {
5656     // Find out what the fix offset of the frame pointer save area.
5657     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5658     // Allocate the frame index for frame pointer save area.
5659     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5660     // Save the result.
5661     FI->setFramePointerSaveIndex(FPSI);
5662   }
5663   return DAG.getFrameIndex(FPSI, PtrVT);
5664 }
5665
5666 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5667                                          SelectionDAG &DAG,
5668                                          const PPCSubtarget &Subtarget) const {
5669   // Get the inputs.
5670   SDValue Chain = Op.getOperand(0);
5671   SDValue Size  = Op.getOperand(1);
5672   SDLoc dl(Op);
5673
5674   // Get the corect type for pointers.
5675   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5676   // Negate the size.
5677   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5678                                   DAG.getConstant(0, PtrVT), Size);
5679   // Construct a node for the frame pointer save index.
5680   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5681   // Build a DYNALLOC node.
5682   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5683   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5684   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5685 }
5686
5687 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5688                                                SelectionDAG &DAG) const {
5689   SDLoc DL(Op);
5690   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5691                      DAG.getVTList(MVT::i32, MVT::Other),
5692                      Op.getOperand(0), Op.getOperand(1));
5693 }
5694
5695 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5696                                                 SelectionDAG &DAG) const {
5697   SDLoc DL(Op);
5698   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5699                      Op.getOperand(0), Op.getOperand(1));
5700 }
5701
5702 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5703   if (Op.getValueType().isVector())
5704     return LowerVectorLoad(Op, DAG);
5705
5706   assert(Op.getValueType() == MVT::i1 &&
5707          "Custom lowering only for i1 loads");
5708
5709   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5710
5711   SDLoc dl(Op);
5712   LoadSDNode *LD = cast<LoadSDNode>(Op);
5713
5714   SDValue Chain = LD->getChain();
5715   SDValue BasePtr = LD->getBasePtr();
5716   MachineMemOperand *MMO = LD->getMemOperand();
5717
5718   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5719                                  BasePtr, MVT::i8, MMO);
5720   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5721
5722   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5723   return DAG.getMergeValues(Ops, dl);
5724 }
5725
5726 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5727   if (Op.getOperand(1).getValueType().isVector())
5728     return LowerVectorStore(Op, DAG);
5729
5730   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5731          "Custom lowering only for i1 stores");
5732
5733   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5734
5735   SDLoc dl(Op);
5736   StoreSDNode *ST = cast<StoreSDNode>(Op);
5737
5738   SDValue Chain = ST->getChain();
5739   SDValue BasePtr = ST->getBasePtr();
5740   SDValue Value = ST->getValue();
5741   MachineMemOperand *MMO = ST->getMemOperand();
5742
5743   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5744   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5745 }
5746
5747 // FIXME: Remove this once the ANDI glue bug is fixed:
5748 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5749   assert(Op.getValueType() == MVT::i1 &&
5750          "Custom lowering only for i1 results");
5751
5752   SDLoc DL(Op);
5753   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5754                      Op.getOperand(0));
5755 }
5756
5757 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5758 /// possible.
5759 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5760   // Not FP? Not a fsel.
5761   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5762       !Op.getOperand(2).getValueType().isFloatingPoint())
5763     return Op;
5764
5765   // We might be able to do better than this under some circumstances, but in
5766   // general, fsel-based lowering of select is a finite-math-only optimization.
5767   // For more information, see section F.3 of the 2.06 ISA specification.
5768   if (!DAG.getTarget().Options.NoInfsFPMath ||
5769       !DAG.getTarget().Options.NoNaNsFPMath)
5770     return Op;
5771
5772   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5773
5774   EVT ResVT = Op.getValueType();
5775   EVT CmpVT = Op.getOperand(0).getValueType();
5776   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5777   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5778   SDLoc dl(Op);
5779
5780   // If the RHS of the comparison is a 0.0, we don't need to do the
5781   // subtraction at all.
5782   SDValue Sel1;
5783   if (isFloatingPointZero(RHS))
5784     switch (CC) {
5785     default: break;       // SETUO etc aren't handled by fsel.
5786     case ISD::SETNE:
5787       std::swap(TV, FV);
5788     case ISD::SETEQ:
5789       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5790         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5791       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5792       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5793         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5794       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5795                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5796     case ISD::SETULT:
5797     case ISD::SETLT:
5798       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5799     case ISD::SETOGE:
5800     case ISD::SETGE:
5801       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5802         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5803       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5804     case ISD::SETUGT:
5805     case ISD::SETGT:
5806       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5807     case ISD::SETOLE:
5808     case ISD::SETLE:
5809       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5810         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5811       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5812                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5813     }
5814
5815   SDValue Cmp;
5816   switch (CC) {
5817   default: break;       // SETUO etc aren't handled by fsel.
5818   case ISD::SETNE:
5819     std::swap(TV, FV);
5820   case ISD::SETEQ:
5821     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5822     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5823       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5824     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5825     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5826       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5827     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5828                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5829   case ISD::SETULT:
5830   case ISD::SETLT:
5831     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5832     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5833       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5834     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5835   case ISD::SETOGE:
5836   case ISD::SETGE:
5837     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5838     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5839       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5840     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5841   case ISD::SETUGT:
5842   case ISD::SETGT:
5843     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5844     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5845       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5846     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5847   case ISD::SETOLE:
5848   case ISD::SETLE:
5849     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5850     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5851       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5852     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5853   }
5854   return Op;
5855 }
5856
5857 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5858                                                SelectionDAG &DAG,
5859                                                SDLoc dl) const {
5860   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5861   SDValue Src = Op.getOperand(0);
5862   if (Src.getValueType() == MVT::f32)
5863     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5864
5865   SDValue Tmp;
5866   switch (Op.getSimpleValueType().SimpleTy) {
5867   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5868   case MVT::i32:
5869     Tmp = DAG.getNode(
5870         Op.getOpcode() == ISD::FP_TO_SINT
5871             ? PPCISD::FCTIWZ
5872             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5873         dl, MVT::f64, Src);
5874     break;
5875   case MVT::i64:
5876     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5877            "i64 FP_TO_UINT is supported only with FPCVT");
5878     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5879                                                         PPCISD::FCTIDUZ,
5880                       dl, MVT::f64, Src);
5881     break;
5882   }
5883
5884   // Convert the FP value to an int value through memory.
5885   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5886     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5887   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5888   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5889   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5890
5891   // Emit a store to the stack slot.
5892   SDValue Chain;
5893   if (i32Stack) {
5894     MachineFunction &MF = DAG.getMachineFunction();
5895     MachineMemOperand *MMO =
5896       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5897     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5898     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5899               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5900   } else
5901     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5902                          MPI, false, false, 0);
5903
5904   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5905   // add in a bias.
5906   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5907     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5908                         DAG.getConstant(4, FIPtr.getValueType()));
5909     MPI = MPI.getWithOffset(4);
5910   }
5911
5912   RLI.Chain = Chain;
5913   RLI.Ptr = FIPtr;
5914   RLI.MPI = MPI;
5915 }
5916
5917 /// \brief Custom lowers floating point to integer conversions to use
5918 /// the direct move instructions available in ISA 2.07 to avoid the
5919 /// need for load/store combinations.
5920 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
5921                                                     SelectionDAG &DAG,
5922                                                     SDLoc dl) const {
5923   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5924   SDValue Src = Op.getOperand(0);
5925
5926   if (Src.getValueType() == MVT::f32)
5927     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5928
5929   SDValue Tmp;
5930   switch (Op.getSimpleValueType().SimpleTy) {
5931   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5932   case MVT::i32:
5933     Tmp = DAG.getNode(
5934         Op.getOpcode() == ISD::FP_TO_SINT
5935             ? PPCISD::FCTIWZ
5936             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5937         dl, MVT::f64, Src);
5938     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
5939     break;
5940   case MVT::i64:
5941     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5942            "i64 FP_TO_UINT is supported only with FPCVT");
5943     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5944                                                         PPCISD::FCTIDUZ,
5945                       dl, MVT::f64, Src);
5946     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
5947     break;
5948   }
5949   return Tmp;
5950 }
5951
5952 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5953                                           SDLoc dl) const {
5954   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
5955     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
5956
5957   ReuseLoadInfo RLI;
5958   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5959
5960   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5961                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5962                      RLI.Ranges);
5963 }
5964
5965 // We're trying to insert a regular store, S, and then a load, L. If the
5966 // incoming value, O, is a load, we might just be able to have our load use the
5967 // address used by O. However, we don't know if anything else will store to
5968 // that address before we can load from it. To prevent this situation, we need
5969 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5970 // the same chain operand as O, we create a token factor from the chain results
5971 // of O and L, and we replace all uses of O's chain result with that token
5972 // factor (see spliceIntoChain below for this last part).
5973 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5974                                             ReuseLoadInfo &RLI,
5975                                             SelectionDAG &DAG,
5976                                             ISD::LoadExtType ET) const {
5977   SDLoc dl(Op);
5978   if (ET == ISD::NON_EXTLOAD &&
5979       (Op.getOpcode() == ISD::FP_TO_UINT ||
5980        Op.getOpcode() == ISD::FP_TO_SINT) &&
5981       isOperationLegalOrCustom(Op.getOpcode(),
5982                                Op.getOperand(0).getValueType())) {
5983
5984     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5985     return true;
5986   }
5987
5988   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5989   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5990       LD->isNonTemporal())
5991     return false;
5992   if (LD->getMemoryVT() != MemVT)
5993     return false;
5994
5995   RLI.Ptr = LD->getBasePtr();
5996   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5997     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5998            "Non-pre-inc AM on PPC?");
5999     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6000                           LD->getOffset());
6001   }
6002
6003   RLI.Chain = LD->getChain();
6004   RLI.MPI = LD->getPointerInfo();
6005   RLI.IsInvariant = LD->isInvariant();
6006   RLI.Alignment = LD->getAlignment();
6007   RLI.AAInfo = LD->getAAInfo();
6008   RLI.Ranges = LD->getRanges();
6009
6010   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6011   return true;
6012 }
6013
6014 // Given the head of the old chain, ResChain, insert a token factor containing
6015 // it and NewResChain, and make users of ResChain now be users of that token
6016 // factor.
6017 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6018                                         SDValue NewResChain,
6019                                         SelectionDAG &DAG) const {
6020   if (!ResChain)
6021     return;
6022
6023   SDLoc dl(NewResChain);
6024
6025   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6026                            NewResChain, DAG.getUNDEF(MVT::Other));
6027   assert(TF.getNode() != NewResChain.getNode() &&
6028          "A new TF really is required here");
6029
6030   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6031   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6032 }
6033
6034 /// \brief Custom lowers integer to floating point conversions to use
6035 /// the direct move instructions available in ISA 2.07 to avoid the
6036 /// need for load/store combinations.
6037 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6038                                                     SelectionDAG &DAG,
6039                                                     SDLoc dl) const {
6040   assert((Op.getValueType() == MVT::f32 ||
6041           Op.getValueType() == MVT::f64) &&
6042          "Invalid floating point type as target of conversion");
6043   assert(Subtarget.hasFPCVT() &&
6044          "Int to FP conversions with direct moves require FPCVT");
6045   SDValue FP;
6046   SDValue Src = Op.getOperand(0);
6047   bool SinglePrec = Op.getValueType() == MVT::f32;
6048   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6049   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6050   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6051                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6052
6053   if (WordInt) {
6054     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6055                      dl, MVT::f64, Src);
6056     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6057   }
6058   else {
6059     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6060     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6061   }
6062
6063   return FP;
6064 }
6065
6066 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6067                                           SelectionDAG &DAG) const {
6068   SDLoc dl(Op);
6069
6070   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6071     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6072       return SDValue();
6073
6074     SDValue Value = Op.getOperand(0);
6075     // The values are now known to be -1 (false) or 1 (true). To convert this
6076     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6077     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6078     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6079   
6080     SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6081     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6082                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6083   
6084     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6085
6086     if (Op.getValueType() != MVT::v4f64)
6087       Value = DAG.getNode(ISD::FP_ROUND, dl,
6088                           Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6089     return Value;
6090   }
6091
6092   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6093   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6094     return SDValue();
6095
6096   if (Op.getOperand(0).getValueType() == MVT::i1)
6097     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6098                        DAG.getConstantFP(1.0, Op.getValueType()),
6099                        DAG.getConstantFP(0.0, Op.getValueType()));
6100
6101   // If we have direct moves, we can do all the conversion, skip the store/load
6102   // however, without FPCVT we can't do most conversions.
6103   if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6104     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6105
6106   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6107          "UINT_TO_FP is supported only with FPCVT");
6108
6109   // If we have FCFIDS, then use it when converting to single-precision.
6110   // Otherwise, convert to double-precision and then round.
6111   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6112                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6113                                                             : PPCISD::FCFIDS)
6114                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6115                                                             : PPCISD::FCFID);
6116   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6117                   ? MVT::f32
6118                   : MVT::f64;
6119
6120   if (Op.getOperand(0).getValueType() == MVT::i64) {
6121     SDValue SINT = Op.getOperand(0);
6122     // When converting to single-precision, we actually need to convert
6123     // to double-precision first and then round to single-precision.
6124     // To avoid double-rounding effects during that operation, we have
6125     // to prepare the input operand.  Bits that might be truncated when
6126     // converting to double-precision are replaced by a bit that won't
6127     // be lost at this stage, but is below the single-precision rounding
6128     // position.
6129     //
6130     // However, if -enable-unsafe-fp-math is in effect, accept double
6131     // rounding to avoid the extra overhead.
6132     if (Op.getValueType() == MVT::f32 &&
6133         !Subtarget.hasFPCVT() &&
6134         !DAG.getTarget().Options.UnsafeFPMath) {
6135
6136       // Twiddle input to make sure the low 11 bits are zero.  (If this
6137       // is the case, we are guaranteed the value will fit into the 53 bit
6138       // mantissa of an IEEE double-precision value without rounding.)
6139       // If any of those low 11 bits were not zero originally, make sure
6140       // bit 12 (value 2048) is set instead, so that the final rounding
6141       // to single-precision gets the correct result.
6142       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6143                                   SINT, DAG.getConstant(2047, MVT::i64));
6144       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6145                           Round, DAG.getConstant(2047, MVT::i64));
6146       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6147       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6148                           Round, DAG.getConstant(-2048, MVT::i64));
6149
6150       // However, we cannot use that value unconditionally: if the magnitude
6151       // of the input value is small, the bit-twiddling we did above might
6152       // end up visibly changing the output.  Fortunately, in that case, we
6153       // don't need to twiddle bits since the original input will convert
6154       // exactly to double-precision floating-point already.  Therefore,
6155       // construct a conditional to use the original value if the top 11
6156       // bits are all sign-bit copies, and use the rounded value computed
6157       // above otherwise.
6158       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6159                                  SINT, DAG.getConstant(53, MVT::i32));
6160       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6161                          Cond, DAG.getConstant(1, MVT::i64));
6162       Cond = DAG.getSetCC(dl, MVT::i32,
6163                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6164
6165       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6166     }
6167
6168     ReuseLoadInfo RLI;
6169     SDValue Bits;
6170
6171     MachineFunction &MF = DAG.getMachineFunction();
6172     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6173       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6174                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6175                          RLI.Ranges);
6176       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6177     } else if (Subtarget.hasLFIWAX() &&
6178                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6179       MachineMemOperand *MMO =
6180         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6181                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6182       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6183       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6184                                      DAG.getVTList(MVT::f64, MVT::Other),
6185                                      Ops, MVT::i32, MMO);
6186       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6187     } else if (Subtarget.hasFPCVT() &&
6188                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6189       MachineMemOperand *MMO =
6190         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6191                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6192       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6193       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6194                                      DAG.getVTList(MVT::f64, MVT::Other),
6195                                      Ops, MVT::i32, MMO);
6196       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6197     } else if (((Subtarget.hasLFIWAX() &&
6198                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6199                 (Subtarget.hasFPCVT() &&
6200                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6201                SINT.getOperand(0).getValueType() == MVT::i32) {
6202       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6203       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6204
6205       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6206       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6207
6208       SDValue Store =
6209         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6210                      MachinePointerInfo::getFixedStack(FrameIdx),
6211                      false, false, 0);
6212
6213       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6214              "Expected an i32 store");
6215
6216       RLI.Ptr = FIdx;
6217       RLI.Chain = Store;
6218       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6219       RLI.Alignment = 4;
6220
6221       MachineMemOperand *MMO =
6222         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6223                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6224       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6225       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6226                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6227                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6228                                      Ops, MVT::i32, MMO);
6229     } else
6230       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6231
6232     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6233
6234     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6235       FP = DAG.getNode(ISD::FP_ROUND, dl,
6236                        MVT::f32, FP, DAG.getIntPtrConstant(0));
6237     return FP;
6238   }
6239
6240   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6241          "Unhandled INT_TO_FP type in custom expander!");
6242   // Since we only generate this in 64-bit mode, we can take advantage of
6243   // 64-bit registers.  In particular, sign extend the input value into the
6244   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6245   // then lfd it and fcfid it.
6246   MachineFunction &MF = DAG.getMachineFunction();
6247   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6248   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6249
6250   SDValue Ld;
6251   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6252     ReuseLoadInfo RLI;
6253     bool ReusingLoad;
6254     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6255                                             DAG))) {
6256       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6257       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6258
6259       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6260                                    MachinePointerInfo::getFixedStack(FrameIdx),
6261                                    false, false, 0);
6262
6263       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6264              "Expected an i32 store");
6265
6266       RLI.Ptr = FIdx;
6267       RLI.Chain = Store;
6268       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6269       RLI.Alignment = 4;
6270     }
6271
6272     MachineMemOperand *MMO =
6273       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6274                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6275     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6276     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6277                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6278                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6279                                  Ops, MVT::i32, MMO);
6280     if (ReusingLoad)
6281       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6282   } else {
6283     assert(Subtarget.isPPC64() &&
6284            "i32->FP without LFIWAX supported only on PPC64");
6285
6286     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6287     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6288
6289     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6290                                 Op.getOperand(0));
6291
6292     // STD the extended value into the stack slot.
6293     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6294                                  MachinePointerInfo::getFixedStack(FrameIdx),
6295                                  false, false, 0);
6296
6297     // Load the value as a double.
6298     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6299                      MachinePointerInfo::getFixedStack(FrameIdx),
6300                      false, false, false, 0);
6301   }
6302
6303   // FCFID it and return it.
6304   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6305   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6306     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6307   return FP;
6308 }
6309
6310 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6311                                             SelectionDAG &DAG) const {
6312   SDLoc dl(Op);
6313   /*
6314    The rounding mode is in bits 30:31 of FPSR, and has the following
6315    settings:
6316      00 Round to nearest
6317      01 Round to 0
6318      10 Round to +inf
6319      11 Round to -inf
6320
6321   FLT_ROUNDS, on the other hand, expects the following:
6322     -1 Undefined
6323      0 Round to 0
6324      1 Round to nearest
6325      2 Round to +inf
6326      3 Round to -inf
6327
6328   To perform the conversion, we do:
6329     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6330   */
6331
6332   MachineFunction &MF = DAG.getMachineFunction();
6333   EVT VT = Op.getValueType();
6334   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6335
6336   // Save FP Control Word to register
6337   EVT NodeTys[] = {
6338     MVT::f64,    // return register
6339     MVT::Glue    // unused in this context
6340   };
6341   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6342
6343   // Save FP register to stack slot
6344   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6345   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6346   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6347                                StackSlot, MachinePointerInfo(), false, false,0);
6348
6349   // Load FP Control Word from low 32 bits of stack slot.
6350   SDValue Four = DAG.getConstant(4, PtrVT);
6351   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6352   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6353                             false, false, false, 0);
6354
6355   // Transform as necessary
6356   SDValue CWD1 =
6357     DAG.getNode(ISD::AND, dl, MVT::i32,
6358                 CWD, DAG.getConstant(3, MVT::i32));
6359   SDValue CWD2 =
6360     DAG.getNode(ISD::SRL, dl, MVT::i32,
6361                 DAG.getNode(ISD::AND, dl, MVT::i32,
6362                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6363                                         CWD, DAG.getConstant(3, MVT::i32)),
6364                             DAG.getConstant(3, MVT::i32)),
6365                 DAG.getConstant(1, MVT::i32));
6366
6367   SDValue RetVal =
6368     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6369
6370   return DAG.getNode((VT.getSizeInBits() < 16 ?
6371                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6372 }
6373
6374 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6375   EVT VT = Op.getValueType();
6376   unsigned BitWidth = VT.getSizeInBits();
6377   SDLoc dl(Op);
6378   assert(Op.getNumOperands() == 3 &&
6379          VT == Op.getOperand(1).getValueType() &&
6380          "Unexpected SHL!");
6381
6382   // Expand into a bunch of logical ops.  Note that these ops
6383   // depend on the PPC behavior for oversized shift amounts.
6384   SDValue Lo = Op.getOperand(0);
6385   SDValue Hi = Op.getOperand(1);
6386   SDValue Amt = Op.getOperand(2);
6387   EVT AmtVT = Amt.getValueType();
6388
6389   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6390                              DAG.getConstant(BitWidth, AmtVT), Amt);
6391   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6392   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6393   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6394   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6395                              DAG.getConstant(-BitWidth, AmtVT));
6396   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6397   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6398   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6399   SDValue OutOps[] = { OutLo, OutHi };
6400   return DAG.getMergeValues(OutOps, dl);
6401 }
6402
6403 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6404   EVT VT = Op.getValueType();
6405   SDLoc dl(Op);
6406   unsigned BitWidth = VT.getSizeInBits();
6407   assert(Op.getNumOperands() == 3 &&
6408          VT == Op.getOperand(1).getValueType() &&
6409          "Unexpected SRL!");
6410
6411   // Expand into a bunch of logical ops.  Note that these ops
6412   // depend on the PPC behavior for oversized shift amounts.
6413   SDValue Lo = Op.getOperand(0);
6414   SDValue Hi = Op.getOperand(1);
6415   SDValue Amt = Op.getOperand(2);
6416   EVT AmtVT = Amt.getValueType();
6417
6418   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6419                              DAG.getConstant(BitWidth, AmtVT), Amt);
6420   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6421   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6422   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6423   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6424                              DAG.getConstant(-BitWidth, AmtVT));
6425   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6426   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6427   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6428   SDValue OutOps[] = { OutLo, OutHi };
6429   return DAG.getMergeValues(OutOps, dl);
6430 }
6431
6432 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6433   SDLoc dl(Op);
6434   EVT VT = Op.getValueType();
6435   unsigned BitWidth = VT.getSizeInBits();
6436   assert(Op.getNumOperands() == 3 &&
6437          VT == Op.getOperand(1).getValueType() &&
6438          "Unexpected SRA!");
6439
6440   // Expand into a bunch of logical ops, followed by a select_cc.
6441   SDValue Lo = Op.getOperand(0);
6442   SDValue Hi = Op.getOperand(1);
6443   SDValue Amt = Op.getOperand(2);
6444   EVT AmtVT = Amt.getValueType();
6445
6446   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6447                              DAG.getConstant(BitWidth, AmtVT), Amt);
6448   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6449   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6450   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6451   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6452                              DAG.getConstant(-BitWidth, AmtVT));
6453   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6454   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6455   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6456                                   Tmp4, Tmp6, ISD::SETLE);
6457   SDValue OutOps[] = { OutLo, OutHi };
6458   return DAG.getMergeValues(OutOps, dl);
6459 }
6460
6461 //===----------------------------------------------------------------------===//
6462 // Vector related lowering.
6463 //
6464
6465 /// BuildSplatI - Build a canonical splati of Val with an element size of
6466 /// SplatSize.  Cast the result to VT.
6467 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6468                              SelectionDAG &DAG, SDLoc dl) {
6469   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6470
6471   static const MVT VTys[] = { // canonical VT to use for each size.
6472     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6473   };
6474
6475   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6476
6477   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6478   if (Val == -1)
6479     SplatSize = 1;
6480
6481   EVT CanonicalVT = VTys[SplatSize-1];
6482
6483   // Build a canonical splat for this value.
6484   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6485   SmallVector<SDValue, 8> Ops;
6486   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6487   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6488   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6489 }
6490
6491 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6492 /// specified intrinsic ID.
6493 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6494                                 SelectionDAG &DAG, SDLoc dl,
6495                                 EVT DestVT = MVT::Other) {
6496   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6497   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6498                      DAG.getConstant(IID, MVT::i32), Op);
6499 }
6500
6501 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6502 /// specified intrinsic ID.
6503 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6504                                 SelectionDAG &DAG, SDLoc dl,
6505                                 EVT DestVT = MVT::Other) {
6506   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6507   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6508                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6509 }
6510
6511 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6512 /// specified intrinsic ID.
6513 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6514                                 SDValue Op2, SelectionDAG &DAG,
6515                                 SDLoc dl, EVT DestVT = MVT::Other) {
6516   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6517   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6518                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6519 }
6520
6521
6522 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6523 /// amount.  The result has the specified value type.
6524 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6525                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6526   // Force LHS/RHS to be the right type.
6527   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6528   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6529
6530   int Ops[16];
6531   for (unsigned i = 0; i != 16; ++i)
6532     Ops[i] = i + Amt;
6533   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6534   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6535 }
6536
6537 // If this is a case we can't handle, return null and let the default
6538 // expansion code take care of it.  If we CAN select this case, and if it
6539 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6540 // this case more efficiently than a constant pool load, lower it to the
6541 // sequence of ops that should be used.
6542 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6543                                              SelectionDAG &DAG) const {
6544   SDLoc dl(Op);
6545   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6546   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6547
6548   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6549     // We first build an i32 vector, load it into a QPX register,
6550     // then convert it to a floating-point vector and compare it
6551     // to a zero vector to get the boolean result.
6552     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6553     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6554     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6555     EVT PtrVT = getPointerTy();
6556     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6557
6558     assert(BVN->getNumOperands() == 4 &&
6559       "BUILD_VECTOR for v4i1 does not have 4 operands");
6560
6561     bool IsConst = true;
6562     for (unsigned i = 0; i < 4; ++i) {
6563       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6564       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6565         IsConst = false;
6566         break;
6567       }
6568     }
6569
6570     if (IsConst) {
6571       Constant *One =
6572         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6573       Constant *NegOne =
6574         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6575
6576       SmallVector<Constant*, 4> CV(4, NegOne);
6577       for (unsigned i = 0; i < 4; ++i) {
6578         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6579           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6580         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6581                    getConstantIntValue()->isZero())
6582           continue;
6583         else
6584           CV[i] = One;
6585       }
6586
6587       Constant *CP = ConstantVector::get(CV);
6588       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6589                       16 /* alignment */);
6590  
6591       SmallVector<SDValue, 2> Ops;
6592       Ops.push_back(DAG.getEntryNode());
6593       Ops.push_back(CPIdx);
6594
6595       SmallVector<EVT, 2> ValueVTs;
6596       ValueVTs.push_back(MVT::v4i1);
6597       ValueVTs.push_back(MVT::Other); // chain
6598       SDVTList VTs = DAG.getVTList(ValueVTs);
6599
6600       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6601         dl, VTs, Ops, MVT::v4f32,
6602         MachinePointerInfo::getConstantPool());
6603     }
6604
6605     SmallVector<SDValue, 4> Stores;
6606     for (unsigned i = 0; i < 4; ++i) {
6607       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6608
6609       unsigned Offset = 4*i;
6610       SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6611       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6612
6613       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6614       if (StoreSize > 4) {
6615         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6616                                            BVN->getOperand(i), Idx,
6617                                            PtrInfo.getWithOffset(Offset),
6618                                            MVT::i32, false, false, 0));
6619       } else {
6620         SDValue StoreValue = BVN->getOperand(i);
6621         if (StoreSize < 4)
6622           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6623
6624         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6625                                       StoreValue, Idx,
6626                                       PtrInfo.getWithOffset(Offset),
6627                                       false, false, 0));
6628       }
6629     }
6630
6631     SDValue StoreChain;
6632     if (!Stores.empty())
6633       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6634     else
6635       StoreChain = DAG.getEntryNode();
6636
6637     // Now load from v4i32 into the QPX register; this will extend it to
6638     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6639     // is typed as v4f64 because the QPX register integer states are not
6640     // explicitly represented.
6641
6642     SmallVector<SDValue, 2> Ops;
6643     Ops.push_back(StoreChain);
6644     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6645     Ops.push_back(FIdx);
6646
6647     SmallVector<EVT, 2> ValueVTs;
6648     ValueVTs.push_back(MVT::v4f64);
6649     ValueVTs.push_back(MVT::Other); // chain
6650     SDVTList VTs = DAG.getVTList(ValueVTs);
6651
6652     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6653       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6654     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6655       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6656       LoadedVect);
6657
6658     SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6659     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6660                           FPZeros, FPZeros, FPZeros, FPZeros);
6661
6662     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6663   }
6664
6665   // All other QPX vectors are handled by generic code.
6666   if (Subtarget.hasQPX())
6667     return SDValue();
6668
6669   // Check if this is a splat of a constant value.
6670   APInt APSplatBits, APSplatUndef;
6671   unsigned SplatBitSize;
6672   bool HasAnyUndefs;
6673   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6674                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6675       SplatBitSize > 32)
6676     return SDValue();
6677
6678   unsigned SplatBits = APSplatBits.getZExtValue();
6679   unsigned SplatUndef = APSplatUndef.getZExtValue();
6680   unsigned SplatSize = SplatBitSize / 8;
6681
6682   // First, handle single instruction cases.
6683
6684   // All zeros?
6685   if (SplatBits == 0) {
6686     // Canonicalize all zero vectors to be v4i32.
6687     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6688       SDValue Z = DAG.getConstant(0, MVT::i32);
6689       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6690       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6691     }
6692     return Op;
6693   }
6694
6695   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6696   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6697                     (32-SplatBitSize));
6698   if (SextVal >= -16 && SextVal <= 15)
6699     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6700
6701
6702   // Two instruction sequences.
6703
6704   // If this value is in the range [-32,30] and is even, use:
6705   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6706   // If this value is in the range [17,31] and is odd, use:
6707   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6708   // If this value is in the range [-31,-17] and is odd, use:
6709   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6710   // Note the last two are three-instruction sequences.
6711   if (SextVal >= -32 && SextVal <= 31) {
6712     // To avoid having these optimizations undone by constant folding,
6713     // we convert to a pseudo that will be expanded later into one of
6714     // the above forms.
6715     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6716     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6717               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6718     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6719     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6720     if (VT == Op.getValueType())
6721       return RetVal;
6722     else
6723       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6724   }
6725
6726   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6727   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6728   // for fneg/fabs.
6729   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6730     // Make -1 and vspltisw -1:
6731     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6732
6733     // Make the VSLW intrinsic, computing 0x8000_0000.
6734     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6735                                    OnesV, DAG, dl);
6736
6737     // xor by OnesV to invert it.
6738     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6739     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6740   }
6741
6742   // Check to see if this is a wide variety of vsplti*, binop self cases.
6743   static const signed char SplatCsts[] = {
6744     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6745     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6746   };
6747
6748   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6749     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6750     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6751     int i = SplatCsts[idx];
6752
6753     // Figure out what shift amount will be used by altivec if shifted by i in
6754     // this splat size.
6755     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6756
6757     // vsplti + shl self.
6758     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6759       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6760       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6761         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6762         Intrinsic::ppc_altivec_vslw
6763       };
6764       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6765       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6766     }
6767
6768     // vsplti + srl self.
6769     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6770       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6771       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6772         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6773         Intrinsic::ppc_altivec_vsrw
6774       };
6775       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6776       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6777     }
6778
6779     // vsplti + sra self.
6780     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6781       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6782       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6783         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6784         Intrinsic::ppc_altivec_vsraw
6785       };
6786       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6787       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6788     }
6789
6790     // vsplti + rol self.
6791     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6792                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6793       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6794       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6795         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6796         Intrinsic::ppc_altivec_vrlw
6797       };
6798       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6799       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6800     }
6801
6802     // t = vsplti c, result = vsldoi t, t, 1
6803     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6804       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6805       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6806     }
6807     // t = vsplti c, result = vsldoi t, t, 2
6808     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6809       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6810       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6811     }
6812     // t = vsplti c, result = vsldoi t, t, 3
6813     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6814       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6815       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6816     }
6817   }
6818
6819   return SDValue();
6820 }
6821
6822 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6823 /// the specified operations to build the shuffle.
6824 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6825                                       SDValue RHS, SelectionDAG &DAG,
6826                                       SDLoc dl) {
6827   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6828   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6829   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6830
6831   enum {
6832     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6833     OP_VMRGHW,
6834     OP_VMRGLW,
6835     OP_VSPLTISW0,
6836     OP_VSPLTISW1,
6837     OP_VSPLTISW2,
6838     OP_VSPLTISW3,
6839     OP_VSLDOI4,
6840     OP_VSLDOI8,
6841     OP_VSLDOI12
6842   };
6843
6844   if (OpNum == OP_COPY) {
6845     if (LHSID == (1*9+2)*9+3) return LHS;
6846     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6847     return RHS;
6848   }
6849
6850   SDValue OpLHS, OpRHS;
6851   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6852   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6853
6854   int ShufIdxs[16];
6855   switch (OpNum) {
6856   default: llvm_unreachable("Unknown i32 permute!");
6857   case OP_VMRGHW:
6858     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6859     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6860     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6861     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6862     break;
6863   case OP_VMRGLW:
6864     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6865     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6866     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6867     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6868     break;
6869   case OP_VSPLTISW0:
6870     for (unsigned i = 0; i != 16; ++i)
6871       ShufIdxs[i] = (i&3)+0;
6872     break;
6873   case OP_VSPLTISW1:
6874     for (unsigned i = 0; i != 16; ++i)
6875       ShufIdxs[i] = (i&3)+4;
6876     break;
6877   case OP_VSPLTISW2:
6878     for (unsigned i = 0; i != 16; ++i)
6879       ShufIdxs[i] = (i&3)+8;
6880     break;
6881   case OP_VSPLTISW3:
6882     for (unsigned i = 0; i != 16; ++i)
6883       ShufIdxs[i] = (i&3)+12;
6884     break;
6885   case OP_VSLDOI4:
6886     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6887   case OP_VSLDOI8:
6888     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6889   case OP_VSLDOI12:
6890     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6891   }
6892   EVT VT = OpLHS.getValueType();
6893   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6894   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6895   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6896   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6897 }
6898
6899 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6900 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6901 /// return the code it can be lowered into.  Worst case, it can always be
6902 /// lowered into a vperm.
6903 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6904                                                SelectionDAG &DAG) const {
6905   SDLoc dl(Op);
6906   SDValue V1 = Op.getOperand(0);
6907   SDValue V2 = Op.getOperand(1);
6908   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6909   EVT VT = Op.getValueType();
6910   bool isLittleEndian = Subtarget.isLittleEndian();
6911
6912   if (Subtarget.hasQPX()) {
6913     if (VT.getVectorNumElements() != 4)
6914       return SDValue();
6915
6916     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6917
6918     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6919     if (AlignIdx != -1) {
6920       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6921                          DAG.getConstant(AlignIdx, MVT::i32));
6922     } else if (SVOp->isSplat()) {
6923       int SplatIdx = SVOp->getSplatIndex();
6924       if (SplatIdx >= 4) {
6925         std::swap(V1, V2);
6926         SplatIdx -= 4;
6927       }
6928
6929       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6930       // nothing to do.
6931
6932       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6933                          DAG.getConstant(SplatIdx, MVT::i32));
6934     }
6935
6936     // Lower this into a qvgpci/qvfperm pair.
6937
6938     // Compute the qvgpci literal
6939     unsigned idx = 0;
6940     for (unsigned i = 0; i < 4; ++i) {
6941       int m = SVOp->getMaskElt(i);
6942       unsigned mm = m >= 0 ? (unsigned) m : i;
6943       idx |= mm << (3-i)*3;
6944     }
6945
6946     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6947                              DAG.getConstant(idx, MVT::i32));
6948     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6949   }
6950
6951   // Cases that are handled by instructions that take permute immediates
6952   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6953   // selected by the instruction selector.
6954   if (V2.getOpcode() == ISD::UNDEF) {
6955     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6956         PPC::isSplatShuffleMask(SVOp, 2) ||
6957         PPC::isSplatShuffleMask(SVOp, 4) ||
6958         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6959         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6960         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6961         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6962         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6963         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6964         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6965         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6966         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6967       return Op;
6968     }
6969   }
6970
6971   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6972   // and produce a fixed permutation.  If any of these match, do not lower to
6973   // VPERM.
6974   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6975   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6976       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6977       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6978       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6979       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6980       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6981       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6982       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6983       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6984     return Op;
6985
6986   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6987   // perfect shuffle table to emit an optimal matching sequence.
6988   ArrayRef<int> PermMask = SVOp->getMask();
6989
6990   unsigned PFIndexes[4];
6991   bool isFourElementShuffle = true;
6992   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6993     unsigned EltNo = 8;   // Start out undef.
6994     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6995       if (PermMask[i*4+j] < 0)
6996         continue;   // Undef, ignore it.
6997
6998       unsigned ByteSource = PermMask[i*4+j];
6999       if ((ByteSource & 3) != j) {
7000         isFourElementShuffle = false;
7001         break;
7002       }
7003
7004       if (EltNo == 8) {
7005         EltNo = ByteSource/4;
7006       } else if (EltNo != ByteSource/4) {
7007         isFourElementShuffle = false;
7008         break;
7009       }
7010     }
7011     PFIndexes[i] = EltNo;
7012   }
7013
7014   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7015   // perfect shuffle vector to determine if it is cost effective to do this as
7016   // discrete instructions, or whether we should use a vperm.
7017   // For now, we skip this for little endian until such time as we have a
7018   // little-endian perfect shuffle table.
7019   if (isFourElementShuffle && !isLittleEndian) {
7020     // Compute the index in the perfect shuffle table.
7021     unsigned PFTableIndex =
7022       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7023
7024     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7025     unsigned Cost  = (PFEntry >> 30);
7026
7027     // Determining when to avoid vperm is tricky.  Many things affect the cost
7028     // of vperm, particularly how many times the perm mask needs to be computed.
7029     // For example, if the perm mask can be hoisted out of a loop or is already
7030     // used (perhaps because there are multiple permutes with the same shuffle
7031     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7032     // the loop requires an extra register.
7033     //
7034     // As a compromise, we only emit discrete instructions if the shuffle can be
7035     // generated in 3 or fewer operations.  When we have loop information
7036     // available, if this block is within a loop, we should avoid using vperm
7037     // for 3-operation perms and use a constant pool load instead.
7038     if (Cost < 3)
7039       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7040   }
7041
7042   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7043   // vector that will get spilled to the constant pool.
7044   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7045
7046   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7047   // that it is in input element units, not in bytes.  Convert now.
7048
7049   // For little endian, the order of the input vectors is reversed, and
7050   // the permutation mask is complemented with respect to 31.  This is
7051   // necessary to produce proper semantics with the big-endian-biased vperm
7052   // instruction.
7053   EVT EltVT = V1.getValueType().getVectorElementType();
7054   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7055
7056   SmallVector<SDValue, 16> ResultMask;
7057   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7058     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7059
7060     for (unsigned j = 0; j != BytesPerElement; ++j)
7061       if (isLittleEndian)
7062         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7063                                              MVT::i32));
7064       else
7065         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7066                                              MVT::i32));
7067   }
7068
7069   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7070                                   ResultMask);
7071   if (isLittleEndian)
7072     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7073                        V2, V1, VPermMask);
7074   else
7075     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7076                        V1, V2, VPermMask);
7077 }
7078
7079 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7080 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7081 /// information about the intrinsic.
7082 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7083                                   bool &isDot, const PPCSubtarget &Subtarget) {
7084   unsigned IntrinsicID =
7085     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7086   CompareOpc = -1;
7087   isDot = false;
7088   switch (IntrinsicID) {
7089   default: return false;
7090     // Comparison predicates.
7091   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7092   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7093   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7094   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7095   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7096   case Intrinsic::ppc_altivec_vcmpequd_p: 
7097     if (Subtarget.hasP8Altivec()) {
7098       CompareOpc = 199; 
7099       isDot = 1; 
7100     }
7101     else 
7102       return false;
7103
7104     break;
7105   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7106   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7107   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7108   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7109   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7110   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7111     if (Subtarget.hasP8Altivec()) {
7112       CompareOpc = 967; 
7113       isDot = 1; 
7114     }
7115     else 
7116       return false;
7117
7118     break;
7119   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7120   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7121   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7122   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7123     if (Subtarget.hasP8Altivec()) {
7124       CompareOpc = 711; 
7125       isDot = 1; 
7126     }
7127     else 
7128       return false;
7129
7130     break;
7131       
7132     // Normal Comparisons.
7133   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7134   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7135   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7136   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7137   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7138   case Intrinsic::ppc_altivec_vcmpequd:
7139     if (Subtarget.hasP8Altivec()) {
7140       CompareOpc = 199; 
7141       isDot = 0; 
7142     }
7143     else
7144       return false;
7145
7146     break;
7147   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7148   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7149   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7150   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7151   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7152   case Intrinsic::ppc_altivec_vcmpgtsd:   
7153     if (Subtarget.hasP8Altivec()) {
7154       CompareOpc = 967; 
7155       isDot = 0; 
7156     }
7157     else
7158       return false;
7159
7160     break;
7161   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7162   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7163   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7164   case Intrinsic::ppc_altivec_vcmpgtud:   
7165     if (Subtarget.hasP8Altivec()) {
7166       CompareOpc = 711; 
7167       isDot = 0; 
7168     }
7169     else
7170       return false;
7171
7172     break;
7173   }
7174   return true;
7175 }
7176
7177 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7178 /// lower, do it, otherwise return null.
7179 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7180                                                    SelectionDAG &DAG) const {
7181   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7182   // opcode number of the comparison.
7183   SDLoc dl(Op);
7184   int CompareOpc;
7185   bool isDot;
7186   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7187     return SDValue();    // Don't custom lower most intrinsics.
7188
7189   // If this is a non-dot comparison, make the VCMP node and we are done.
7190   if (!isDot) {
7191     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7192                               Op.getOperand(1), Op.getOperand(2),
7193                               DAG.getConstant(CompareOpc, MVT::i32));
7194     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7195   }
7196
7197   // Create the PPCISD altivec 'dot' comparison node.
7198   SDValue Ops[] = {
7199     Op.getOperand(2),  // LHS
7200     Op.getOperand(3),  // RHS
7201     DAG.getConstant(CompareOpc, MVT::i32)
7202   };
7203   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7204   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7205
7206   // Now that we have the comparison, emit a copy from the CR to a GPR.
7207   // This is flagged to the above dot comparison.
7208   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7209                                 DAG.getRegister(PPC::CR6, MVT::i32),
7210                                 CompNode.getValue(1));
7211
7212   // Unpack the result based on how the target uses it.
7213   unsigned BitNo;   // Bit # of CR6.
7214   bool InvertBit;   // Invert result?
7215   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7216   default:  // Can't happen, don't crash on invalid number though.
7217   case 0:   // Return the value of the EQ bit of CR6.
7218     BitNo = 0; InvertBit = false;
7219     break;
7220   case 1:   // Return the inverted value of the EQ bit of CR6.
7221     BitNo = 0; InvertBit = true;
7222     break;
7223   case 2:   // Return the value of the LT bit of CR6.
7224     BitNo = 2; InvertBit = false;
7225     break;
7226   case 3:   // Return the inverted value of the LT bit of CR6.
7227     BitNo = 2; InvertBit = true;
7228     break;
7229   }
7230
7231   // Shift the bit into the low position.
7232   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7233                       DAG.getConstant(8-(3-BitNo), MVT::i32));
7234   // Isolate the bit.
7235   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7236                       DAG.getConstant(1, MVT::i32));
7237
7238   // If we are supposed to, toggle the bit.
7239   if (InvertBit)
7240     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7241                         DAG.getConstant(1, MVT::i32));
7242   return Flags;
7243 }
7244
7245 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7246                                                   SelectionDAG &DAG) const {
7247   SDLoc dl(Op);
7248   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7249   // instructions), but for smaller types, we need to first extend up to v2i32
7250   // before doing going farther.
7251   if (Op.getValueType() == MVT::v2i64) {
7252     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7253     if (ExtVT != MVT::v2i32) {
7254       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7255       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7256                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7257                                         ExtVT.getVectorElementType(), 4)));
7258       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7259       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7260                        DAG.getValueType(MVT::v2i32));
7261     }
7262
7263     return Op;
7264   }
7265
7266   return SDValue();
7267 }
7268
7269 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7270                                                    SelectionDAG &DAG) const {
7271   SDLoc dl(Op);
7272   // Create a stack slot that is 16-byte aligned.
7273   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7274   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7275   EVT PtrVT = getPointerTy();
7276   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7277
7278   // Store the input value into Value#0 of the stack slot.
7279   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7280                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7281                                false, false, 0);
7282   // Load it out.
7283   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7284                      false, false, false, 0);
7285 }
7286
7287 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7288                                                    SelectionDAG &DAG) const {
7289   SDLoc dl(Op);
7290   SDNode *N = Op.getNode();
7291
7292   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7293          "Unknown extract_vector_elt type");
7294
7295   SDValue Value = N->getOperand(0);
7296
7297   // The first part of this is like the store lowering except that we don't
7298   // need to track the chain.
7299
7300   // The values are now known to be -1 (false) or 1 (true). To convert this
7301   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7302   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7303   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7304
7305   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7306   // understand how to form the extending load.
7307   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7308   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7309                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7310
7311   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7312
7313   // Now convert to an integer and store.
7314   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7315     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7316     Value);
7317
7318   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7319   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7320   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7321   EVT PtrVT = getPointerTy();
7322   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7323
7324   SDValue StoreChain = DAG.getEntryNode();
7325   SmallVector<SDValue, 2> Ops;
7326   Ops.push_back(StoreChain);
7327   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7328   Ops.push_back(Value);
7329   Ops.push_back(FIdx);
7330
7331   SmallVector<EVT, 2> ValueVTs;
7332   ValueVTs.push_back(MVT::Other); // chain
7333   SDVTList VTs = DAG.getVTList(ValueVTs);
7334
7335   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7336     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7337
7338   // Extract the value requested.
7339   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7340   SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7341   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7342
7343   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7344                                PtrInfo.getWithOffset(Offset),
7345                                false, false, false, 0);
7346
7347   if (!Subtarget.useCRBits())
7348     return IntVal;
7349
7350   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7351 }
7352
7353 /// Lowering for QPX v4i1 loads
7354 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7355                                            SelectionDAG &DAG) const {
7356   SDLoc dl(Op);
7357   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7358   SDValue LoadChain = LN->getChain();
7359   SDValue BasePtr = LN->getBasePtr();
7360
7361   if (Op.getValueType() == MVT::v4f64 ||
7362       Op.getValueType() == MVT::v4f32) {
7363     EVT MemVT = LN->getMemoryVT();
7364     unsigned Alignment = LN->getAlignment();
7365
7366     // If this load is properly aligned, then it is legal.
7367     if (Alignment >= MemVT.getStoreSize())
7368       return Op;
7369
7370     EVT ScalarVT = Op.getValueType().getScalarType(),
7371         ScalarMemVT = MemVT.getScalarType();
7372     unsigned Stride = ScalarMemVT.getStoreSize();
7373
7374     SmallVector<SDValue, 8> Vals, LoadChains;
7375     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7376       SDValue Load;
7377       if (ScalarVT != ScalarMemVT)
7378         Load =
7379           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7380                          BasePtr,
7381                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7382                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7383                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7384                          LN->getAAInfo());
7385       else
7386         Load =
7387           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7388                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7389                        LN->isVolatile(), LN->isNonTemporal(),
7390                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7391                        LN->getAAInfo());
7392
7393       if (Idx == 0 && LN->isIndexed()) {
7394         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7395                "Unknown addressing mode on vector load");
7396         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7397                                   LN->getAddressingMode());
7398       }
7399
7400       Vals.push_back(Load);
7401       LoadChains.push_back(Load.getValue(1));
7402
7403       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7404                             DAG.getConstant(Stride, BasePtr.getValueType()));
7405     }
7406
7407     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7408     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7409                                    Op.getValueType(), Vals);
7410
7411     if (LN->isIndexed()) {
7412       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7413       return DAG.getMergeValues(RetOps, dl);
7414     }
7415
7416     SDValue RetOps[] = { Value, TF };
7417     return DAG.getMergeValues(RetOps, dl);
7418   }
7419
7420   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7421   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7422
7423   // To lower v4i1 from a byte array, we load the byte elements of the
7424   // vector and then reuse the BUILD_VECTOR logic.
7425
7426   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7427   for (unsigned i = 0; i < 4; ++i) {
7428     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7429     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7430
7431     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7432                         dl, MVT::i32, LoadChain, Idx,
7433                         LN->getPointerInfo().getWithOffset(i),
7434                         MVT::i8 /* memory type */,
7435                         LN->isVolatile(), LN->isNonTemporal(),
7436                         LN->isInvariant(),
7437                         1 /* alignment */, LN->getAAInfo()));
7438     VectElmtChains.push_back(VectElmts[i].getValue(1));
7439   }
7440
7441   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7442   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7443
7444   SDValue RVals[] = { Value, LoadChain };
7445   return DAG.getMergeValues(RVals, dl);
7446 }
7447
7448 /// Lowering for QPX v4i1 stores
7449 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7450                                             SelectionDAG &DAG) const {
7451   SDLoc dl(Op);
7452   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7453   SDValue StoreChain = SN->getChain();
7454   SDValue BasePtr = SN->getBasePtr();
7455   SDValue Value = SN->getValue();
7456
7457   if (Value.getValueType() == MVT::v4f64 ||
7458       Value.getValueType() == MVT::v4f32) {
7459     EVT MemVT = SN->getMemoryVT();
7460     unsigned Alignment = SN->getAlignment();
7461
7462     // If this store is properly aligned, then it is legal.
7463     if (Alignment >= MemVT.getStoreSize())
7464       return Op;
7465
7466     EVT ScalarVT = Value.getValueType().getScalarType(),
7467         ScalarMemVT = MemVT.getScalarType();
7468     unsigned Stride = ScalarMemVT.getStoreSize();
7469
7470     SmallVector<SDValue, 8> Stores;
7471     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7472       SDValue Ex =
7473         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7474                     DAG.getConstant(Idx, getVectorIdxTy()));
7475       SDValue Store;
7476       if (ScalarVT != ScalarMemVT)
7477         Store =
7478           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7479                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7480                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7481                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7482       else
7483         Store =
7484           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7485                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7486                        SN->isVolatile(), SN->isNonTemporal(),
7487                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7488
7489       if (Idx == 0 && SN->isIndexed()) {
7490         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7491                "Unknown addressing mode on vector store");
7492         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7493                                     SN->getAddressingMode());
7494       }
7495
7496       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7497                             DAG.getConstant(Stride, BasePtr.getValueType()));
7498       Stores.push_back(Store);
7499     }
7500
7501     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7502
7503     if (SN->isIndexed()) {
7504       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7505       return DAG.getMergeValues(RetOps, dl);
7506     }
7507
7508     return TF;
7509   }
7510
7511   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7512   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7513
7514   // The values are now known to be -1 (false) or 1 (true). To convert this
7515   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7516   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7517   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7518
7519   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7520   // understand how to form the extending load.
7521   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7522   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7523                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7524
7525   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7526
7527   // Now convert to an integer and store.
7528   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7529     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7530     Value);
7531
7532   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7533   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7534   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7535   EVT PtrVT = getPointerTy();
7536   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7537
7538   SmallVector<SDValue, 2> Ops;
7539   Ops.push_back(StoreChain);
7540   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7541   Ops.push_back(Value);
7542   Ops.push_back(FIdx);
7543
7544   SmallVector<EVT, 2> ValueVTs;
7545   ValueVTs.push_back(MVT::Other); // chain
7546   SDVTList VTs = DAG.getVTList(ValueVTs);
7547
7548   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7549     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7550
7551   // Move data into the byte array.
7552   SmallVector<SDValue, 4> Loads, LoadChains;
7553   for (unsigned i = 0; i < 4; ++i) {
7554     unsigned Offset = 4*i;
7555     SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7556     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7557
7558     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7559                                    PtrInfo.getWithOffset(Offset),
7560                                    false, false, false, 0));
7561     LoadChains.push_back(Loads[i].getValue(1));
7562   }
7563
7564   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7565
7566   SmallVector<SDValue, 4> Stores;
7567   for (unsigned i = 0; i < 4; ++i) {
7568     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7569     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7570
7571     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7572                                        SN->getPointerInfo().getWithOffset(i),
7573                                        MVT::i8 /* memory type */,
7574                                        SN->isNonTemporal(), SN->isVolatile(), 
7575                                        1 /* alignment */, SN->getAAInfo()));
7576   }
7577
7578   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7579
7580   return StoreChain;
7581 }
7582
7583 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7584   SDLoc dl(Op);
7585   if (Op.getValueType() == MVT::v4i32) {
7586     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7587
7588     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7589     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7590
7591     SDValue RHSSwap =   // = vrlw RHS, 16
7592       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7593
7594     // Shrinkify inputs to v8i16.
7595     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7596     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7597     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7598
7599     // Low parts multiplied together, generating 32-bit results (we ignore the
7600     // top parts).
7601     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7602                                         LHS, RHS, DAG, dl, MVT::v4i32);
7603
7604     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7605                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7606     // Shift the high parts up 16 bits.
7607     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7608                               Neg16, DAG, dl);
7609     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7610   } else if (Op.getValueType() == MVT::v8i16) {
7611     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7612
7613     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7614
7615     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7616                             LHS, RHS, Zero, DAG, dl);
7617   } else if (Op.getValueType() == MVT::v16i8) {
7618     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7619     bool isLittleEndian = Subtarget.isLittleEndian();
7620
7621     // Multiply the even 8-bit parts, producing 16-bit sums.
7622     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7623                                            LHS, RHS, DAG, dl, MVT::v8i16);
7624     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7625
7626     // Multiply the odd 8-bit parts, producing 16-bit sums.
7627     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7628                                           LHS, RHS, DAG, dl, MVT::v8i16);
7629     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7630
7631     // Merge the results together.  Because vmuleub and vmuloub are
7632     // instructions with a big-endian bias, we must reverse the
7633     // element numbering and reverse the meaning of "odd" and "even"
7634     // when generating little endian code.
7635     int Ops[16];
7636     for (unsigned i = 0; i != 8; ++i) {
7637       if (isLittleEndian) {
7638         Ops[i*2  ] = 2*i;
7639         Ops[i*2+1] = 2*i+16;
7640       } else {
7641         Ops[i*2  ] = 2*i+1;
7642         Ops[i*2+1] = 2*i+1+16;
7643       }
7644     }
7645     if (isLittleEndian)
7646       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7647     else
7648       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7649   } else {
7650     llvm_unreachable("Unknown mul to lower!");
7651   }
7652 }
7653
7654 /// LowerOperation - Provide custom lowering hooks for some operations.
7655 ///
7656 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7657   switch (Op.getOpcode()) {
7658   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7659   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7660   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7661   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7662   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7663   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7664   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7665   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7666   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7667   case ISD::VASTART:
7668     return LowerVASTART(Op, DAG, Subtarget);
7669
7670   case ISD::VAARG:
7671     return LowerVAARG(Op, DAG, Subtarget);
7672
7673   case ISD::VACOPY:
7674     return LowerVACOPY(Op, DAG, Subtarget);
7675
7676   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7677   case ISD::DYNAMIC_STACKALLOC:
7678     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7679
7680   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7681   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7682
7683   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7684   case ISD::STORE:              return LowerSTORE(Op, DAG);
7685   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7686   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7687   case ISD::FP_TO_UINT:
7688   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7689                                                       SDLoc(Op));
7690   case ISD::UINT_TO_FP:
7691   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7692   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7693
7694   // Lower 64-bit shifts.
7695   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7696   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7697   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7698
7699   // Vector-related lowering.
7700   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7701   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7702   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7703   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7704   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7705   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7706   case ISD::MUL:                return LowerMUL(Op, DAG);
7707
7708   // For counter-based loop handling.
7709   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7710
7711   // Frame & Return address.
7712   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7713   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7714   }
7715 }
7716
7717 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7718                                            SmallVectorImpl<SDValue>&Results,
7719                                            SelectionDAG &DAG) const {
7720   SDLoc dl(N);
7721   switch (N->getOpcode()) {
7722   default:
7723     llvm_unreachable("Do not know how to custom type legalize this operation!");
7724   case ISD::READCYCLECOUNTER: {
7725     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7726     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7727
7728     Results.push_back(RTB);
7729     Results.push_back(RTB.getValue(1));
7730     Results.push_back(RTB.getValue(2));
7731     break;
7732   }
7733   case ISD::INTRINSIC_W_CHAIN: {
7734     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7735         Intrinsic::ppc_is_decremented_ctr_nonzero)
7736       break;
7737
7738     assert(N->getValueType(0) == MVT::i1 &&
7739            "Unexpected result type for CTR decrement intrinsic");
7740     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7741     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7742     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7743                                  N->getOperand(1)); 
7744
7745     Results.push_back(NewInt);
7746     Results.push_back(NewInt.getValue(1));
7747     break;
7748   }
7749   case ISD::VAARG: {
7750     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7751       return;
7752
7753     EVT VT = N->getValueType(0);
7754
7755     if (VT == MVT::i64) {
7756       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7757
7758       Results.push_back(NewNode);
7759       Results.push_back(NewNode.getValue(1));
7760     }
7761     return;
7762   }
7763   case ISD::FP_ROUND_INREG: {
7764     assert(N->getValueType(0) == MVT::ppcf128);
7765     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7766     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7767                              MVT::f64, N->getOperand(0),
7768                              DAG.getIntPtrConstant(0));
7769     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7770                              MVT::f64, N->getOperand(0),
7771                              DAG.getIntPtrConstant(1));
7772
7773     // Add the two halves of the long double in round-to-zero mode.
7774     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7775
7776     // We know the low half is about to be thrown away, so just use something
7777     // convenient.
7778     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7779                                 FPreg, FPreg));
7780     return;
7781   }
7782   case ISD::FP_TO_SINT:
7783   case ISD::FP_TO_UINT:
7784     // LowerFP_TO_INT() can only handle f32 and f64.
7785     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7786       return;
7787     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7788     return;
7789   }
7790 }
7791
7792
7793 //===----------------------------------------------------------------------===//
7794 //  Other Lowering Code
7795 //===----------------------------------------------------------------------===//
7796
7797 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7798   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7799   Function *Func = Intrinsic::getDeclaration(M, Id);
7800   return Builder.CreateCall(Func);
7801 }
7802
7803 // The mappings for emitLeading/TrailingFence is taken from
7804 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7805 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7806                                          AtomicOrdering Ord, bool IsStore,
7807                                          bool IsLoad) const {
7808   if (Ord == SequentiallyConsistent)
7809     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7810   else if (isAtLeastRelease(Ord))
7811     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7812   else
7813     return nullptr;
7814 }
7815
7816 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7817                                           AtomicOrdering Ord, bool IsStore,
7818                                           bool IsLoad) const {
7819   if (IsLoad && isAtLeastAcquire(Ord))
7820     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7821   // FIXME: this is too conservative, a dependent branch + isync is enough.
7822   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7823   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7824   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7825   else
7826     return nullptr;
7827 }
7828
7829 MachineBasicBlock *
7830 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7831                                     unsigned AtomicSize,
7832                                     unsigned BinOpcode) const {
7833   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7834   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7835
7836   auto LoadMnemonic = PPC::LDARX;
7837   auto StoreMnemonic = PPC::STDCX;
7838   switch (AtomicSize) {
7839   default:
7840     llvm_unreachable("Unexpected size of atomic entity");
7841   case 1:
7842     LoadMnemonic = PPC::LBARX;
7843     StoreMnemonic = PPC::STBCX;
7844     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7845     break;
7846   case 2:
7847     LoadMnemonic = PPC::LHARX;
7848     StoreMnemonic = PPC::STHCX;
7849     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7850     break;
7851   case 4:
7852     LoadMnemonic = PPC::LWARX;
7853     StoreMnemonic = PPC::STWCX;
7854     break;
7855   case 8:
7856     LoadMnemonic = PPC::LDARX;
7857     StoreMnemonic = PPC::STDCX;
7858     break;
7859   }
7860
7861   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7862   MachineFunction *F = BB->getParent();
7863   MachineFunction::iterator It = BB;
7864   ++It;
7865
7866   unsigned dest = MI->getOperand(0).getReg();
7867   unsigned ptrA = MI->getOperand(1).getReg();
7868   unsigned ptrB = MI->getOperand(2).getReg();
7869   unsigned incr = MI->getOperand(3).getReg();
7870   DebugLoc dl = MI->getDebugLoc();
7871
7872   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7873   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7874   F->insert(It, loopMBB);
7875   F->insert(It, exitMBB);
7876   exitMBB->splice(exitMBB->begin(), BB,
7877                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7878   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7879
7880   MachineRegisterInfo &RegInfo = F->getRegInfo();
7881   unsigned TmpReg = (!BinOpcode) ? incr :
7882     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7883                                            : &PPC::GPRCRegClass);
7884
7885   //  thisMBB:
7886   //   ...
7887   //   fallthrough --> loopMBB
7888   BB->addSuccessor(loopMBB);
7889
7890   //  loopMBB:
7891   //   l[wd]arx dest, ptr
7892   //   add r0, dest, incr
7893   //   st[wd]cx. r0, ptr
7894   //   bne- loopMBB
7895   //   fallthrough --> exitMBB
7896   BB = loopMBB;
7897   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7898     .addReg(ptrA).addReg(ptrB);
7899   if (BinOpcode)
7900     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7901   BuildMI(BB, dl, TII->get(StoreMnemonic))
7902     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7903   BuildMI(BB, dl, TII->get(PPC::BCC))
7904     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7905   BB->addSuccessor(loopMBB);
7906   BB->addSuccessor(exitMBB);
7907
7908   //  exitMBB:
7909   //   ...
7910   BB = exitMBB;
7911   return BB;
7912 }
7913
7914 MachineBasicBlock *
7915 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7916                                             MachineBasicBlock *BB,
7917                                             bool is8bit,    // operation
7918                                             unsigned BinOpcode) const {
7919   // If we support part-word atomic mnemonics, just use them
7920   if (Subtarget.hasPartwordAtomics())
7921     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7922
7923   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7924   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7925   // In 64 bit mode we have to use 64 bits for addresses, even though the
7926   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
7927   // registers without caring whether they're 32 or 64, but here we're
7928   // doing actual arithmetic on the addresses.
7929   bool is64bit = Subtarget.isPPC64();
7930   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7931
7932   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7933   MachineFunction *F = BB->getParent();
7934   MachineFunction::iterator It = BB;
7935   ++It;
7936
7937   unsigned dest = MI->getOperand(0).getReg();
7938   unsigned ptrA = MI->getOperand(1).getReg();
7939   unsigned ptrB = MI->getOperand(2).getReg();
7940   unsigned incr = MI->getOperand(3).getReg();
7941   DebugLoc dl = MI->getDebugLoc();
7942
7943   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7944   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7945   F->insert(It, loopMBB);
7946   F->insert(It, exitMBB);
7947   exitMBB->splice(exitMBB->begin(), BB,
7948                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7949   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7950
7951   MachineRegisterInfo &RegInfo = F->getRegInfo();
7952   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7953                                           : &PPC::GPRCRegClass;
7954   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7955   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7956   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7957   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7958   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7959   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7960   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7961   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7962   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7963   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7964   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7965   unsigned Ptr1Reg;
7966   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7967
7968   //  thisMBB:
7969   //   ...
7970   //   fallthrough --> loopMBB
7971   BB->addSuccessor(loopMBB);
7972
7973   // The 4-byte load must be aligned, while a char or short may be
7974   // anywhere in the word.  Hence all this nasty bookkeeping code.
7975   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7976   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7977   //   xori shift, shift1, 24 [16]
7978   //   rlwinm ptr, ptr1, 0, 0, 29
7979   //   slw incr2, incr, shift
7980   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7981   //   slw mask, mask2, shift
7982   //  loopMBB:
7983   //   lwarx tmpDest, ptr
7984   //   add tmp, tmpDest, incr2
7985   //   andc tmp2, tmpDest, mask
7986   //   and tmp3, tmp, mask
7987   //   or tmp4, tmp3, tmp2
7988   //   stwcx. tmp4, ptr
7989   //   bne- loopMBB
7990   //   fallthrough --> exitMBB
7991   //   srw dest, tmpDest, shift
7992   if (ptrA != ZeroReg) {
7993     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7994     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7995       .addReg(ptrA).addReg(ptrB);
7996   } else {
7997     Ptr1Reg = ptrB;
7998   }
7999   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8000       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8001   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8002       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8003   if (is64bit)
8004     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8005       .addReg(Ptr1Reg).addImm(0).addImm(61);
8006   else
8007     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8008       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8009   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8010       .addReg(incr).addReg(ShiftReg);
8011   if (is8bit)
8012     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8013   else {
8014     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8015     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8016   }
8017   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8018       .addReg(Mask2Reg).addReg(ShiftReg);
8019
8020   BB = loopMBB;
8021   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8022     .addReg(ZeroReg).addReg(PtrReg);
8023   if (BinOpcode)
8024     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8025       .addReg(Incr2Reg).addReg(TmpDestReg);
8026   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8027     .addReg(TmpDestReg).addReg(MaskReg);
8028   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8029     .addReg(TmpReg).addReg(MaskReg);
8030   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8031     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8032   BuildMI(BB, dl, TII->get(PPC::STWCX))
8033     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8034   BuildMI(BB, dl, TII->get(PPC::BCC))
8035     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8036   BB->addSuccessor(loopMBB);
8037   BB->addSuccessor(exitMBB);
8038
8039   //  exitMBB:
8040   //   ...
8041   BB = exitMBB;
8042   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8043     .addReg(ShiftReg);
8044   return BB;
8045 }
8046
8047 llvm::MachineBasicBlock*
8048 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8049                                     MachineBasicBlock *MBB) const {
8050   DebugLoc DL = MI->getDebugLoc();
8051   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8052
8053   MachineFunction *MF = MBB->getParent();
8054   MachineRegisterInfo &MRI = MF->getRegInfo();
8055
8056   const BasicBlock *BB = MBB->getBasicBlock();
8057   MachineFunction::iterator I = MBB;
8058   ++I;
8059
8060   // Memory Reference
8061   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8062   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8063
8064   unsigned DstReg = MI->getOperand(0).getReg();
8065   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8066   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8067   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8068   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8069
8070   MVT PVT = getPointerTy();
8071   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8072          "Invalid Pointer Size!");
8073   // For v = setjmp(buf), we generate
8074   //
8075   // thisMBB:
8076   //  SjLjSetup mainMBB
8077   //  bl mainMBB
8078   //  v_restore = 1
8079   //  b sinkMBB
8080   //
8081   // mainMBB:
8082   //  buf[LabelOffset] = LR
8083   //  v_main = 0
8084   //
8085   // sinkMBB:
8086   //  v = phi(main, restore)
8087   //
8088
8089   MachineBasicBlock *thisMBB = MBB;
8090   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8091   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8092   MF->insert(I, mainMBB);
8093   MF->insert(I, sinkMBB);
8094
8095   MachineInstrBuilder MIB;
8096
8097   // Transfer the remainder of BB and its successor edges to sinkMBB.
8098   sinkMBB->splice(sinkMBB->begin(), MBB,
8099                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8100   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8101
8102   // Note that the structure of the jmp_buf used here is not compatible
8103   // with that used by libc, and is not designed to be. Specifically, it
8104   // stores only those 'reserved' registers that LLVM does not otherwise
8105   // understand how to spill. Also, by convention, by the time this
8106   // intrinsic is called, Clang has already stored the frame address in the
8107   // first slot of the buffer and stack address in the third. Following the
8108   // X86 target code, we'll store the jump address in the second slot. We also
8109   // need to save the TOC pointer (R2) to handle jumps between shared
8110   // libraries, and that will be stored in the fourth slot. The thread
8111   // identifier (R13) is not affected.
8112
8113   // thisMBB:
8114   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8115   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8116   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8117
8118   // Prepare IP either in reg.
8119   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8120   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8121   unsigned BufReg = MI->getOperand(1).getReg();
8122
8123   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8124     setUsesTOCBasePtr(*MBB->getParent());
8125     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8126             .addReg(PPC::X2)
8127             .addImm(TOCOffset)
8128             .addReg(BufReg);
8129     MIB.setMemRefs(MMOBegin, MMOEnd);
8130   }
8131
8132   // Naked functions never have a base pointer, and so we use r1. For all
8133   // other functions, this decision must be delayed until during PEI.
8134   unsigned BaseReg;
8135   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8136     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8137   else
8138     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8139
8140   MIB = BuildMI(*thisMBB, MI, DL,
8141                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8142             .addReg(BaseReg)
8143             .addImm(BPOffset)
8144             .addReg(BufReg);
8145   MIB.setMemRefs(MMOBegin, MMOEnd);
8146
8147   // Setup
8148   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8149   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8150   MIB.addRegMask(TRI->getNoPreservedMask());
8151
8152   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8153
8154   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8155           .addMBB(mainMBB);
8156   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8157
8158   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8159   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8160
8161   // mainMBB:
8162   //  mainDstReg = 0
8163   MIB =
8164       BuildMI(mainMBB, DL,
8165               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8166
8167   // Store IP
8168   if (Subtarget.isPPC64()) {
8169     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8170             .addReg(LabelReg)
8171             .addImm(LabelOffset)
8172             .addReg(BufReg);
8173   } else {
8174     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8175             .addReg(LabelReg)
8176             .addImm(LabelOffset)
8177             .addReg(BufReg);
8178   }
8179
8180   MIB.setMemRefs(MMOBegin, MMOEnd);
8181
8182   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8183   mainMBB->addSuccessor(sinkMBB);
8184
8185   // sinkMBB:
8186   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8187           TII->get(PPC::PHI), DstReg)
8188     .addReg(mainDstReg).addMBB(mainMBB)
8189     .addReg(restoreDstReg).addMBB(thisMBB);
8190
8191   MI->eraseFromParent();
8192   return sinkMBB;
8193 }
8194
8195 MachineBasicBlock *
8196 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8197                                      MachineBasicBlock *MBB) const {
8198   DebugLoc DL = MI->getDebugLoc();
8199   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8200
8201   MachineFunction *MF = MBB->getParent();
8202   MachineRegisterInfo &MRI = MF->getRegInfo();
8203
8204   // Memory Reference
8205   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8206   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8207
8208   MVT PVT = getPointerTy();
8209   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8210          "Invalid Pointer Size!");
8211
8212   const TargetRegisterClass *RC =
8213     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8214   unsigned Tmp = MRI.createVirtualRegister(RC);
8215   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8216   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8217   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8218   unsigned BP =
8219       (PVT == MVT::i64)
8220           ? PPC::X30
8221           : (Subtarget.isSVR4ABI() &&
8222                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8223                  ? PPC::R29
8224                  : PPC::R30);
8225
8226   MachineInstrBuilder MIB;
8227
8228   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8229   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8230   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8231   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8232
8233   unsigned BufReg = MI->getOperand(0).getReg();
8234
8235   // Reload FP (the jumped-to function may not have had a
8236   // frame pointer, and if so, then its r31 will be restored
8237   // as necessary).
8238   if (PVT == MVT::i64) {
8239     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8240             .addImm(0)
8241             .addReg(BufReg);
8242   } else {
8243     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8244             .addImm(0)
8245             .addReg(BufReg);
8246   }
8247   MIB.setMemRefs(MMOBegin, MMOEnd);
8248
8249   // Reload IP
8250   if (PVT == MVT::i64) {
8251     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8252             .addImm(LabelOffset)
8253             .addReg(BufReg);
8254   } else {
8255     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8256             .addImm(LabelOffset)
8257             .addReg(BufReg);
8258   }
8259   MIB.setMemRefs(MMOBegin, MMOEnd);
8260
8261   // Reload SP
8262   if (PVT == MVT::i64) {
8263     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8264             .addImm(SPOffset)
8265             .addReg(BufReg);
8266   } else {
8267     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8268             .addImm(SPOffset)
8269             .addReg(BufReg);
8270   }
8271   MIB.setMemRefs(MMOBegin, MMOEnd);
8272
8273   // Reload BP
8274   if (PVT == MVT::i64) {
8275     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8276             .addImm(BPOffset)
8277             .addReg(BufReg);
8278   } else {
8279     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8280             .addImm(BPOffset)
8281             .addReg(BufReg);
8282   }
8283   MIB.setMemRefs(MMOBegin, MMOEnd);
8284
8285   // Reload TOC
8286   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8287     setUsesTOCBasePtr(*MBB->getParent());
8288     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8289             .addImm(TOCOffset)
8290             .addReg(BufReg);
8291
8292     MIB.setMemRefs(MMOBegin, MMOEnd);
8293   }
8294
8295   // Jump
8296   BuildMI(*MBB, MI, DL,
8297           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8298   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8299
8300   MI->eraseFromParent();
8301   return MBB;
8302 }
8303
8304 MachineBasicBlock *
8305 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8306                                                MachineBasicBlock *BB) const {
8307   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8308       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8309     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8310         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8311       // Call lowering should have added an r2 operand to indicate a dependence
8312       // on the TOC base pointer value. It can't however, because there is no
8313       // way to mark the dependence as implicit there, and so the stackmap code
8314       // will confuse it with a regular operand. Instead, add the dependence
8315       // here.
8316       setUsesTOCBasePtr(*BB->getParent());
8317       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8318     }
8319
8320     return emitPatchPoint(MI, BB);
8321   }
8322
8323   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8324       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8325     return emitEHSjLjSetJmp(MI, BB);
8326   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8327              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8328     return emitEHSjLjLongJmp(MI, BB);
8329   }
8330
8331   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8332
8333   // To "insert" these instructions we actually have to insert their
8334   // control-flow patterns.
8335   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8336   MachineFunction::iterator It = BB;
8337   ++It;
8338
8339   MachineFunction *F = BB->getParent();
8340
8341   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8342                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8343                               MI->getOpcode() == PPC::SELECT_I4 ||
8344                               MI->getOpcode() == PPC::SELECT_I8)) {
8345     SmallVector<MachineOperand, 2> Cond;
8346     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8347         MI->getOpcode() == PPC::SELECT_CC_I8)
8348       Cond.push_back(MI->getOperand(4));
8349     else
8350       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8351     Cond.push_back(MI->getOperand(1));
8352
8353     DebugLoc dl = MI->getDebugLoc();
8354     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8355                       Cond, MI->getOperand(2).getReg(),
8356                       MI->getOperand(3).getReg());
8357   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8358              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8359              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8360              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8361              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8362              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8363              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8364              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8365              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8366              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8367              MI->getOpcode() == PPC::SELECT_I4 ||
8368              MI->getOpcode() == PPC::SELECT_I8 ||
8369              MI->getOpcode() == PPC::SELECT_F4 ||
8370              MI->getOpcode() == PPC::SELECT_F8 ||
8371              MI->getOpcode() == PPC::SELECT_QFRC ||
8372              MI->getOpcode() == PPC::SELECT_QSRC ||
8373              MI->getOpcode() == PPC::SELECT_QBRC ||
8374              MI->getOpcode() == PPC::SELECT_VRRC ||
8375              MI->getOpcode() == PPC::SELECT_VSFRC ||
8376              MI->getOpcode() == PPC::SELECT_VSRC) {
8377     // The incoming instruction knows the destination vreg to set, the
8378     // condition code register to branch on, the true/false values to
8379     // select between, and a branch opcode to use.
8380
8381     //  thisMBB:
8382     //  ...
8383     //   TrueVal = ...
8384     //   cmpTY ccX, r1, r2
8385     //   bCC copy1MBB
8386     //   fallthrough --> copy0MBB
8387     MachineBasicBlock *thisMBB = BB;
8388     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8389     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8390     DebugLoc dl = MI->getDebugLoc();
8391     F->insert(It, copy0MBB);
8392     F->insert(It, sinkMBB);
8393
8394     // Transfer the remainder of BB and its successor edges to sinkMBB.
8395     sinkMBB->splice(sinkMBB->begin(), BB,
8396                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8397     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8398
8399     // Next, add the true and fallthrough blocks as its successors.
8400     BB->addSuccessor(copy0MBB);
8401     BB->addSuccessor(sinkMBB);
8402
8403     if (MI->getOpcode() == PPC::SELECT_I4 ||
8404         MI->getOpcode() == PPC::SELECT_I8 ||
8405         MI->getOpcode() == PPC::SELECT_F4 ||
8406         MI->getOpcode() == PPC::SELECT_F8 ||
8407         MI->getOpcode() == PPC::SELECT_QFRC ||
8408         MI->getOpcode() == PPC::SELECT_QSRC ||
8409         MI->getOpcode() == PPC::SELECT_QBRC ||
8410         MI->getOpcode() == PPC::SELECT_VRRC ||
8411         MI->getOpcode() == PPC::SELECT_VSFRC ||
8412         MI->getOpcode() == PPC::SELECT_VSRC) {
8413       BuildMI(BB, dl, TII->get(PPC::BC))
8414         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8415     } else {
8416       unsigned SelectPred = MI->getOperand(4).getImm();
8417       BuildMI(BB, dl, TII->get(PPC::BCC))
8418         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8419     }
8420
8421     //  copy0MBB:
8422     //   %FalseValue = ...
8423     //   # fallthrough to sinkMBB
8424     BB = copy0MBB;
8425
8426     // Update machine-CFG edges
8427     BB->addSuccessor(sinkMBB);
8428
8429     //  sinkMBB:
8430     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8431     //  ...
8432     BB = sinkMBB;
8433     BuildMI(*BB, BB->begin(), dl,
8434             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8435       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8436       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8437   } else if (MI->getOpcode() == PPC::ReadTB) {
8438     // To read the 64-bit time-base register on a 32-bit target, we read the
8439     // two halves. Should the counter have wrapped while it was being read, we
8440     // need to try again.
8441     // ...
8442     // readLoop:
8443     // mfspr Rx,TBU # load from TBU
8444     // mfspr Ry,TB  # load from TB
8445     // mfspr Rz,TBU # load from TBU
8446     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8447     // bne readLoop   # branch if they're not equal
8448     // ...
8449
8450     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8451     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8452     DebugLoc dl = MI->getDebugLoc();
8453     F->insert(It, readMBB);
8454     F->insert(It, sinkMBB);
8455
8456     // Transfer the remainder of BB and its successor edges to sinkMBB.
8457     sinkMBB->splice(sinkMBB->begin(), BB,
8458                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8459     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8460
8461     BB->addSuccessor(readMBB);
8462     BB = readMBB;
8463
8464     MachineRegisterInfo &RegInfo = F->getRegInfo();
8465     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8466     unsigned LoReg = MI->getOperand(0).getReg();
8467     unsigned HiReg = MI->getOperand(1).getReg();
8468
8469     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8470     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8471     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8472
8473     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8474
8475     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8476       .addReg(HiReg).addReg(ReadAgainReg);
8477     BuildMI(BB, dl, TII->get(PPC::BCC))
8478       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8479
8480     BB->addSuccessor(readMBB);
8481     BB->addSuccessor(sinkMBB);
8482   }
8483   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8484     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8485   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8486     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8487   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8488     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8489   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8490     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8491
8492   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8493     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8494   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8495     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8496   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8497     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8498   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8499     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8500
8501   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8502     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8503   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8504     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8505   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8506     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8507   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8508     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8509
8510   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8511     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8512   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8513     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8514   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8515     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8516   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8517     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8518
8519   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8520     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8521   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8522     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8523   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8524     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8525   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8526     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8527
8528   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8529     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8530   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8531     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8532   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8533     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8534   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8535     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8536
8537   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8538     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8539   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8540     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8541   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8542     BB = EmitAtomicBinary(MI, BB, 4, 0);
8543   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8544     BB = EmitAtomicBinary(MI, BB, 8, 0);
8545
8546   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8547            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8548            (Subtarget.hasPartwordAtomics() &&
8549             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8550            (Subtarget.hasPartwordAtomics() &&
8551             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8552     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8553
8554     auto LoadMnemonic = PPC::LDARX;
8555     auto StoreMnemonic = PPC::STDCX;
8556     switch(MI->getOpcode()) {
8557     default:
8558       llvm_unreachable("Compare and swap of unknown size");
8559     case PPC::ATOMIC_CMP_SWAP_I8:
8560       LoadMnemonic = PPC::LBARX;
8561       StoreMnemonic = PPC::STBCX;
8562       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8563       break;
8564     case PPC::ATOMIC_CMP_SWAP_I16:
8565       LoadMnemonic = PPC::LHARX;
8566       StoreMnemonic = PPC::STHCX;
8567       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8568       break;
8569     case PPC::ATOMIC_CMP_SWAP_I32:
8570       LoadMnemonic = PPC::LWARX;
8571       StoreMnemonic = PPC::STWCX;
8572       break;
8573     case PPC::ATOMIC_CMP_SWAP_I64:
8574       LoadMnemonic = PPC::LDARX;
8575       StoreMnemonic = PPC::STDCX;
8576       break;
8577     }
8578     unsigned dest   = MI->getOperand(0).getReg();
8579     unsigned ptrA   = MI->getOperand(1).getReg();
8580     unsigned ptrB   = MI->getOperand(2).getReg();
8581     unsigned oldval = MI->getOperand(3).getReg();
8582     unsigned newval = MI->getOperand(4).getReg();
8583     DebugLoc dl     = MI->getDebugLoc();
8584
8585     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8586     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8587     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8588     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8589     F->insert(It, loop1MBB);
8590     F->insert(It, loop2MBB);
8591     F->insert(It, midMBB);
8592     F->insert(It, exitMBB);
8593     exitMBB->splice(exitMBB->begin(), BB,
8594                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8595     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8596
8597     //  thisMBB:
8598     //   ...
8599     //   fallthrough --> loopMBB
8600     BB->addSuccessor(loop1MBB);
8601
8602     // loop1MBB:
8603     //   l[bhwd]arx dest, ptr
8604     //   cmp[wd] dest, oldval
8605     //   bne- midMBB
8606     // loop2MBB:
8607     //   st[bhwd]cx. newval, ptr
8608     //   bne- loopMBB
8609     //   b exitBB
8610     // midMBB:
8611     //   st[bhwd]cx. dest, ptr
8612     // exitBB:
8613     BB = loop1MBB;
8614     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8615       .addReg(ptrA).addReg(ptrB);
8616     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8617       .addReg(oldval).addReg(dest);
8618     BuildMI(BB, dl, TII->get(PPC::BCC))
8619       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8620     BB->addSuccessor(loop2MBB);
8621     BB->addSuccessor(midMBB);
8622
8623     BB = loop2MBB;
8624     BuildMI(BB, dl, TII->get(StoreMnemonic))
8625       .addReg(newval).addReg(ptrA).addReg(ptrB);
8626     BuildMI(BB, dl, TII->get(PPC::BCC))
8627       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8628     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8629     BB->addSuccessor(loop1MBB);
8630     BB->addSuccessor(exitMBB);
8631
8632     BB = midMBB;
8633     BuildMI(BB, dl, TII->get(StoreMnemonic))
8634       .addReg(dest).addReg(ptrA).addReg(ptrB);
8635     BB->addSuccessor(exitMBB);
8636
8637     //  exitMBB:
8638     //   ...
8639     BB = exitMBB;
8640   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8641              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8642     // We must use 64-bit registers for addresses when targeting 64-bit,
8643     // since we're actually doing arithmetic on them.  Other registers
8644     // can be 32-bit.
8645     bool is64bit = Subtarget.isPPC64();
8646     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8647
8648     unsigned dest   = MI->getOperand(0).getReg();
8649     unsigned ptrA   = MI->getOperand(1).getReg();
8650     unsigned ptrB   = MI->getOperand(2).getReg();
8651     unsigned oldval = MI->getOperand(3).getReg();
8652     unsigned newval = MI->getOperand(4).getReg();
8653     DebugLoc dl     = MI->getDebugLoc();
8654
8655     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8656     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8657     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8658     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8659     F->insert(It, loop1MBB);
8660     F->insert(It, loop2MBB);
8661     F->insert(It, midMBB);
8662     F->insert(It, exitMBB);
8663     exitMBB->splice(exitMBB->begin(), BB,
8664                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8665     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8666
8667     MachineRegisterInfo &RegInfo = F->getRegInfo();
8668     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8669                                             : &PPC::GPRCRegClass;
8670     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8671     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8672     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8673     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8674     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8675     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8676     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8677     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8678     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8679     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8680     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8681     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8682     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8683     unsigned Ptr1Reg;
8684     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8685     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8686     //  thisMBB:
8687     //   ...
8688     //   fallthrough --> loopMBB
8689     BB->addSuccessor(loop1MBB);
8690
8691     // The 4-byte load must be aligned, while a char or short may be
8692     // anywhere in the word.  Hence all this nasty bookkeeping code.
8693     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8694     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8695     //   xori shift, shift1, 24 [16]
8696     //   rlwinm ptr, ptr1, 0, 0, 29
8697     //   slw newval2, newval, shift
8698     //   slw oldval2, oldval,shift
8699     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8700     //   slw mask, mask2, shift
8701     //   and newval3, newval2, mask
8702     //   and oldval3, oldval2, mask
8703     // loop1MBB:
8704     //   lwarx tmpDest, ptr
8705     //   and tmp, tmpDest, mask
8706     //   cmpw tmp, oldval3
8707     //   bne- midMBB
8708     // loop2MBB:
8709     //   andc tmp2, tmpDest, mask
8710     //   or tmp4, tmp2, newval3
8711     //   stwcx. tmp4, ptr
8712     //   bne- loop1MBB
8713     //   b exitBB
8714     // midMBB:
8715     //   stwcx. tmpDest, ptr
8716     // exitBB:
8717     //   srw dest, tmpDest, shift
8718     if (ptrA != ZeroReg) {
8719       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8720       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8721         .addReg(ptrA).addReg(ptrB);
8722     } else {
8723       Ptr1Reg = ptrB;
8724     }
8725     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8726         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8727     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8728         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8729     if (is64bit)
8730       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8731         .addReg(Ptr1Reg).addImm(0).addImm(61);
8732     else
8733       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8734         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8735     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8736         .addReg(newval).addReg(ShiftReg);
8737     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8738         .addReg(oldval).addReg(ShiftReg);
8739     if (is8bit)
8740       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8741     else {
8742       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8743       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8744         .addReg(Mask3Reg).addImm(65535);
8745     }
8746     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8747         .addReg(Mask2Reg).addReg(ShiftReg);
8748     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8749         .addReg(NewVal2Reg).addReg(MaskReg);
8750     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8751         .addReg(OldVal2Reg).addReg(MaskReg);
8752
8753     BB = loop1MBB;
8754     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8755         .addReg(ZeroReg).addReg(PtrReg);
8756     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8757         .addReg(TmpDestReg).addReg(MaskReg);
8758     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8759         .addReg(TmpReg).addReg(OldVal3Reg);
8760     BuildMI(BB, dl, TII->get(PPC::BCC))
8761         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8762     BB->addSuccessor(loop2MBB);
8763     BB->addSuccessor(midMBB);
8764
8765     BB = loop2MBB;
8766     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8767         .addReg(TmpDestReg).addReg(MaskReg);
8768     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8769         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8770     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8771         .addReg(ZeroReg).addReg(PtrReg);
8772     BuildMI(BB, dl, TII->get(PPC::BCC))
8773       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8774     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8775     BB->addSuccessor(loop1MBB);
8776     BB->addSuccessor(exitMBB);
8777
8778     BB = midMBB;
8779     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8780       .addReg(ZeroReg).addReg(PtrReg);
8781     BB->addSuccessor(exitMBB);
8782
8783     //  exitMBB:
8784     //   ...
8785     BB = exitMBB;
8786     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8787       .addReg(ShiftReg);
8788   } else if (MI->getOpcode() == PPC::FADDrtz) {
8789     // This pseudo performs an FADD with rounding mode temporarily forced
8790     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8791     // is not modeled at the SelectionDAG level.
8792     unsigned Dest = MI->getOperand(0).getReg();
8793     unsigned Src1 = MI->getOperand(1).getReg();
8794     unsigned Src2 = MI->getOperand(2).getReg();
8795     DebugLoc dl   = MI->getDebugLoc();
8796
8797     MachineRegisterInfo &RegInfo = F->getRegInfo();
8798     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8799
8800     // Save FPSCR value.
8801     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8802
8803     // Set rounding mode to round-to-zero.
8804     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8805     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8806
8807     // Perform addition.
8808     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8809
8810     // Restore FPSCR value.
8811     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8812   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8813              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8814              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8815              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8816     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8817                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8818                       PPC::ANDIo8 : PPC::ANDIo;
8819     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8820                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8821
8822     MachineRegisterInfo &RegInfo = F->getRegInfo();
8823     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8824                                                   &PPC::GPRCRegClass :
8825                                                   &PPC::G8RCRegClass);
8826
8827     DebugLoc dl   = MI->getDebugLoc();
8828     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8829       .addReg(MI->getOperand(1).getReg()).addImm(1);
8830     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8831             MI->getOperand(0).getReg())
8832       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8833   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
8834     DebugLoc Dl = MI->getDebugLoc();
8835     MachineRegisterInfo &RegInfo = F->getRegInfo();
8836     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8837     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
8838     return BB;
8839   } else {
8840     llvm_unreachable("Unexpected instr type to insert");
8841   }
8842
8843   MI->eraseFromParent();   // The pseudo instruction is gone now.
8844   return BB;
8845 }
8846
8847 //===----------------------------------------------------------------------===//
8848 // Target Optimization Hooks
8849 //===----------------------------------------------------------------------===//
8850
8851 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8852                                             DAGCombinerInfo &DCI,
8853                                             unsigned &RefinementSteps,
8854                                             bool &UseOneConstNR) const {
8855   EVT VT = Operand.getValueType();
8856   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8857       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8858       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8859       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8860       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8861       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8862     // Convergence is quadratic, so we essentially double the number of digits
8863     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8864     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8865     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8866     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8867     if (VT.getScalarType() == MVT::f64)
8868       ++RefinementSteps;
8869     UseOneConstNR = true;
8870     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8871   }
8872   return SDValue();
8873 }
8874
8875 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8876                                             DAGCombinerInfo &DCI,
8877                                             unsigned &RefinementSteps) const {
8878   EVT VT = Operand.getValueType();
8879   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8880       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8881       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8882       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8883       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8884       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8885     // Convergence is quadratic, so we essentially double the number of digits
8886     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8887     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8888     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8889     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8890     if (VT.getScalarType() == MVT::f64)
8891       ++RefinementSteps;
8892     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8893   }
8894   return SDValue();
8895 }
8896
8897 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8898   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8899   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8900   // enabled for division), this functionality is redundant with the default
8901   // combiner logic (once the division -> reciprocal/multiply transformation
8902   // has taken place). As a result, this matters more for older cores than for
8903   // newer ones.
8904
8905   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8906   // reciprocal if there are two or more FDIVs (for embedded cores with only
8907   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8908   switch (Subtarget.getDarwinDirective()) {
8909   default:
8910     return NumUsers > 2;
8911   case PPC::DIR_440:
8912   case PPC::DIR_A2:
8913   case PPC::DIR_E500mc:
8914   case PPC::DIR_E5500:
8915     return NumUsers > 1;
8916   }
8917 }
8918
8919 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8920                             unsigned Bytes, int Dist,
8921                             SelectionDAG &DAG) {
8922   if (VT.getSizeInBits() / 8 != Bytes)
8923     return false;
8924
8925   SDValue BaseLoc = Base->getBasePtr();
8926   if (Loc.getOpcode() == ISD::FrameIndex) {
8927     if (BaseLoc.getOpcode() != ISD::FrameIndex)
8928       return false;
8929     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8930     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
8931     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8932     int FS  = MFI->getObjectSize(FI);
8933     int BFS = MFI->getObjectSize(BFI);
8934     if (FS != BFS || FS != (int)Bytes) return false;
8935     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8936   }
8937
8938   // Handle X+C
8939   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8940       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8941     return true;
8942
8943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8944   const GlobalValue *GV1 = nullptr;
8945   const GlobalValue *GV2 = nullptr;
8946   int64_t Offset1 = 0;
8947   int64_t Offset2 = 0;
8948   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8949   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8950   if (isGA1 && isGA2 && GV1 == GV2)
8951     return Offset1 == (Offset2 + Dist*Bytes);
8952   return false;
8953 }
8954
8955 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8956 // not enforce equality of the chain operands.
8957 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8958                             unsigned Bytes, int Dist,
8959                             SelectionDAG &DAG) {
8960   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8961     EVT VT = LS->getMemoryVT();
8962     SDValue Loc = LS->getBasePtr();
8963     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8964   }
8965
8966   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8967     EVT VT;
8968     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8969     default: return false;
8970     case Intrinsic::ppc_qpx_qvlfd:
8971     case Intrinsic::ppc_qpx_qvlfda:
8972       VT = MVT::v4f64;
8973       break;
8974     case Intrinsic::ppc_qpx_qvlfs:
8975     case Intrinsic::ppc_qpx_qvlfsa:
8976       VT = MVT::v4f32;
8977       break;
8978     case Intrinsic::ppc_qpx_qvlfcd:
8979     case Intrinsic::ppc_qpx_qvlfcda:
8980       VT = MVT::v2f64;
8981       break;
8982     case Intrinsic::ppc_qpx_qvlfcs:
8983     case Intrinsic::ppc_qpx_qvlfcsa:
8984       VT = MVT::v2f32;
8985       break;
8986     case Intrinsic::ppc_qpx_qvlfiwa:
8987     case Intrinsic::ppc_qpx_qvlfiwz:
8988     case Intrinsic::ppc_altivec_lvx:
8989     case Intrinsic::ppc_altivec_lvxl:
8990     case Intrinsic::ppc_vsx_lxvw4x:
8991       VT = MVT::v4i32;
8992       break;
8993     case Intrinsic::ppc_vsx_lxvd2x:
8994       VT = MVT::v2f64;
8995       break;
8996     case Intrinsic::ppc_altivec_lvebx:
8997       VT = MVT::i8;
8998       break;
8999     case Intrinsic::ppc_altivec_lvehx:
9000       VT = MVT::i16;
9001       break;
9002     case Intrinsic::ppc_altivec_lvewx:
9003       VT = MVT::i32;
9004       break;
9005     }
9006
9007     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9008   }
9009
9010   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9011     EVT VT;
9012     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9013     default: return false;
9014     case Intrinsic::ppc_qpx_qvstfd:
9015     case Intrinsic::ppc_qpx_qvstfda:
9016       VT = MVT::v4f64;
9017       break;
9018     case Intrinsic::ppc_qpx_qvstfs:
9019     case Intrinsic::ppc_qpx_qvstfsa:
9020       VT = MVT::v4f32;
9021       break;
9022     case Intrinsic::ppc_qpx_qvstfcd:
9023     case Intrinsic::ppc_qpx_qvstfcda:
9024       VT = MVT::v2f64;
9025       break;
9026     case Intrinsic::ppc_qpx_qvstfcs:
9027     case Intrinsic::ppc_qpx_qvstfcsa:
9028       VT = MVT::v2f32;
9029       break;
9030     case Intrinsic::ppc_qpx_qvstfiw:
9031     case Intrinsic::ppc_qpx_qvstfiwa:
9032     case Intrinsic::ppc_altivec_stvx:
9033     case Intrinsic::ppc_altivec_stvxl:
9034     case Intrinsic::ppc_vsx_stxvw4x:
9035       VT = MVT::v4i32;
9036       break;
9037     case Intrinsic::ppc_vsx_stxvd2x:
9038       VT = MVT::v2f64;
9039       break;
9040     case Intrinsic::ppc_altivec_stvebx:
9041       VT = MVT::i8;
9042       break;
9043     case Intrinsic::ppc_altivec_stvehx:
9044       VT = MVT::i16;
9045       break;
9046     case Intrinsic::ppc_altivec_stvewx:
9047       VT = MVT::i32;
9048       break;
9049     }
9050
9051     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9052   }
9053
9054   return false;
9055 }
9056
9057 // Return true is there is a nearyby consecutive load to the one provided
9058 // (regardless of alignment). We search up and down the chain, looking though
9059 // token factors and other loads (but nothing else). As a result, a true result
9060 // indicates that it is safe to create a new consecutive load adjacent to the
9061 // load provided.
9062 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9063   SDValue Chain = LD->getChain();
9064   EVT VT = LD->getMemoryVT();
9065
9066   SmallSet<SDNode *, 16> LoadRoots;
9067   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9068   SmallSet<SDNode *, 16> Visited;
9069
9070   // First, search up the chain, branching to follow all token-factor operands.
9071   // If we find a consecutive load, then we're done, otherwise, record all
9072   // nodes just above the top-level loads and token factors.
9073   while (!Queue.empty()) {
9074     SDNode *ChainNext = Queue.pop_back_val();
9075     if (!Visited.insert(ChainNext).second)
9076       continue;
9077
9078     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9079       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9080         return true;
9081
9082       if (!Visited.count(ChainLD->getChain().getNode()))
9083         Queue.push_back(ChainLD->getChain().getNode());
9084     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9085       for (const SDUse &O : ChainNext->ops())
9086         if (!Visited.count(O.getNode()))
9087           Queue.push_back(O.getNode());
9088     } else
9089       LoadRoots.insert(ChainNext);
9090   }
9091
9092   // Second, search down the chain, starting from the top-level nodes recorded
9093   // in the first phase. These top-level nodes are the nodes just above all
9094   // loads and token factors. Starting with their uses, recursively look though
9095   // all loads (just the chain uses) and token factors to find a consecutive
9096   // load.
9097   Visited.clear();
9098   Queue.clear();
9099
9100   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9101        IE = LoadRoots.end(); I != IE; ++I) {
9102     Queue.push_back(*I);
9103        
9104     while (!Queue.empty()) {
9105       SDNode *LoadRoot = Queue.pop_back_val();
9106       if (!Visited.insert(LoadRoot).second)
9107         continue;
9108
9109       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9110         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9111           return true;
9112
9113       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9114            UE = LoadRoot->use_end(); UI != UE; ++UI)
9115         if (((isa<MemSDNode>(*UI) &&
9116             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9117             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9118           Queue.push_back(*UI);
9119     }
9120   }
9121
9122   return false;
9123 }
9124
9125 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9126                                                   DAGCombinerInfo &DCI) const {
9127   SelectionDAG &DAG = DCI.DAG;
9128   SDLoc dl(N);
9129
9130   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9131   // If we're tracking CR bits, we need to be careful that we don't have:
9132   //   trunc(binary-ops(zext(x), zext(y)))
9133   // or
9134   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9135   // such that we're unnecessarily moving things into GPRs when it would be
9136   // better to keep them in CR bits.
9137
9138   // Note that trunc here can be an actual i1 trunc, or can be the effective
9139   // truncation that comes from a setcc or select_cc.
9140   if (N->getOpcode() == ISD::TRUNCATE &&
9141       N->getValueType(0) != MVT::i1)
9142     return SDValue();
9143
9144   if (N->getOperand(0).getValueType() != MVT::i32 &&
9145       N->getOperand(0).getValueType() != MVT::i64)
9146     return SDValue();
9147
9148   if (N->getOpcode() == ISD::SETCC ||
9149       N->getOpcode() == ISD::SELECT_CC) {
9150     // If we're looking at a comparison, then we need to make sure that the
9151     // high bits (all except for the first) don't matter the result.
9152     ISD::CondCode CC =
9153       cast<CondCodeSDNode>(N->getOperand(
9154         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9155     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9156
9157     if (ISD::isSignedIntSetCC(CC)) {
9158       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9159           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9160         return SDValue();
9161     } else if (ISD::isUnsignedIntSetCC(CC)) {
9162       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9163                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9164           !DAG.MaskedValueIsZero(N->getOperand(1),
9165                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9166         return SDValue();
9167     } else {
9168       // This is neither a signed nor an unsigned comparison, just make sure
9169       // that the high bits are equal.
9170       APInt Op1Zero, Op1One;
9171       APInt Op2Zero, Op2One;
9172       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9173       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9174
9175       // We don't really care about what is known about the first bit (if
9176       // anything), so clear it in all masks prior to comparing them.
9177       Op1Zero.clearBit(0); Op1One.clearBit(0);
9178       Op2Zero.clearBit(0); Op2One.clearBit(0);
9179
9180       if (Op1Zero != Op2Zero || Op1One != Op2One)
9181         return SDValue();
9182     }
9183   }
9184
9185   // We now know that the higher-order bits are irrelevant, we just need to
9186   // make sure that all of the intermediate operations are bit operations, and
9187   // all inputs are extensions.
9188   if (N->getOperand(0).getOpcode() != ISD::AND &&
9189       N->getOperand(0).getOpcode() != ISD::OR  &&
9190       N->getOperand(0).getOpcode() != ISD::XOR &&
9191       N->getOperand(0).getOpcode() != ISD::SELECT &&
9192       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9193       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9194       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9195       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9196       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9197     return SDValue();
9198
9199   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9200       N->getOperand(1).getOpcode() != ISD::AND &&
9201       N->getOperand(1).getOpcode() != ISD::OR  &&
9202       N->getOperand(1).getOpcode() != ISD::XOR &&
9203       N->getOperand(1).getOpcode() != ISD::SELECT &&
9204       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9205       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9206       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9207       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9208       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9209     return SDValue();
9210
9211   SmallVector<SDValue, 4> Inputs;
9212   SmallVector<SDValue, 8> BinOps, PromOps;
9213   SmallPtrSet<SDNode *, 16> Visited;
9214
9215   for (unsigned i = 0; i < 2; ++i) {
9216     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9217           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9218           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9219           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9220         isa<ConstantSDNode>(N->getOperand(i)))
9221       Inputs.push_back(N->getOperand(i));
9222     else
9223       BinOps.push_back(N->getOperand(i));
9224
9225     if (N->getOpcode() == ISD::TRUNCATE)
9226       break;
9227   }
9228
9229   // Visit all inputs, collect all binary operations (and, or, xor and
9230   // select) that are all fed by extensions. 
9231   while (!BinOps.empty()) {
9232     SDValue BinOp = BinOps.back();
9233     BinOps.pop_back();
9234
9235     if (!Visited.insert(BinOp.getNode()).second)
9236       continue;
9237
9238     PromOps.push_back(BinOp);
9239
9240     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9241       // The condition of the select is not promoted.
9242       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9243         continue;
9244       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9245         continue;
9246
9247       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9248             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9249             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9250            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9251           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9252         Inputs.push_back(BinOp.getOperand(i)); 
9253       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9254                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9255                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9256                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9257                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9258                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9259                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9260                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9261                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9262         BinOps.push_back(BinOp.getOperand(i));
9263       } else {
9264         // We have an input that is not an extension or another binary
9265         // operation; we'll abort this transformation.
9266         return SDValue();
9267       }
9268     }
9269   }
9270
9271   // Make sure that this is a self-contained cluster of operations (which
9272   // is not quite the same thing as saying that everything has only one
9273   // use).
9274   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9275     if (isa<ConstantSDNode>(Inputs[i]))
9276       continue;
9277
9278     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9279                               UE = Inputs[i].getNode()->use_end();
9280          UI != UE; ++UI) {
9281       SDNode *User = *UI;
9282       if (User != N && !Visited.count(User))
9283         return SDValue();
9284
9285       // Make sure that we're not going to promote the non-output-value
9286       // operand(s) or SELECT or SELECT_CC.
9287       // FIXME: Although we could sometimes handle this, and it does occur in
9288       // practice that one of the condition inputs to the select is also one of
9289       // the outputs, we currently can't deal with this.
9290       if (User->getOpcode() == ISD::SELECT) {
9291         if (User->getOperand(0) == Inputs[i])
9292           return SDValue();
9293       } else if (User->getOpcode() == ISD::SELECT_CC) {
9294         if (User->getOperand(0) == Inputs[i] ||
9295             User->getOperand(1) == Inputs[i])
9296           return SDValue();
9297       }
9298     }
9299   }
9300
9301   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9302     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9303                               UE = PromOps[i].getNode()->use_end();
9304          UI != UE; ++UI) {
9305       SDNode *User = *UI;
9306       if (User != N && !Visited.count(User))
9307         return SDValue();
9308
9309       // Make sure that we're not going to promote the non-output-value
9310       // operand(s) or SELECT or SELECT_CC.
9311       // FIXME: Although we could sometimes handle this, and it does occur in
9312       // practice that one of the condition inputs to the select is also one of
9313       // the outputs, we currently can't deal with this.
9314       if (User->getOpcode() == ISD::SELECT) {
9315         if (User->getOperand(0) == PromOps[i])
9316           return SDValue();
9317       } else if (User->getOpcode() == ISD::SELECT_CC) {
9318         if (User->getOperand(0) == PromOps[i] ||
9319             User->getOperand(1) == PromOps[i])
9320           return SDValue();
9321       }
9322     }
9323   }
9324
9325   // Replace all inputs with the extension operand.
9326   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9327     // Constants may have users outside the cluster of to-be-promoted nodes,
9328     // and so we need to replace those as we do the promotions.
9329     if (isa<ConstantSDNode>(Inputs[i]))
9330       continue;
9331     else
9332       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9333   }
9334
9335   // Replace all operations (these are all the same, but have a different
9336   // (i1) return type). DAG.getNode will validate that the types of
9337   // a binary operator match, so go through the list in reverse so that
9338   // we've likely promoted both operands first. Any intermediate truncations or
9339   // extensions disappear.
9340   while (!PromOps.empty()) {
9341     SDValue PromOp = PromOps.back();
9342     PromOps.pop_back();
9343
9344     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9345         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9346         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9347         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9348       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9349           PromOp.getOperand(0).getValueType() != MVT::i1) {
9350         // The operand is not yet ready (see comment below).
9351         PromOps.insert(PromOps.begin(), PromOp);
9352         continue;
9353       }
9354
9355       SDValue RepValue = PromOp.getOperand(0);
9356       if (isa<ConstantSDNode>(RepValue))
9357         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9358
9359       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9360       continue;
9361     }
9362
9363     unsigned C;
9364     switch (PromOp.getOpcode()) {
9365     default:             C = 0; break;
9366     case ISD::SELECT:    C = 1; break;
9367     case ISD::SELECT_CC: C = 2; break;
9368     }
9369
9370     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9371          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9372         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9373          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9374       // The to-be-promoted operands of this node have not yet been
9375       // promoted (this should be rare because we're going through the
9376       // list backward, but if one of the operands has several users in
9377       // this cluster of to-be-promoted nodes, it is possible).
9378       PromOps.insert(PromOps.begin(), PromOp);
9379       continue;
9380     }
9381
9382     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9383                                 PromOp.getNode()->op_end());
9384
9385     // If there are any constant inputs, make sure they're replaced now.
9386     for (unsigned i = 0; i < 2; ++i)
9387       if (isa<ConstantSDNode>(Ops[C+i]))
9388         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9389
9390     DAG.ReplaceAllUsesOfValueWith(PromOp,
9391       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9392   }
9393
9394   // Now we're left with the initial truncation itself.
9395   if (N->getOpcode() == ISD::TRUNCATE)
9396     return N->getOperand(0);
9397
9398   // Otherwise, this is a comparison. The operands to be compared have just
9399   // changed type (to i1), but everything else is the same.
9400   return SDValue(N, 0);
9401 }
9402
9403 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9404                                                   DAGCombinerInfo &DCI) const {
9405   SelectionDAG &DAG = DCI.DAG;
9406   SDLoc dl(N);
9407
9408   // If we're tracking CR bits, we need to be careful that we don't have:
9409   //   zext(binary-ops(trunc(x), trunc(y)))
9410   // or
9411   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9412   // such that we're unnecessarily moving things into CR bits that can more
9413   // efficiently stay in GPRs. Note that if we're not certain that the high
9414   // bits are set as required by the final extension, we still may need to do
9415   // some masking to get the proper behavior.
9416
9417   // This same functionality is important on PPC64 when dealing with
9418   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9419   // the return values of functions. Because it is so similar, it is handled
9420   // here as well.
9421
9422   if (N->getValueType(0) != MVT::i32 &&
9423       N->getValueType(0) != MVT::i64)
9424     return SDValue();
9425
9426   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9427         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9428     return SDValue();
9429
9430   if (N->getOperand(0).getOpcode() != ISD::AND &&
9431       N->getOperand(0).getOpcode() != ISD::OR  &&
9432       N->getOperand(0).getOpcode() != ISD::XOR &&
9433       N->getOperand(0).getOpcode() != ISD::SELECT &&
9434       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9435     return SDValue();
9436
9437   SmallVector<SDValue, 4> Inputs;
9438   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9439   SmallPtrSet<SDNode *, 16> Visited;
9440
9441   // Visit all inputs, collect all binary operations (and, or, xor and
9442   // select) that are all fed by truncations. 
9443   while (!BinOps.empty()) {
9444     SDValue BinOp = BinOps.back();
9445     BinOps.pop_back();
9446
9447     if (!Visited.insert(BinOp.getNode()).second)
9448       continue;
9449
9450     PromOps.push_back(BinOp);
9451
9452     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9453       // The condition of the select is not promoted.
9454       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9455         continue;
9456       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9457         continue;
9458
9459       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9460           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9461         Inputs.push_back(BinOp.getOperand(i)); 
9462       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9463                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9464                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9465                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9466                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9467         BinOps.push_back(BinOp.getOperand(i));
9468       } else {
9469         // We have an input that is not a truncation or another binary
9470         // operation; we'll abort this transformation.
9471         return SDValue();
9472       }
9473     }
9474   }
9475
9476   // The operands of a select that must be truncated when the select is
9477   // promoted because the operand is actually part of the to-be-promoted set.
9478   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9479
9480   // Make sure that this is a self-contained cluster of operations (which
9481   // is not quite the same thing as saying that everything has only one
9482   // use).
9483   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9484     if (isa<ConstantSDNode>(Inputs[i]))
9485       continue;
9486
9487     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9488                               UE = Inputs[i].getNode()->use_end();
9489          UI != UE; ++UI) {
9490       SDNode *User = *UI;
9491       if (User != N && !Visited.count(User))
9492         return SDValue();
9493
9494       // If we're going to promote the non-output-value operand(s) or SELECT or
9495       // SELECT_CC, record them for truncation.
9496       if (User->getOpcode() == ISD::SELECT) {
9497         if (User->getOperand(0) == Inputs[i])
9498           SelectTruncOp[0].insert(std::make_pair(User,
9499                                     User->getOperand(0).getValueType()));
9500       } else if (User->getOpcode() == ISD::SELECT_CC) {
9501         if (User->getOperand(0) == Inputs[i])
9502           SelectTruncOp[0].insert(std::make_pair(User,
9503                                     User->getOperand(0).getValueType()));
9504         if (User->getOperand(1) == Inputs[i])
9505           SelectTruncOp[1].insert(std::make_pair(User,
9506                                     User->getOperand(1).getValueType()));
9507       }
9508     }
9509   }
9510
9511   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9512     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9513                               UE = PromOps[i].getNode()->use_end();
9514          UI != UE; ++UI) {
9515       SDNode *User = *UI;
9516       if (User != N && !Visited.count(User))
9517         return SDValue();
9518
9519       // If we're going to promote the non-output-value operand(s) or SELECT or
9520       // SELECT_CC, record them for truncation.
9521       if (User->getOpcode() == ISD::SELECT) {
9522         if (User->getOperand(0) == PromOps[i])
9523           SelectTruncOp[0].insert(std::make_pair(User,
9524                                     User->getOperand(0).getValueType()));
9525       } else if (User->getOpcode() == ISD::SELECT_CC) {
9526         if (User->getOperand(0) == PromOps[i])
9527           SelectTruncOp[0].insert(std::make_pair(User,
9528                                     User->getOperand(0).getValueType()));
9529         if (User->getOperand(1) == PromOps[i])
9530           SelectTruncOp[1].insert(std::make_pair(User,
9531                                     User->getOperand(1).getValueType()));
9532       }
9533     }
9534   }
9535
9536   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9537   bool ReallyNeedsExt = false;
9538   if (N->getOpcode() != ISD::ANY_EXTEND) {
9539     // If all of the inputs are not already sign/zero extended, then
9540     // we'll still need to do that at the end.
9541     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9542       if (isa<ConstantSDNode>(Inputs[i]))
9543         continue;
9544
9545       unsigned OpBits =
9546         Inputs[i].getOperand(0).getValueSizeInBits();
9547       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9548
9549       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9550            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9551                                   APInt::getHighBitsSet(OpBits,
9552                                                         OpBits-PromBits))) ||
9553           (N->getOpcode() == ISD::SIGN_EXTEND &&
9554            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9555              (OpBits-(PromBits-1)))) {
9556         ReallyNeedsExt = true;
9557         break;
9558       }
9559     }
9560   }
9561
9562   // Replace all inputs, either with the truncation operand, or a
9563   // truncation or extension to the final output type.
9564   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9565     // Constant inputs need to be replaced with the to-be-promoted nodes that
9566     // use them because they might have users outside of the cluster of
9567     // promoted nodes.
9568     if (isa<ConstantSDNode>(Inputs[i]))
9569       continue;
9570
9571     SDValue InSrc = Inputs[i].getOperand(0);
9572     if (Inputs[i].getValueType() == N->getValueType(0))
9573       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9574     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9575       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9576         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9577     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9578       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9579         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9580     else
9581       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9582         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9583   }
9584
9585   // Replace all operations (these are all the same, but have a different
9586   // (promoted) return type). DAG.getNode will validate that the types of
9587   // a binary operator match, so go through the list in reverse so that
9588   // we've likely promoted both operands first.
9589   while (!PromOps.empty()) {
9590     SDValue PromOp = PromOps.back();
9591     PromOps.pop_back();
9592
9593     unsigned C;
9594     switch (PromOp.getOpcode()) {
9595     default:             C = 0; break;
9596     case ISD::SELECT:    C = 1; break;
9597     case ISD::SELECT_CC: C = 2; break;
9598     }
9599
9600     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9601          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9602         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9603          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9604       // The to-be-promoted operands of this node have not yet been
9605       // promoted (this should be rare because we're going through the
9606       // list backward, but if one of the operands has several users in
9607       // this cluster of to-be-promoted nodes, it is possible).
9608       PromOps.insert(PromOps.begin(), PromOp);
9609       continue;
9610     }
9611
9612     // For SELECT and SELECT_CC nodes, we do a similar check for any
9613     // to-be-promoted comparison inputs.
9614     if (PromOp.getOpcode() == ISD::SELECT ||
9615         PromOp.getOpcode() == ISD::SELECT_CC) {
9616       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9617            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9618           (SelectTruncOp[1].count(PromOp.getNode()) &&
9619            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9620         PromOps.insert(PromOps.begin(), PromOp);
9621         continue;
9622       }
9623     }
9624
9625     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9626                                 PromOp.getNode()->op_end());
9627
9628     // If this node has constant inputs, then they'll need to be promoted here.
9629     for (unsigned i = 0; i < 2; ++i) {
9630       if (!isa<ConstantSDNode>(Ops[C+i]))
9631         continue;
9632       if (Ops[C+i].getValueType() == N->getValueType(0))
9633         continue;
9634
9635       if (N->getOpcode() == ISD::SIGN_EXTEND)
9636         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9637       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9638         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9639       else
9640         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9641     }
9642
9643     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9644     // truncate them again to the original value type.
9645     if (PromOp.getOpcode() == ISD::SELECT ||
9646         PromOp.getOpcode() == ISD::SELECT_CC) {
9647       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9648       if (SI0 != SelectTruncOp[0].end())
9649         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9650       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9651       if (SI1 != SelectTruncOp[1].end())
9652         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9653     }
9654
9655     DAG.ReplaceAllUsesOfValueWith(PromOp,
9656       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9657   }
9658
9659   // Now we're left with the initial extension itself.
9660   if (!ReallyNeedsExt)
9661     return N->getOperand(0);
9662
9663   // To zero extend, just mask off everything except for the first bit (in the
9664   // i1 case).
9665   if (N->getOpcode() == ISD::ZERO_EXTEND)
9666     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9667                        DAG.getConstant(APInt::getLowBitsSet(
9668                                          N->getValueSizeInBits(0), PromBits),
9669                                        N->getValueType(0)));
9670
9671   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9672          "Invalid extension type");
9673   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9674   SDValue ShiftCst =
9675     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9676   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9677                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9678                                  N->getOperand(0), ShiftCst), ShiftCst);
9679 }
9680
9681 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9682                                               DAGCombinerInfo &DCI) const {
9683   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9684           N->getOpcode() == ISD::UINT_TO_FP) &&
9685          "Need an int -> FP conversion node here");
9686
9687   if (!Subtarget.has64BitSupport())
9688     return SDValue();
9689
9690   SelectionDAG &DAG = DCI.DAG;
9691   SDLoc dl(N);
9692   SDValue Op(N, 0);
9693
9694   // Don't handle ppc_fp128 here or i1 conversions.
9695   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9696     return SDValue();
9697   if (Op.getOperand(0).getValueType() == MVT::i1)
9698     return SDValue();
9699
9700   // For i32 intermediate values, unfortunately, the conversion functions
9701   // leave the upper 32 bits of the value are undefined. Within the set of
9702   // scalar instructions, we have no method for zero- or sign-extending the
9703   // value. Thus, we cannot handle i32 intermediate values here.
9704   if (Op.getOperand(0).getValueType() == MVT::i32)
9705     return SDValue();
9706
9707   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9708          "UINT_TO_FP is supported only with FPCVT");
9709
9710   // If we have FCFIDS, then use it when converting to single-precision.
9711   // Otherwise, convert to double-precision and then round.
9712   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9713                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9714                                                             : PPCISD::FCFIDS)
9715                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9716                                                             : PPCISD::FCFID);
9717   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9718                   ? MVT::f32
9719                   : MVT::f64;
9720
9721   // If we're converting from a float, to an int, and back to a float again,
9722   // then we don't need the store/load pair at all.
9723   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9724        Subtarget.hasFPCVT()) ||
9725       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9726     SDValue Src = Op.getOperand(0).getOperand(0);
9727     if (Src.getValueType() == MVT::f32) {
9728       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9729       DCI.AddToWorklist(Src.getNode());
9730     }
9731
9732     unsigned FCTOp =
9733       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9734                                                         PPCISD::FCTIDUZ;
9735
9736     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9737     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9738
9739     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9740       FP = DAG.getNode(ISD::FP_ROUND, dl,
9741                        MVT::f32, FP, DAG.getIntPtrConstant(0));
9742       DCI.AddToWorklist(FP.getNode());
9743     }
9744
9745     return FP;
9746   }
9747
9748   return SDValue();
9749 }
9750
9751 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9752 // builtins) into loads with swaps.
9753 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9754                                               DAGCombinerInfo &DCI) const {
9755   SelectionDAG &DAG = DCI.DAG;
9756   SDLoc dl(N);
9757   SDValue Chain;
9758   SDValue Base;
9759   MachineMemOperand *MMO;
9760
9761   switch (N->getOpcode()) {
9762   default:
9763     llvm_unreachable("Unexpected opcode for little endian VSX load");
9764   case ISD::LOAD: {
9765     LoadSDNode *LD = cast<LoadSDNode>(N);
9766     Chain = LD->getChain();
9767     Base = LD->getBasePtr();
9768     MMO = LD->getMemOperand();
9769     // If the MMO suggests this isn't a load of a full vector, leave
9770     // things alone.  For a built-in, we have to make the change for
9771     // correctness, so if there is a size problem that will be a bug.
9772     if (MMO->getSize() < 16)
9773       return SDValue();
9774     break;
9775   }
9776   case ISD::INTRINSIC_W_CHAIN: {
9777     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9778     Chain = Intrin->getChain();
9779     Base = Intrin->getBasePtr();
9780     MMO = Intrin->getMemOperand();
9781     break;
9782   }
9783   }
9784
9785   MVT VecTy = N->getValueType(0).getSimpleVT();
9786   SDValue LoadOps[] = { Chain, Base };
9787   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9788                                          DAG.getVTList(VecTy, MVT::Other),
9789                                          LoadOps, VecTy, MMO);
9790   DCI.AddToWorklist(Load.getNode());
9791   Chain = Load.getValue(1);
9792   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9793                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9794   DCI.AddToWorklist(Swap.getNode());
9795   return Swap;
9796 }
9797
9798 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9799 // builtins) into stores with swaps.
9800 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9801                                                DAGCombinerInfo &DCI) const {
9802   SelectionDAG &DAG = DCI.DAG;
9803   SDLoc dl(N);
9804   SDValue Chain;
9805   SDValue Base;
9806   unsigned SrcOpnd;
9807   MachineMemOperand *MMO;
9808
9809   switch (N->getOpcode()) {
9810   default:
9811     llvm_unreachable("Unexpected opcode for little endian VSX store");
9812   case ISD::STORE: {
9813     StoreSDNode *ST = cast<StoreSDNode>(N);
9814     Chain = ST->getChain();
9815     Base = ST->getBasePtr();
9816     MMO = ST->getMemOperand();
9817     SrcOpnd = 1;
9818     // If the MMO suggests this isn't a store of a full vector, leave
9819     // things alone.  For a built-in, we have to make the change for
9820     // correctness, so if there is a size problem that will be a bug.
9821     if (MMO->getSize() < 16)
9822       return SDValue();
9823     break;
9824   }
9825   case ISD::INTRINSIC_VOID: {
9826     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9827     Chain = Intrin->getChain();
9828     // Intrin->getBasePtr() oddly does not get what we want.
9829     Base = Intrin->getOperand(3);
9830     MMO = Intrin->getMemOperand();
9831     SrcOpnd = 2;
9832     break;
9833   }
9834   }
9835
9836   SDValue Src = N->getOperand(SrcOpnd);
9837   MVT VecTy = Src.getValueType().getSimpleVT();
9838   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9839                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9840   DCI.AddToWorklist(Swap.getNode());
9841   Chain = Swap.getValue(1);
9842   SDValue StoreOps[] = { Chain, Swap, Base };
9843   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9844                                           DAG.getVTList(MVT::Other),
9845                                           StoreOps, VecTy, MMO);
9846   DCI.AddToWorklist(Store.getNode());
9847   return Store;
9848 }
9849
9850 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9851                                              DAGCombinerInfo &DCI) const {
9852   SelectionDAG &DAG = DCI.DAG;
9853   SDLoc dl(N);
9854   switch (N->getOpcode()) {
9855   default: break;
9856   case PPCISD::SHL:
9857     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9858       if (C->isNullValue())   // 0 << V -> 0.
9859         return N->getOperand(0);
9860     }
9861     break;
9862   case PPCISD::SRL:
9863     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9864       if (C->isNullValue())   // 0 >>u V -> 0.
9865         return N->getOperand(0);
9866     }
9867     break;
9868   case PPCISD::SRA:
9869     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9870       if (C->isNullValue() ||   //  0 >>s V -> 0.
9871           C->isAllOnesValue())    // -1 >>s V -> -1.
9872         return N->getOperand(0);
9873     }
9874     break;
9875   case ISD::SIGN_EXTEND:
9876   case ISD::ZERO_EXTEND:
9877   case ISD::ANY_EXTEND: 
9878     return DAGCombineExtBoolTrunc(N, DCI);
9879   case ISD::TRUNCATE:
9880   case ISD::SETCC:
9881   case ISD::SELECT_CC:
9882     return DAGCombineTruncBoolExt(N, DCI);
9883   case ISD::SINT_TO_FP:
9884   case ISD::UINT_TO_FP:
9885     return combineFPToIntToFP(N, DCI);
9886   case ISD::STORE: {
9887     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9888     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9889         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9890         N->getOperand(1).getValueType() == MVT::i32 &&
9891         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9892       SDValue Val = N->getOperand(1).getOperand(0);
9893       if (Val.getValueType() == MVT::f32) {
9894         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9895         DCI.AddToWorklist(Val.getNode());
9896       }
9897       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9898       DCI.AddToWorklist(Val.getNode());
9899
9900       SDValue Ops[] = {
9901         N->getOperand(0), Val, N->getOperand(2),
9902         DAG.getValueType(N->getOperand(1).getValueType())
9903       };
9904
9905       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9906               DAG.getVTList(MVT::Other), Ops,
9907               cast<StoreSDNode>(N)->getMemoryVT(),
9908               cast<StoreSDNode>(N)->getMemOperand());
9909       DCI.AddToWorklist(Val.getNode());
9910       return Val;
9911     }
9912
9913     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9914     if (cast<StoreSDNode>(N)->isUnindexed() &&
9915         N->getOperand(1).getOpcode() == ISD::BSWAP &&
9916         N->getOperand(1).getNode()->hasOneUse() &&
9917         (N->getOperand(1).getValueType() == MVT::i32 ||
9918          N->getOperand(1).getValueType() == MVT::i16 ||
9919          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9920           N->getOperand(1).getValueType() == MVT::i64))) {
9921       SDValue BSwapOp = N->getOperand(1).getOperand(0);
9922       // Do an any-extend to 32-bits if this is a half-word input.
9923       if (BSwapOp.getValueType() == MVT::i16)
9924         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9925
9926       SDValue Ops[] = {
9927         N->getOperand(0), BSwapOp, N->getOperand(2),
9928         DAG.getValueType(N->getOperand(1).getValueType())
9929       };
9930       return
9931         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9932                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9933                                 cast<StoreSDNode>(N)->getMemOperand());
9934     }
9935
9936     // For little endian, VSX stores require generating xxswapd/lxvd2x.
9937     EVT VT = N->getOperand(1).getValueType();
9938     if (VT.isSimple()) {
9939       MVT StoreVT = VT.getSimpleVT();
9940       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9941           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9942            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9943         return expandVSXStoreForLE(N, DCI);
9944     }
9945     break;
9946   }
9947   case ISD::LOAD: {
9948     LoadSDNode *LD = cast<LoadSDNode>(N);
9949     EVT VT = LD->getValueType(0);
9950
9951     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9952     if (VT.isSimple()) {
9953       MVT LoadVT = VT.getSimpleVT();
9954       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9955           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9956            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9957         return expandVSXLoadForLE(N, DCI);
9958     }
9959
9960     EVT MemVT = LD->getMemoryVT();
9961     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9962     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9963     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9964     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9965     if (LD->isUnindexed() && VT.isVector() &&
9966         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9967           // P8 and later hardware should just use LOAD.
9968           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9969                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9970          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9971           LD->getAlignment() >= ScalarABIAlignment)) &&
9972         LD->getAlignment() < ABIAlignment) {
9973       // This is a type-legal unaligned Altivec or QPX load.
9974       SDValue Chain = LD->getChain();
9975       SDValue Ptr = LD->getBasePtr();
9976       bool isLittleEndian = Subtarget.isLittleEndian();
9977
9978       // This implements the loading of unaligned vectors as described in
9979       // the venerable Apple Velocity Engine overview. Specifically:
9980       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9981       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9982       //
9983       // The general idea is to expand a sequence of one or more unaligned
9984       // loads into an alignment-based permutation-control instruction (lvsl
9985       // or lvsr), a series of regular vector loads (which always truncate
9986       // their input address to an aligned address), and a series of
9987       // permutations.  The results of these permutations are the requested
9988       // loaded values.  The trick is that the last "extra" load is not taken
9989       // from the address you might suspect (sizeof(vector) bytes after the
9990       // last requested load), but rather sizeof(vector) - 1 bytes after the
9991       // last requested vector. The point of this is to avoid a page fault if
9992       // the base address happened to be aligned. This works because if the
9993       // base address is aligned, then adding less than a full vector length
9994       // will cause the last vector in the sequence to be (re)loaded.
9995       // Otherwise, the next vector will be fetched as you might suspect was
9996       // necessary.
9997
9998       // We might be able to reuse the permutation generation from
9999       // a different base address offset from this one by an aligned amount.
10000       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10001       // optimization later.
10002       Intrinsic::ID Intr, IntrLD, IntrPerm;
10003       MVT PermCntlTy, PermTy, LDTy;
10004       if (Subtarget.hasAltivec()) {
10005         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10006                                  Intrinsic::ppc_altivec_lvsl;
10007         IntrLD = Intrinsic::ppc_altivec_lvx;
10008         IntrPerm = Intrinsic::ppc_altivec_vperm;
10009         PermCntlTy = MVT::v16i8;
10010         PermTy = MVT::v4i32;
10011         LDTy = MVT::v4i32;
10012       } else {
10013         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10014                                        Intrinsic::ppc_qpx_qvlpcls;
10015         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10016                                        Intrinsic::ppc_qpx_qvlfs;
10017         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10018         PermCntlTy = MVT::v4f64;
10019         PermTy = MVT::v4f64;
10020         LDTy = MemVT.getSimpleVT();
10021       }
10022
10023       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10024
10025       // Create the new MMO for the new base load. It is like the original MMO,
10026       // but represents an area in memory almost twice the vector size centered
10027       // on the original address. If the address is unaligned, we might start
10028       // reading up to (sizeof(vector)-1) bytes below the address of the
10029       // original unaligned load.
10030       MachineFunction &MF = DAG.getMachineFunction();
10031       MachineMemOperand *BaseMMO =
10032         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10033                                 2*MemVT.getStoreSize()-1);
10034
10035       // Create the new base load.
10036       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
10037       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10038       SDValue BaseLoad =
10039         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10040                                 DAG.getVTList(PermTy, MVT::Other),
10041                                 BaseLoadOps, LDTy, BaseMMO);
10042
10043       // Note that the value of IncOffset (which is provided to the next
10044       // load's pointer info offset value, and thus used to calculate the
10045       // alignment), and the value of IncValue (which is actually used to
10046       // increment the pointer value) are different! This is because we
10047       // require the next load to appear to be aligned, even though it
10048       // is actually offset from the base pointer by a lesser amount.
10049       int IncOffset = VT.getSizeInBits() / 8;
10050       int IncValue = IncOffset;
10051
10052       // Walk (both up and down) the chain looking for another load at the real
10053       // (aligned) offset (the alignment of the other load does not matter in
10054       // this case). If found, then do not use the offset reduction trick, as
10055       // that will prevent the loads from being later combined (as they would
10056       // otherwise be duplicates).
10057       if (!findConsecutiveLoad(LD, DAG))
10058         --IncValue;
10059
10060       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
10061       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10062
10063       MachineMemOperand *ExtraMMO =
10064         MF.getMachineMemOperand(LD->getMemOperand(),
10065                                 1, 2*MemVT.getStoreSize()-1);
10066       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10067       SDValue ExtraLoad =
10068         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10069                                 DAG.getVTList(PermTy, MVT::Other),
10070                                 ExtraLoadOps, LDTy, ExtraMMO);
10071
10072       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10073         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10074
10075       // Because vperm has a big-endian bias, we must reverse the order
10076       // of the input vectors and complement the permute control vector
10077       // when generating little endian code.  We have already handled the
10078       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10079       // and ExtraLoad here.
10080       SDValue Perm;
10081       if (isLittleEndian)
10082         Perm = BuildIntrinsicOp(IntrPerm,
10083                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10084       else
10085         Perm = BuildIntrinsicOp(IntrPerm,
10086                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10087
10088       if (VT != PermTy)
10089         Perm = Subtarget.hasAltivec() ?
10090                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10091                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10092                                DAG.getTargetConstant(1, MVT::i64));
10093                                // second argument is 1 because this rounding
10094                                // is always exact.
10095
10096       // The output of the permutation is our loaded result, the TokenFactor is
10097       // our new chain.
10098       DCI.CombineTo(N, Perm, TF);
10099       return SDValue(N, 0);
10100     }
10101     }
10102     break;
10103     case ISD::INTRINSIC_WO_CHAIN: {
10104       bool isLittleEndian = Subtarget.isLittleEndian();
10105       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10106       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10107                                            : Intrinsic::ppc_altivec_lvsl);
10108       if ((IID == Intr ||
10109            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10110            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10111         N->getOperand(1)->getOpcode() == ISD::ADD) {
10112         SDValue Add = N->getOperand(1);
10113
10114         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10115                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10116
10117         if (DAG.MaskedValueIsZero(
10118                 Add->getOperand(1),
10119                 APInt::getAllOnesValue(Bits /* alignment */)
10120                     .zext(
10121                         Add.getValueType().getScalarType().getSizeInBits()))) {
10122           SDNode *BasePtr = Add->getOperand(0).getNode();
10123           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10124                                     UE = BasePtr->use_end();
10125                UI != UE; ++UI) {
10126             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10127                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10128               // We've found another LVSL/LVSR, and this address is an aligned
10129               // multiple of that one. The results will be the same, so use the
10130               // one we've just found instead.
10131
10132               return SDValue(*UI, 0);
10133             }
10134           }
10135         }
10136
10137         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10138           SDNode *BasePtr = Add->getOperand(0).getNode();
10139           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10140                UE = BasePtr->use_end(); UI != UE; ++UI) {
10141             if (UI->getOpcode() == ISD::ADD &&
10142                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10143                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10144                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10145                 (1ULL << Bits) == 0) {
10146               SDNode *OtherAdd = *UI;
10147               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10148                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10149                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10150                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10151                   return SDValue(*VI, 0);
10152                 }
10153               }
10154             }
10155           }
10156         }
10157       }
10158     }
10159
10160     break;
10161   case ISD::INTRINSIC_W_CHAIN: {
10162     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10163     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10164       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10165       default:
10166         break;
10167       case Intrinsic::ppc_vsx_lxvw4x:
10168       case Intrinsic::ppc_vsx_lxvd2x:
10169         return expandVSXLoadForLE(N, DCI);
10170       }
10171     }
10172     break;
10173   }
10174   case ISD::INTRINSIC_VOID: {
10175     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10176     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10177       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10178       default:
10179         break;
10180       case Intrinsic::ppc_vsx_stxvw4x:
10181       case Intrinsic::ppc_vsx_stxvd2x:
10182         return expandVSXStoreForLE(N, DCI);
10183       }
10184     }
10185     break;
10186   }
10187   case ISD::BSWAP:
10188     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10189     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10190         N->getOperand(0).hasOneUse() &&
10191         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10192          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10193           N->getValueType(0) == MVT::i64))) {
10194       SDValue Load = N->getOperand(0);
10195       LoadSDNode *LD = cast<LoadSDNode>(Load);
10196       // Create the byte-swapping load.
10197       SDValue Ops[] = {
10198         LD->getChain(),    // Chain
10199         LD->getBasePtr(),  // Ptr
10200         DAG.getValueType(N->getValueType(0)) // VT
10201       };
10202       SDValue BSLoad =
10203         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10204                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10205                                               MVT::i64 : MVT::i32, MVT::Other),
10206                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10207
10208       // If this is an i16 load, insert the truncate.
10209       SDValue ResVal = BSLoad;
10210       if (N->getValueType(0) == MVT::i16)
10211         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10212
10213       // First, combine the bswap away.  This makes the value produced by the
10214       // load dead.
10215       DCI.CombineTo(N, ResVal);
10216
10217       // Next, combine the load away, we give it a bogus result value but a real
10218       // chain result.  The result value is dead because the bswap is dead.
10219       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10220
10221       // Return N so it doesn't get rechecked!
10222       return SDValue(N, 0);
10223     }
10224
10225     break;
10226   case PPCISD::VCMP: {
10227     // If a VCMPo node already exists with exactly the same operands as this
10228     // node, use its result instead of this node (VCMPo computes both a CR6 and
10229     // a normal output).
10230     //
10231     if (!N->getOperand(0).hasOneUse() &&
10232         !N->getOperand(1).hasOneUse() &&
10233         !N->getOperand(2).hasOneUse()) {
10234
10235       // Scan all of the users of the LHS, looking for VCMPo's that match.
10236       SDNode *VCMPoNode = nullptr;
10237
10238       SDNode *LHSN = N->getOperand(0).getNode();
10239       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10240            UI != E; ++UI)
10241         if (UI->getOpcode() == PPCISD::VCMPo &&
10242             UI->getOperand(1) == N->getOperand(1) &&
10243             UI->getOperand(2) == N->getOperand(2) &&
10244             UI->getOperand(0) == N->getOperand(0)) {
10245           VCMPoNode = *UI;
10246           break;
10247         }
10248
10249       // If there is no VCMPo node, or if the flag value has a single use, don't
10250       // transform this.
10251       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10252         break;
10253
10254       // Look at the (necessarily single) use of the flag value.  If it has a
10255       // chain, this transformation is more complex.  Note that multiple things
10256       // could use the value result, which we should ignore.
10257       SDNode *FlagUser = nullptr;
10258       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10259            FlagUser == nullptr; ++UI) {
10260         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10261         SDNode *User = *UI;
10262         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10263           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10264             FlagUser = User;
10265             break;
10266           }
10267         }
10268       }
10269
10270       // If the user is a MFOCRF instruction, we know this is safe.
10271       // Otherwise we give up for right now.
10272       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10273         return SDValue(VCMPoNode, 0);
10274     }
10275     break;
10276   }
10277   case ISD::BRCOND: {
10278     SDValue Cond = N->getOperand(1);
10279     SDValue Target = N->getOperand(2);
10280  
10281     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10282         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10283           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10284
10285       // We now need to make the intrinsic dead (it cannot be instruction
10286       // selected).
10287       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10288       assert(Cond.getNode()->hasOneUse() &&
10289              "Counter decrement has more than one use");
10290
10291       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10292                          N->getOperand(0), Target);
10293     }
10294   }
10295   break;
10296   case ISD::BR_CC: {
10297     // If this is a branch on an altivec predicate comparison, lower this so
10298     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10299     // lowering is done pre-legalize, because the legalizer lowers the predicate
10300     // compare down to code that is difficult to reassemble.
10301     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10302     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10303
10304     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10305     // value. If so, pass-through the AND to get to the intrinsic.
10306     if (LHS.getOpcode() == ISD::AND &&
10307         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10308         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10309           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10310         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10311         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10312           isZero())
10313       LHS = LHS.getOperand(0);
10314
10315     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10316         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10317           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10318         isa<ConstantSDNode>(RHS)) {
10319       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10320              "Counter decrement comparison is not EQ or NE");
10321
10322       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10323       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10324                     (CC == ISD::SETNE && !Val);
10325
10326       // We now need to make the intrinsic dead (it cannot be instruction
10327       // selected).
10328       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10329       assert(LHS.getNode()->hasOneUse() &&
10330              "Counter decrement has more than one use");
10331
10332       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10333                          N->getOperand(0), N->getOperand(4));
10334     }
10335
10336     int CompareOpc;
10337     bool isDot;
10338
10339     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10340         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10341         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10342       assert(isDot && "Can't compare against a vector result!");
10343
10344       // If this is a comparison against something other than 0/1, then we know
10345       // that the condition is never/always true.
10346       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10347       if (Val != 0 && Val != 1) {
10348         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10349           return N->getOperand(0);
10350         // Always !=, turn it into an unconditional branch.
10351         return DAG.getNode(ISD::BR, dl, MVT::Other,
10352                            N->getOperand(0), N->getOperand(4));
10353       }
10354
10355       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10356
10357       // Create the PPCISD altivec 'dot' comparison node.
10358       SDValue Ops[] = {
10359         LHS.getOperand(2),  // LHS of compare
10360         LHS.getOperand(3),  // RHS of compare
10361         DAG.getConstant(CompareOpc, MVT::i32)
10362       };
10363       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10364       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10365
10366       // Unpack the result based on how the target uses it.
10367       PPC::Predicate CompOpc;
10368       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10369       default:  // Can't happen, don't crash on invalid number though.
10370       case 0:   // Branch on the value of the EQ bit of CR6.
10371         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10372         break;
10373       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10374         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10375         break;
10376       case 2:   // Branch on the value of the LT bit of CR6.
10377         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10378         break;
10379       case 3:   // Branch on the inverted value of the LT bit of CR6.
10380         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10381         break;
10382       }
10383
10384       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10385                          DAG.getConstant(CompOpc, MVT::i32),
10386                          DAG.getRegister(PPC::CR6, MVT::i32),
10387                          N->getOperand(4), CompNode.getValue(1));
10388     }
10389     break;
10390   }
10391   }
10392
10393   return SDValue();
10394 }
10395
10396 SDValue
10397 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10398                                   SelectionDAG &DAG,
10399                                   std::vector<SDNode *> *Created) const {
10400   // fold (sdiv X, pow2)
10401   EVT VT = N->getValueType(0);
10402   if (VT == MVT::i64 && !Subtarget.isPPC64())
10403     return SDValue();
10404   if ((VT != MVT::i32 && VT != MVT::i64) ||
10405       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10406     return SDValue();
10407
10408   SDLoc DL(N);
10409   SDValue N0 = N->getOperand(0);
10410
10411   bool IsNegPow2 = (-Divisor).isPowerOf2();
10412   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10413   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10414
10415   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10416   if (Created)
10417     Created->push_back(Op.getNode());
10418
10419   if (IsNegPow2) {
10420     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10421     if (Created)
10422       Created->push_back(Op.getNode());
10423   }
10424
10425   return Op;
10426 }
10427
10428 //===----------------------------------------------------------------------===//
10429 // Inline Assembly Support
10430 //===----------------------------------------------------------------------===//
10431
10432 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10433                                                       APInt &KnownZero,
10434                                                       APInt &KnownOne,
10435                                                       const SelectionDAG &DAG,
10436                                                       unsigned Depth) const {
10437   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10438   switch (Op.getOpcode()) {
10439   default: break;
10440   case PPCISD::LBRX: {
10441     // lhbrx is known to have the top bits cleared out.
10442     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10443       KnownZero = 0xFFFF0000;
10444     break;
10445   }
10446   case ISD::INTRINSIC_WO_CHAIN: {
10447     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10448     default: break;
10449     case Intrinsic::ppc_altivec_vcmpbfp_p:
10450     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10451     case Intrinsic::ppc_altivec_vcmpequb_p:
10452     case Intrinsic::ppc_altivec_vcmpequh_p:
10453     case Intrinsic::ppc_altivec_vcmpequw_p:
10454     case Intrinsic::ppc_altivec_vcmpequd_p:
10455     case Intrinsic::ppc_altivec_vcmpgefp_p:
10456     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10457     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10458     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10459     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10460     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10461     case Intrinsic::ppc_altivec_vcmpgtub_p:
10462     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10463     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10464     case Intrinsic::ppc_altivec_vcmpgtud_p:
10465       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10466       break;
10467     }
10468   }
10469   }
10470 }
10471
10472 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10473   switch (Subtarget.getDarwinDirective()) {
10474   default: break;
10475   case PPC::DIR_970:
10476   case PPC::DIR_PWR4:
10477   case PPC::DIR_PWR5:
10478   case PPC::DIR_PWR5X:
10479   case PPC::DIR_PWR6:
10480   case PPC::DIR_PWR6X:
10481   case PPC::DIR_PWR7:
10482   case PPC::DIR_PWR8: {
10483     if (!ML)
10484       break;
10485
10486     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10487
10488     // For small loops (between 5 and 8 instructions), align to a 32-byte
10489     // boundary so that the entire loop fits in one instruction-cache line.
10490     uint64_t LoopSize = 0;
10491     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10492       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10493         LoopSize += TII->GetInstSizeInBytes(J);
10494
10495     if (LoopSize > 16 && LoopSize <= 32)
10496       return 5;
10497
10498     break;
10499   }
10500   }
10501
10502   return TargetLowering::getPrefLoopAlignment(ML);
10503 }
10504
10505 /// getConstraintType - Given a constraint, return the type of
10506 /// constraint it is for this target.
10507 PPCTargetLowering::ConstraintType
10508 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10509   if (Constraint.size() == 1) {
10510     switch (Constraint[0]) {
10511     default: break;
10512     case 'b':
10513     case 'r':
10514     case 'f':
10515     case 'v':
10516     case 'y':
10517       return C_RegisterClass;
10518     case 'Z':
10519       // FIXME: While Z does indicate a memory constraint, it specifically
10520       // indicates an r+r address (used in conjunction with the 'y' modifier
10521       // in the replacement string). Currently, we're forcing the base
10522       // register to be r0 in the asm printer (which is interpreted as zero)
10523       // and forming the complete address in the second register. This is
10524       // suboptimal.
10525       return C_Memory;
10526     }
10527   } else if (Constraint == "wc") { // individual CR bits.
10528     return C_RegisterClass;
10529   } else if (Constraint == "wa" || Constraint == "wd" ||
10530              Constraint == "wf" || Constraint == "ws") {
10531     return C_RegisterClass; // VSX registers.
10532   }
10533   return TargetLowering::getConstraintType(Constraint);
10534 }
10535
10536 /// Examine constraint type and operand type and determine a weight value.
10537 /// This object must already have been set up with the operand type
10538 /// and the current alternative constraint selected.
10539 TargetLowering::ConstraintWeight
10540 PPCTargetLowering::getSingleConstraintMatchWeight(
10541     AsmOperandInfo &info, const char *constraint) const {
10542   ConstraintWeight weight = CW_Invalid;
10543   Value *CallOperandVal = info.CallOperandVal;
10544     // If we don't have a value, we can't do a match,
10545     // but allow it at the lowest weight.
10546   if (!CallOperandVal)
10547     return CW_Default;
10548   Type *type = CallOperandVal->getType();
10549
10550   // Look at the constraint type.
10551   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10552     return CW_Register; // an individual CR bit.
10553   else if ((StringRef(constraint) == "wa" ||
10554             StringRef(constraint) == "wd" ||
10555             StringRef(constraint) == "wf") &&
10556            type->isVectorTy())
10557     return CW_Register;
10558   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10559     return CW_Register;
10560
10561   switch (*constraint) {
10562   default:
10563     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10564     break;
10565   case 'b':
10566     if (type->isIntegerTy())
10567       weight = CW_Register;
10568     break;
10569   case 'f':
10570     if (type->isFloatTy())
10571       weight = CW_Register;
10572     break;
10573   case 'd':
10574     if (type->isDoubleTy())
10575       weight = CW_Register;
10576     break;
10577   case 'v':
10578     if (type->isVectorTy())
10579       weight = CW_Register;
10580     break;
10581   case 'y':
10582     weight = CW_Register;
10583     break;
10584   case 'Z':
10585     weight = CW_Memory;
10586     break;
10587   }
10588   return weight;
10589 }
10590
10591 std::pair<unsigned, const TargetRegisterClass *>
10592 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10593                                                 const std::string &Constraint,
10594                                                 MVT VT) const {
10595   if (Constraint.size() == 1) {
10596     // GCC RS6000 Constraint Letters
10597     switch (Constraint[0]) {
10598     case 'b':   // R1-R31
10599       if (VT == MVT::i64 && Subtarget.isPPC64())
10600         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10601       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10602     case 'r':   // R0-R31
10603       if (VT == MVT::i64 && Subtarget.isPPC64())
10604         return std::make_pair(0U, &PPC::G8RCRegClass);
10605       return std::make_pair(0U, &PPC::GPRCRegClass);
10606     case 'f':
10607       if (VT == MVT::f32 || VT == MVT::i32)
10608         return std::make_pair(0U, &PPC::F4RCRegClass);
10609       if (VT == MVT::f64 || VT == MVT::i64)
10610         return std::make_pair(0U, &PPC::F8RCRegClass);
10611       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10612         return std::make_pair(0U, &PPC::QFRCRegClass);
10613       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10614         return std::make_pair(0U, &PPC::QSRCRegClass);
10615       break;
10616     case 'v':
10617       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10618         return std::make_pair(0U, &PPC::QFRCRegClass);
10619       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10620         return std::make_pair(0U, &PPC::QSRCRegClass);
10621       return std::make_pair(0U, &PPC::VRRCRegClass);
10622     case 'y':   // crrc
10623       return std::make_pair(0U, &PPC::CRRCRegClass);
10624     }
10625   } else if (Constraint == "wc") { // an individual CR bit.
10626     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10627   } else if (Constraint == "wa" || Constraint == "wd" ||
10628              Constraint == "wf") {
10629     return std::make_pair(0U, &PPC::VSRCRegClass);
10630   } else if (Constraint == "ws") {
10631     return std::make_pair(0U, &PPC::VSFRCRegClass);
10632   }
10633
10634   std::pair<unsigned, const TargetRegisterClass *> R =
10635       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10636
10637   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10638   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10639   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10640   // register.
10641   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10642   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10643   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10644       PPC::GPRCRegClass.contains(R.first))
10645     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10646                             PPC::sub_32, &PPC::G8RCRegClass),
10647                           &PPC::G8RCRegClass);
10648
10649   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10650   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10651     R.first = PPC::CR0;
10652     R.second = &PPC::CRRCRegClass;
10653   }
10654
10655   return R;
10656 }
10657
10658
10659 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10660 /// vector.  If it is invalid, don't add anything to Ops.
10661 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10662                                                      std::string &Constraint,
10663                                                      std::vector<SDValue>&Ops,
10664                                                      SelectionDAG &DAG) const {
10665   SDValue Result;
10666
10667   // Only support length 1 constraints.
10668   if (Constraint.length() > 1) return;
10669
10670   char Letter = Constraint[0];
10671   switch (Letter) {
10672   default: break;
10673   case 'I':
10674   case 'J':
10675   case 'K':
10676   case 'L':
10677   case 'M':
10678   case 'N':
10679   case 'O':
10680   case 'P': {
10681     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10682     if (!CST) return; // Must be an immediate to match.
10683     int64_t Value = CST->getSExtValue();
10684     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10685                          // numbers are printed as such.
10686     switch (Letter) {
10687     default: llvm_unreachable("Unknown constraint letter!");
10688     case 'I':  // "I" is a signed 16-bit constant.
10689       if (isInt<16>(Value))
10690         Result = DAG.getTargetConstant(Value, TCVT);
10691       break;
10692     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10693       if (isShiftedUInt<16, 16>(Value))
10694         Result = DAG.getTargetConstant(Value, TCVT);
10695       break;
10696     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10697       if (isShiftedInt<16, 16>(Value))
10698         Result = DAG.getTargetConstant(Value, TCVT);
10699       break;
10700     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10701       if (isUInt<16>(Value))
10702         Result = DAG.getTargetConstant(Value, TCVT);
10703       break;
10704     case 'M':  // "M" is a constant that is greater than 31.
10705       if (Value > 31)
10706         Result = DAG.getTargetConstant(Value, TCVT);
10707       break;
10708     case 'N':  // "N" is a positive constant that is an exact power of two.
10709       if (Value > 0 && isPowerOf2_64(Value))
10710         Result = DAG.getTargetConstant(Value, TCVT);
10711       break;
10712     case 'O':  // "O" is the constant zero.
10713       if (Value == 0)
10714         Result = DAG.getTargetConstant(Value, TCVT);
10715       break;
10716     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10717       if (isInt<16>(-Value))
10718         Result = DAG.getTargetConstant(Value, TCVT);
10719       break;
10720     }
10721     break;
10722   }
10723   }
10724
10725   if (Result.getNode()) {
10726     Ops.push_back(Result);
10727     return;
10728   }
10729
10730   // Handle standard constraint letters.
10731   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10732 }
10733
10734 // isLegalAddressingMode - Return true if the addressing mode represented
10735 // by AM is legal for this target, for a load/store of the specified type.
10736 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10737                                               Type *Ty) const {
10738   // PPC does not allow r+i addressing modes for vectors!
10739   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10740     return false;
10741
10742   // PPC allows a sign-extended 16-bit immediate field.
10743   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10744     return false;
10745
10746   // No global is ever allowed as a base.
10747   if (AM.BaseGV)
10748     return false;
10749
10750   // PPC only support r+r,
10751   switch (AM.Scale) {
10752   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10753     break;
10754   case 1:
10755     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10756       return false;
10757     // Otherwise we have r+r or r+i.
10758     break;
10759   case 2:
10760     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10761       return false;
10762     // Allow 2*r as r+r.
10763     break;
10764   default:
10765     // No other scales are supported.
10766     return false;
10767   }
10768
10769   return true;
10770 }
10771
10772 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10773                                            SelectionDAG &DAG) const {
10774   MachineFunction &MF = DAG.getMachineFunction();
10775   MachineFrameInfo *MFI = MF.getFrameInfo();
10776   MFI->setReturnAddressIsTaken(true);
10777
10778   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10779     return SDValue();
10780
10781   SDLoc dl(Op);
10782   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10783
10784   // Make sure the function does not optimize away the store of the RA to
10785   // the stack.
10786   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10787   FuncInfo->setLRStoreRequired();
10788   bool isPPC64 = Subtarget.isPPC64();
10789
10790   if (Depth > 0) {
10791     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10792     SDValue Offset =
10793         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10794                         isPPC64 ? MVT::i64 : MVT::i32);
10795     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10796                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10797                                    FrameAddr, Offset),
10798                        MachinePointerInfo(), false, false, false, 0);
10799   }
10800
10801   // Just load the return address off the stack.
10802   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10803   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10804                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10805 }
10806
10807 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10808                                           SelectionDAG &DAG) const {
10809   SDLoc dl(Op);
10810   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10811
10812   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10813   bool isPPC64 = PtrVT == MVT::i64;
10814
10815   MachineFunction &MF = DAG.getMachineFunction();
10816   MachineFrameInfo *MFI = MF.getFrameInfo();
10817   MFI->setFrameAddressIsTaken(true);
10818
10819   // Naked functions never have a frame pointer, and so we use r1. For all
10820   // other functions, this decision must be delayed until during PEI.
10821   unsigned FrameReg;
10822   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10823     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10824   else
10825     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10826
10827   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10828                                          PtrVT);
10829   while (Depth--)
10830     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10831                             FrameAddr, MachinePointerInfo(), false, false,
10832                             false, 0);
10833   return FrameAddr;
10834 }
10835
10836 // FIXME? Maybe this could be a TableGen attribute on some registers and
10837 // this table could be generated automatically from RegInfo.
10838 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10839                                               EVT VT) const {
10840   bool isPPC64 = Subtarget.isPPC64();
10841   bool isDarwinABI = Subtarget.isDarwinABI();
10842
10843   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10844       (!isPPC64 && VT != MVT::i32))
10845     report_fatal_error("Invalid register global variable type");
10846
10847   bool is64Bit = isPPC64 && VT == MVT::i64;
10848   unsigned Reg = StringSwitch<unsigned>(RegName)
10849                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10850                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10851                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10852                                   (is64Bit ? PPC::X13 : PPC::R13))
10853                    .Default(0);
10854
10855   if (Reg)
10856     return Reg;
10857   report_fatal_error("Invalid register name global variable");
10858 }
10859
10860 bool
10861 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10862   // The PowerPC target isn't yet aware of offsets.
10863   return false;
10864 }
10865
10866 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10867                                            const CallInst &I,
10868                                            unsigned Intrinsic) const {
10869
10870   switch (Intrinsic) {
10871   case Intrinsic::ppc_qpx_qvlfd:
10872   case Intrinsic::ppc_qpx_qvlfs:
10873   case Intrinsic::ppc_qpx_qvlfcd:
10874   case Intrinsic::ppc_qpx_qvlfcs:
10875   case Intrinsic::ppc_qpx_qvlfiwa:
10876   case Intrinsic::ppc_qpx_qvlfiwz:
10877   case Intrinsic::ppc_altivec_lvx:
10878   case Intrinsic::ppc_altivec_lvxl:
10879   case Intrinsic::ppc_altivec_lvebx:
10880   case Intrinsic::ppc_altivec_lvehx:
10881   case Intrinsic::ppc_altivec_lvewx:
10882   case Intrinsic::ppc_vsx_lxvd2x:
10883   case Intrinsic::ppc_vsx_lxvw4x: {
10884     EVT VT;
10885     switch (Intrinsic) {
10886     case Intrinsic::ppc_altivec_lvebx:
10887       VT = MVT::i8;
10888       break;
10889     case Intrinsic::ppc_altivec_lvehx:
10890       VT = MVT::i16;
10891       break;
10892     case Intrinsic::ppc_altivec_lvewx:
10893       VT = MVT::i32;
10894       break;
10895     case Intrinsic::ppc_vsx_lxvd2x:
10896       VT = MVT::v2f64;
10897       break;
10898     case Intrinsic::ppc_qpx_qvlfd:
10899       VT = MVT::v4f64;
10900       break;
10901     case Intrinsic::ppc_qpx_qvlfs:
10902       VT = MVT::v4f32;
10903       break;
10904     case Intrinsic::ppc_qpx_qvlfcd:
10905       VT = MVT::v2f64;
10906       break;
10907     case Intrinsic::ppc_qpx_qvlfcs:
10908       VT = MVT::v2f32;
10909       break;
10910     default:
10911       VT = MVT::v4i32;
10912       break;
10913     }
10914
10915     Info.opc = ISD::INTRINSIC_W_CHAIN;
10916     Info.memVT = VT;
10917     Info.ptrVal = I.getArgOperand(0);
10918     Info.offset = -VT.getStoreSize()+1;
10919     Info.size = 2*VT.getStoreSize()-1;
10920     Info.align = 1;
10921     Info.vol = false;
10922     Info.readMem = true;
10923     Info.writeMem = false;
10924     return true;
10925   }
10926   case Intrinsic::ppc_qpx_qvlfda:
10927   case Intrinsic::ppc_qpx_qvlfsa:
10928   case Intrinsic::ppc_qpx_qvlfcda:
10929   case Intrinsic::ppc_qpx_qvlfcsa:
10930   case Intrinsic::ppc_qpx_qvlfiwaa:
10931   case Intrinsic::ppc_qpx_qvlfiwza: {
10932     EVT VT;
10933     switch (Intrinsic) {
10934     case Intrinsic::ppc_qpx_qvlfda:
10935       VT = MVT::v4f64;
10936       break;
10937     case Intrinsic::ppc_qpx_qvlfsa:
10938       VT = MVT::v4f32;
10939       break;
10940     case Intrinsic::ppc_qpx_qvlfcda:
10941       VT = MVT::v2f64;
10942       break;
10943     case Intrinsic::ppc_qpx_qvlfcsa:
10944       VT = MVT::v2f32;
10945       break;
10946     default:
10947       VT = MVT::v4i32;
10948       break;
10949     }
10950
10951     Info.opc = ISD::INTRINSIC_W_CHAIN;
10952     Info.memVT = VT;
10953     Info.ptrVal = I.getArgOperand(0);
10954     Info.offset = 0;
10955     Info.size = VT.getStoreSize();
10956     Info.align = 1;
10957     Info.vol = false;
10958     Info.readMem = true;
10959     Info.writeMem = false;
10960     return true;
10961   }
10962   case Intrinsic::ppc_qpx_qvstfd:
10963   case Intrinsic::ppc_qpx_qvstfs:
10964   case Intrinsic::ppc_qpx_qvstfcd:
10965   case Intrinsic::ppc_qpx_qvstfcs:
10966   case Intrinsic::ppc_qpx_qvstfiw:
10967   case Intrinsic::ppc_altivec_stvx:
10968   case Intrinsic::ppc_altivec_stvxl:
10969   case Intrinsic::ppc_altivec_stvebx:
10970   case Intrinsic::ppc_altivec_stvehx:
10971   case Intrinsic::ppc_altivec_stvewx:
10972   case Intrinsic::ppc_vsx_stxvd2x:
10973   case Intrinsic::ppc_vsx_stxvw4x: {
10974     EVT VT;
10975     switch (Intrinsic) {
10976     case Intrinsic::ppc_altivec_stvebx:
10977       VT = MVT::i8;
10978       break;
10979     case Intrinsic::ppc_altivec_stvehx:
10980       VT = MVT::i16;
10981       break;
10982     case Intrinsic::ppc_altivec_stvewx:
10983       VT = MVT::i32;
10984       break;
10985     case Intrinsic::ppc_vsx_stxvd2x:
10986       VT = MVT::v2f64;
10987       break;
10988     case Intrinsic::ppc_qpx_qvstfd:
10989       VT = MVT::v4f64;
10990       break;
10991     case Intrinsic::ppc_qpx_qvstfs:
10992       VT = MVT::v4f32;
10993       break;
10994     case Intrinsic::ppc_qpx_qvstfcd:
10995       VT = MVT::v2f64;
10996       break;
10997     case Intrinsic::ppc_qpx_qvstfcs:
10998       VT = MVT::v2f32;
10999       break;
11000     default:
11001       VT = MVT::v4i32;
11002       break;
11003     }
11004
11005     Info.opc = ISD::INTRINSIC_VOID;
11006     Info.memVT = VT;
11007     Info.ptrVal = I.getArgOperand(1);
11008     Info.offset = -VT.getStoreSize()+1;
11009     Info.size = 2*VT.getStoreSize()-1;
11010     Info.align = 1;
11011     Info.vol = false;
11012     Info.readMem = false;
11013     Info.writeMem = true;
11014     return true;
11015   }
11016   case Intrinsic::ppc_qpx_qvstfda:
11017   case Intrinsic::ppc_qpx_qvstfsa:
11018   case Intrinsic::ppc_qpx_qvstfcda:
11019   case Intrinsic::ppc_qpx_qvstfcsa:
11020   case Intrinsic::ppc_qpx_qvstfiwa: {
11021     EVT VT;
11022     switch (Intrinsic) {
11023     case Intrinsic::ppc_qpx_qvstfda:
11024       VT = MVT::v4f64;
11025       break;
11026     case Intrinsic::ppc_qpx_qvstfsa:
11027       VT = MVT::v4f32;
11028       break;
11029     case Intrinsic::ppc_qpx_qvstfcda:
11030       VT = MVT::v2f64;
11031       break;
11032     case Intrinsic::ppc_qpx_qvstfcsa:
11033       VT = MVT::v2f32;
11034       break;
11035     default:
11036       VT = MVT::v4i32;
11037       break;
11038     }
11039
11040     Info.opc = ISD::INTRINSIC_VOID;
11041     Info.memVT = VT;
11042     Info.ptrVal = I.getArgOperand(1);
11043     Info.offset = 0;
11044     Info.size = VT.getStoreSize();
11045     Info.align = 1;
11046     Info.vol = false;
11047     Info.readMem = false;
11048     Info.writeMem = true;
11049     return true;
11050   }
11051   default:
11052     break;
11053   }
11054
11055   return false;
11056 }
11057
11058 /// getOptimalMemOpType - Returns the target specific optimal type for load
11059 /// and store operations as a result of memset, memcpy, and memmove
11060 /// lowering. If DstAlign is zero that means it's safe to destination
11061 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11062 /// means there isn't a need to check it against alignment requirement,
11063 /// probably because the source does not need to be loaded. If 'IsMemset' is
11064 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11065 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11066 /// source is constant so it does not need to be loaded.
11067 /// It returns EVT::Other if the type should be determined using generic
11068 /// target-independent logic.
11069 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11070                                            unsigned DstAlign, unsigned SrcAlign,
11071                                            bool IsMemset, bool ZeroMemset,
11072                                            bool MemcpyStrSrc,
11073                                            MachineFunction &MF) const {
11074   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11075     const Function *F = MF.getFunction();
11076     // When expanding a memset, require at least two QPX instructions to cover
11077     // the cost of loading the value to be stored from the constant pool.
11078     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11079        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11080         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11081       return MVT::v4f64;
11082     }
11083
11084     // We should use Altivec/VSX loads and stores when available. For unaligned
11085     // addresses, unaligned VSX loads are only fast starting with the P8.
11086     if (Subtarget.hasAltivec() && Size >= 16 &&
11087         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11088          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11089       return MVT::v4i32;
11090   }
11091
11092   if (Subtarget.isPPC64()) {
11093     return MVT::i64;
11094   }
11095
11096   return MVT::i32;
11097 }
11098
11099 /// \brief Returns true if it is beneficial to convert a load of a constant
11100 /// to just the constant itself.
11101 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11102                                                           Type *Ty) const {
11103   assert(Ty->isIntegerTy());
11104
11105   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11106   if (BitSize == 0 || BitSize > 64)
11107     return false;
11108   return true;
11109 }
11110
11111 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11112   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11113     return false;
11114   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11115   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11116   return NumBits1 == 64 && NumBits2 == 32;
11117 }
11118
11119 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11120   if (!VT1.isInteger() || !VT2.isInteger())
11121     return false;
11122   unsigned NumBits1 = VT1.getSizeInBits();
11123   unsigned NumBits2 = VT2.getSizeInBits();
11124   return NumBits1 == 64 && NumBits2 == 32;
11125 }
11126
11127 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11128   // Generally speaking, zexts are not free, but they are free when they can be
11129   // folded with other operations.
11130   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11131     EVT MemVT = LD->getMemoryVT();
11132     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11133          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11134         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11135          LD->getExtensionType() == ISD::ZEXTLOAD))
11136       return true;
11137   }
11138
11139   // FIXME: Add other cases...
11140   //  - 32-bit shifts with a zext to i64
11141   //  - zext after ctlz, bswap, etc.
11142   //  - zext after and by a constant mask
11143
11144   return TargetLowering::isZExtFree(Val, VT2);
11145 }
11146
11147 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11148   assert(VT.isFloatingPoint());
11149   return true;
11150 }
11151
11152 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11153   return isInt<16>(Imm) || isUInt<16>(Imm);
11154 }
11155
11156 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11157   return isInt<16>(Imm) || isUInt<16>(Imm);
11158 }
11159
11160 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11161                                                        unsigned,
11162                                                        unsigned,
11163                                                        bool *Fast) const {
11164   if (DisablePPCUnaligned)
11165     return false;
11166
11167   // PowerPC supports unaligned memory access for simple non-vector types.
11168   // Although accessing unaligned addresses is not as efficient as accessing
11169   // aligned addresses, it is generally more efficient than manual expansion,
11170   // and generally only traps for software emulation when crossing page
11171   // boundaries.
11172
11173   if (!VT.isSimple())
11174     return false;
11175
11176   if (VT.getSimpleVT().isVector()) {
11177     if (Subtarget.hasVSX()) {
11178       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11179           VT != MVT::v4f32 && VT != MVT::v4i32)
11180         return false;
11181     } else {
11182       return false;
11183     }
11184   }
11185
11186   if (VT == MVT::ppcf128)
11187     return false;
11188
11189   if (Fast)
11190     *Fast = true;
11191
11192   return true;
11193 }
11194
11195 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11196   VT = VT.getScalarType();
11197
11198   if (!VT.isSimple())
11199     return false;
11200
11201   switch (VT.getSimpleVT().SimpleTy) {
11202   case MVT::f32:
11203   case MVT::f64:
11204     return true;
11205   default:
11206     break;
11207   }
11208
11209   return false;
11210 }
11211
11212 const MCPhysReg *
11213 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11214   // LR is a callee-save register, but we must treat it as clobbered by any call
11215   // site. Hence we include LR in the scratch registers, which are in turn added
11216   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11217   // to CTR, which is used by any indirect call.
11218   static const MCPhysReg ScratchRegs[] = {
11219     PPC::X12, PPC::LR8, PPC::CTR8, 0
11220   };
11221
11222   return ScratchRegs;
11223 }
11224
11225 bool
11226 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11227                      EVT VT , unsigned DefinedValues) const {
11228   if (VT == MVT::v2i64)
11229     return false;
11230
11231   if (Subtarget.hasQPX()) {
11232     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11233       return true;
11234   }
11235
11236   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11237 }
11238
11239 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11240   if (DisableILPPref || Subtarget.enableMachineScheduler())
11241     return TargetLowering::getSchedulingPreference(N);
11242
11243   return Sched::ILP;
11244 }
11245
11246 // Create a fast isel object.
11247 FastISel *
11248 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11249                                   const TargetLibraryInfo *LibInfo) const {
11250   return PPC::createFastISel(FuncInfo, LibInfo);
11251 }