ff5a0d5afbd1e5ea92b0219a252c736a0b374e44
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
50
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
53
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
56
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
59
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
61                                      const PPCSubtarget &STI)
62     : TargetLowering(TM), Subtarget(STI) {
63   // Use _setjmp/_longjmp instead of setjmp/longjmp.
64   setUseUnderscoreSetJmp(true);
65   setUseUnderscoreLongJmp(true);
66
67   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68   // arguments are at least 4/8 bytes aligned.
69   bool isPPC64 = Subtarget.isPPC64();
70   setMinStackArgumentAlignment(isPPC64 ? 8:4);
71
72   // Set up the register classes.
73   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76
77   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78   for (MVT VT : MVT::integer_valuetypes()) {
79     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
81   }
82
83   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
84
85   // PowerPC has pre-inc load and store's.
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
93   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
100
101   if (Subtarget.useCRBits()) {
102     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
103
104     if (isPPC64 || Subtarget.hasFPCVT()) {
105       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
106       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
107                          isPPC64 ? MVT::i64 : MVT::i32);
108       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
109       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
110                          isPPC64 ? MVT::i64 : MVT::i32);
111     } else {
112       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
113       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
114     }
115
116     // PowerPC does not support direct load / store of condition registers
117     setOperationAction(ISD::LOAD, MVT::i1, Custom);
118     setOperationAction(ISD::STORE, MVT::i1, Custom);
119
120     // FIXME: Remove this once the ANDI glue bug is fixed:
121     if (ANDIGlueBug)
122       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
123
124     for (MVT VT : MVT::integer_valuetypes()) {
125       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
126       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
127       setTruncStoreAction(VT, MVT::i1, Expand);
128     }
129
130     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
131   }
132
133   // This is used in the ppcf128->int sequence.  Note it has different semantics
134   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
135   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
136
137   // We do not currently implement these libm ops for PowerPC.
138   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
140   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
142   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
144
145   // PowerPC has no SREM/UREM instructions
146   setOperationAction(ISD::SREM, MVT::i32, Expand);
147   setOperationAction(ISD::UREM, MVT::i32, Expand);
148   setOperationAction(ISD::SREM, MVT::i64, Expand);
149   setOperationAction(ISD::UREM, MVT::i64, Expand);
150
151   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
160
161   // We don't support sin/cos/sqrt/fmod/pow
162   setOperationAction(ISD::FSIN , MVT::f64, Expand);
163   setOperationAction(ISD::FCOS , MVT::f64, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165   setOperationAction(ISD::FREM , MVT::f64, Expand);
166   setOperationAction(ISD::FPOW , MVT::f64, Expand);
167   setOperationAction(ISD::FMA  , MVT::f64, Legal);
168   setOperationAction(ISD::FSIN , MVT::f32, Expand);
169   setOperationAction(ISD::FCOS , MVT::f32, Expand);
170   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171   setOperationAction(ISD::FREM , MVT::f32, Expand);
172   setOperationAction(ISD::FPOW , MVT::f32, Expand);
173   setOperationAction(ISD::FMA  , MVT::f32, Legal);
174
175   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
176
177   // If we're enabling GP optimizations, use hardware square root
178   if (!Subtarget.hasFSQRT() &&
179       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
180         Subtarget.hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget.hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
185         Subtarget.hasFRES()))
186     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
187
188   if (Subtarget.hasFCPSGN()) {
189     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
191   } else {
192     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
194   }
195
196   if (Subtarget.hasFPRND()) {
197     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
199     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200     setOperationAction(ISD::FROUND, MVT::f64, Legal);
201
202     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
204     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205     setOperationAction(ISD::FROUND, MVT::f32, Legal);
206   }
207
208   // PowerPC does not have BSWAP, CTPOP or CTTZ
209   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
210   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
214   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
217
218   if (Subtarget.hasPOPCNTD()) {
219     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
220     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
221   } else {
222     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
223     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
224   }
225
226   // PowerPC does not have ROTR
227   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
228   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
229
230   if (!Subtarget.useCRBits()) {
231     // PowerPC does not have Select
232     setOperationAction(ISD::SELECT, MVT::i32, Expand);
233     setOperationAction(ISD::SELECT, MVT::i64, Expand);
234     setOperationAction(ISD::SELECT, MVT::f32, Expand);
235     setOperationAction(ISD::SELECT, MVT::f64, Expand);
236   }
237
238   // PowerPC wants to turn select_cc of FP into fsel when possible.
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
241
242   // PowerPC wants to optimize integer setcc a bit
243   if (!Subtarget.useCRBits())
244     setOperationAction(ISD::SETCC, MVT::i32, Custom);
245
246   // PowerPC does not have BRCOND which requires SetCC
247   if (!Subtarget.useCRBits())
248     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
249
250   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
251
252   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254
255   // PowerPC does not have [U|S]INT_TO_FP
256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
258
259   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
263
264   // We cannot sextinreg(i1).  Expand to shifts.
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
266
267   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269   // support continuation, user-level threading, and etc.. As a result, no
270   // other SjLj exception interfaces are implemented and please don't build
271   // your own exception handling based on them.
272   // LLVM/Clang supports zero-cost DWARF exception handling.
273   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
275
276   // We want to legalize GlobalAddress and ConstantPool nodes into the
277   // appropriate instructions to materialize the address.
278   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
281   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
282   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
283   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
286   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
287   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
288
289   // TRAP is legal.
290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
291
292   // TRAMPOLINE is custom lowered.
293   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
295
296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
298
299   if (Subtarget.isSVR4ABI()) {
300     if (isPPC64) {
301       // VAARG always uses double-word chunks, so promote anything smaller.
302       setOperationAction(ISD::VAARG, MVT::i1, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::i8, Promote);
305       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306       setOperationAction(ISD::VAARG, MVT::i16, Promote);
307       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308       setOperationAction(ISD::VAARG, MVT::i32, Promote);
309       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310       setOperationAction(ISD::VAARG, MVT::Other, Expand);
311     } else {
312       // VAARG is custom lowered with the 32-bit SVR4 ABI.
313       setOperationAction(ISD::VAARG, MVT::Other, Custom);
314       setOperationAction(ISD::VAARG, MVT::i64, Custom);
315     }
316   } else
317     setOperationAction(ISD::VAARG, MVT::Other, Expand);
318
319   if (Subtarget.isSVR4ABI() && !isPPC64)
320     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
322   else
323     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
324
325   // Use the default implementation.
326   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
327   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
328   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
329   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
331
332   // We want to custom lower some of our intrinsics.
333   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
334
335   // To handle counter-based loop conditions.
336   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
337
338   // Comparisons that require checking two conditions.
339   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
351
352   if (Subtarget.has64BitSupport()) {
353     // They also have instructions for converting between i64 and fp.
354     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358     // This is just the low 32 bits of a (signed) fp->i64 conversion.
359     // We cannot do this with Promote because i64 is not a legal type.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
361
362     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
364   } else {
365     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
367   }
368
369   // With the instructions enabled under FPCVT, we can do everything.
370   if (Subtarget.hasFPCVT()) {
371     if (Subtarget.has64BitSupport()) {
372       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
376     }
377
378     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
382   }
383
384   if (Subtarget.use64BitRegs()) {
385     // 64-bit PowerPC implementations can support i64 types directly
386     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389     // 64-bit PowerPC wants to expand i128 shifts itself.
390     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
393   } else {
394     // 32-bit PowerPC wants to expand i64 shifts itself.
395     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
398   }
399
400   if (Subtarget.hasAltivec()) {
401     // First set operation action for all vector types to expand. Then we
402     // will selectively turn on ones that can be effectively codegen'd.
403     for (MVT VT : MVT::vector_valuetypes()) {
404       // add/sub are legal for all supported vector VT's.
405       setOperationAction(ISD::ADD , VT, Legal);
406       setOperationAction(ISD::SUB , VT, Legal);
407
408       // Vector instructions introduced in P8
409       if (Subtarget.hasP8Altivec()) {
410         setOperationAction(ISD::CTPOP, VT, Legal);
411         setOperationAction(ISD::CTLZ, VT, Legal);
412       }
413       else {
414         setOperationAction(ISD::CTPOP, VT, Expand);
415         setOperationAction(ISD::CTLZ, VT, Expand);
416       }
417
418       // We promote all shuffles to v16i8.
419       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
420       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
421
422       // We promote all non-typed operations to v4i32.
423       setOperationAction(ISD::AND   , VT, Promote);
424       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
425       setOperationAction(ISD::OR    , VT, Promote);
426       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
427       setOperationAction(ISD::XOR   , VT, Promote);
428       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
429       setOperationAction(ISD::LOAD  , VT, Promote);
430       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
431       setOperationAction(ISD::SELECT, VT, Promote);
432       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
433       setOperationAction(ISD::STORE, VT, Promote);
434       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
435
436       // No other operations are legal.
437       setOperationAction(ISD::MUL , VT, Expand);
438       setOperationAction(ISD::SDIV, VT, Expand);
439       setOperationAction(ISD::SREM, VT, Expand);
440       setOperationAction(ISD::UDIV, VT, Expand);
441       setOperationAction(ISD::UREM, VT, Expand);
442       setOperationAction(ISD::FDIV, VT, Expand);
443       setOperationAction(ISD::FREM, VT, Expand);
444       setOperationAction(ISD::FNEG, VT, Expand);
445       setOperationAction(ISD::FSQRT, VT, Expand);
446       setOperationAction(ISD::FLOG, VT, Expand);
447       setOperationAction(ISD::FLOG10, VT, Expand);
448       setOperationAction(ISD::FLOG2, VT, Expand);
449       setOperationAction(ISD::FEXP, VT, Expand);
450       setOperationAction(ISD::FEXP2, VT, Expand);
451       setOperationAction(ISD::FSIN, VT, Expand);
452       setOperationAction(ISD::FCOS, VT, Expand);
453       setOperationAction(ISD::FABS, VT, Expand);
454       setOperationAction(ISD::FPOWI, VT, Expand);
455       setOperationAction(ISD::FFLOOR, VT, Expand);
456       setOperationAction(ISD::FCEIL,  VT, Expand);
457       setOperationAction(ISD::FTRUNC, VT, Expand);
458       setOperationAction(ISD::FRINT,  VT, Expand);
459       setOperationAction(ISD::FNEARBYINT, VT, Expand);
460       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
461       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
462       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
463       setOperationAction(ISD::MULHU, VT, Expand);
464       setOperationAction(ISD::MULHS, VT, Expand);
465       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
466       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
467       setOperationAction(ISD::UDIVREM, VT, Expand);
468       setOperationAction(ISD::SDIVREM, VT, Expand);
469       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
470       setOperationAction(ISD::FPOW, VT, Expand);
471       setOperationAction(ISD::BSWAP, VT, Expand);
472       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
473       setOperationAction(ISD::CTTZ, VT, Expand);
474       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
475       setOperationAction(ISD::VSELECT, VT, Expand);
476       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
477
478       for (MVT InnerVT : MVT::vector_valuetypes()) {
479         setTruncStoreAction(VT, InnerVT, Expand);
480         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
481         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
482         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
483       }
484     }
485
486     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
487     // with merges, splats, etc.
488     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
489
490     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
491     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
492     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
493     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
494     setOperationAction(ISD::SELECT, MVT::v4i32,
495                        Subtarget.useCRBits() ? Legal : Expand);
496     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
497     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
498     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
499     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
500     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
501     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
502     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
503     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
504     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
505
506     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
507     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
508     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
509     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
510
511     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
512     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
513
514     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
515       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
516       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
517     }
518
519     
520     if (Subtarget.hasP8Altivec()) 
521       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
522     else
523       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
524       
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
527
528     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
529     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
530
531     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
532     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
533     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
534     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
535
536     // Altivec does not contain unordered floating-point compare instructions
537     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
538     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
539     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
540     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
541
542     if (Subtarget.hasVSX()) {
543       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
544       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
545
546       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
547       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
548       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
549       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
550       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
551
552       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
553
554       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
555       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
556
557       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
558       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
559
560       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
561       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
562       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
563       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
564       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
565
566       // Share the Altivec comparison restrictions.
567       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
568       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
569       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
570       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
571
572       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
573       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
574
575       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
576
577       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
578
579       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
580       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
581
582       if (Subtarget.hasP8Altivec()) {
583         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
584         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
585         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
586
587         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
588       }
589       else {
590         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
591         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
592         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
593
594         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
595
596         // VSX v2i64 only supports non-arithmetic operations.
597         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
598         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
599       }
600
601       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
602       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
603       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
604       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
605
606       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
607
608       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
609       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
610       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
611       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
612
613       // Vector operation legalization checks the result type of
614       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
615       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
616       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
617       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
618       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
619
620       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
621     }
622
623     if (Subtarget.hasP8Altivec()) 
624       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
625   }
626
627   if (Subtarget.hasQPX()) {
628     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
629     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
630     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
631     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
632
633     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
634     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
635
636     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
637     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
638
639     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
640     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
641
642     if (!Subtarget.useCRBits())
643       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
644     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
645
646     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
647     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
648     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
649     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
650     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
651     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
652     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
653
654     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
655     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
656
657     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
658     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
659     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
660
661     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
662     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
663     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
664     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
665     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
666     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
667     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
668     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
669     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
670     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
671     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
672
673     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
674     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
675
676     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
677     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
678
679     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
680
681     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
682     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
683     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
684     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
685
686     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
687     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
688
689     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
690     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
691
692     if (!Subtarget.useCRBits())
693       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
694     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
695
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
697     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
698     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
699     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
700     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
701     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
702     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
703
704     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
705     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
706
707     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
708     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
709     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
710     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
711     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
712     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
713     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
714     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
715     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
716     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
717     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
718
719     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
720     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
721
722     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
723     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
724
725     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
726
727     setOperationAction(ISD::AND , MVT::v4i1, Legal);
728     setOperationAction(ISD::OR , MVT::v4i1, Legal);
729     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
730
731     if (!Subtarget.useCRBits())
732       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
733     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
734
735     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
736     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
737
738     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
739     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
740     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
741     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
742     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
743     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
744     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
745
746     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
747     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
748
749     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
750
751     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
752     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
753     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
754     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
755
756     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
757     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
758     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
759     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
760
761     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
762     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
763
764     // These need to set FE_INEXACT, and so cannot be vectorized here.
765     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
766     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
767
768     if (TM.Options.UnsafeFPMath) {
769       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
770       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
771
772       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
773       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
774     } else {
775       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
776       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
777
778       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
779       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
780     }
781   }
782
783   if (Subtarget.has64BitSupport())
784     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
785
786   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
787
788   if (!isPPC64) {
789     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
790     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
791   }
792
793   setBooleanContents(ZeroOrOneBooleanContent);
794
795   if (Subtarget.hasAltivec()) {
796     // Altivec instructions set fields to all zeros or all ones.
797     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
798   }
799
800   if (!isPPC64) {
801     // These libcalls are not available in 32-bit.
802     setLibcallName(RTLIB::SHL_I128, nullptr);
803     setLibcallName(RTLIB::SRL_I128, nullptr);
804     setLibcallName(RTLIB::SRA_I128, nullptr);
805   }
806
807   if (isPPC64) {
808     setStackPointerRegisterToSaveRestore(PPC::X1);
809     setExceptionPointerRegister(PPC::X3);
810     setExceptionSelectorRegister(PPC::X4);
811   } else {
812     setStackPointerRegisterToSaveRestore(PPC::R1);
813     setExceptionPointerRegister(PPC::R3);
814     setExceptionSelectorRegister(PPC::R4);
815   }
816
817   // We have target-specific dag combine patterns for the following nodes:
818   setTargetDAGCombine(ISD::SINT_TO_FP);
819   if (Subtarget.hasFPCVT())
820     setTargetDAGCombine(ISD::UINT_TO_FP);
821   setTargetDAGCombine(ISD::LOAD);
822   setTargetDAGCombine(ISD::STORE);
823   setTargetDAGCombine(ISD::BR_CC);
824   if (Subtarget.useCRBits())
825     setTargetDAGCombine(ISD::BRCOND);
826   setTargetDAGCombine(ISD::BSWAP);
827   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
828   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
829   setTargetDAGCombine(ISD::INTRINSIC_VOID);
830
831   setTargetDAGCombine(ISD::SIGN_EXTEND);
832   setTargetDAGCombine(ISD::ZERO_EXTEND);
833   setTargetDAGCombine(ISD::ANY_EXTEND);
834
835   if (Subtarget.useCRBits()) {
836     setTargetDAGCombine(ISD::TRUNCATE);
837     setTargetDAGCombine(ISD::SETCC);
838     setTargetDAGCombine(ISD::SELECT_CC);
839   }
840
841   // Use reciprocal estimates.
842   if (TM.Options.UnsafeFPMath) {
843     setTargetDAGCombine(ISD::FDIV);
844     setTargetDAGCombine(ISD::FSQRT);
845   }
846
847   // Darwin long double math library functions have $LDBL128 appended.
848   if (Subtarget.isDarwin()) {
849     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
850     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
851     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
852     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
853     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
854     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
855     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
856     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
857     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
858     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
859   }
860
861   // With 32 condition bits, we don't need to sink (and duplicate) compares
862   // aggressively in CodeGenPrep.
863   if (Subtarget.useCRBits()) {
864     setHasMultipleConditionRegisters();
865     setJumpIsExpensive();
866   }
867
868   setMinFunctionAlignment(2);
869   if (Subtarget.isDarwin())
870     setPrefFunctionAlignment(4);
871
872   switch (Subtarget.getDarwinDirective()) {
873   default: break;
874   case PPC::DIR_970:
875   case PPC::DIR_A2:
876   case PPC::DIR_E500mc:
877   case PPC::DIR_E5500:
878   case PPC::DIR_PWR4:
879   case PPC::DIR_PWR5:
880   case PPC::DIR_PWR5X:
881   case PPC::DIR_PWR6:
882   case PPC::DIR_PWR6X:
883   case PPC::DIR_PWR7:
884   case PPC::DIR_PWR8:
885     setPrefFunctionAlignment(4);
886     setPrefLoopAlignment(4);
887     break;
888   }
889
890   setInsertFencesForAtomic(true);
891
892   if (Subtarget.enableMachineScheduler())
893     setSchedulingPreference(Sched::Source);
894   else
895     setSchedulingPreference(Sched::Hybrid);
896
897   computeRegisterProperties(STI.getRegisterInfo());
898
899   // The Freescale cores do better with aggressive inlining of memcpy and
900   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
901   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
902       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
903     MaxStoresPerMemset = 32;
904     MaxStoresPerMemsetOptSize = 16;
905     MaxStoresPerMemcpy = 32;
906     MaxStoresPerMemcpyOptSize = 8;
907     MaxStoresPerMemmove = 32;
908     MaxStoresPerMemmoveOptSize = 8;
909   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
910     // The A2 also benefits from (very) aggressive inlining of memcpy and
911     // friends. The overhead of a the function call, even when warm, can be
912     // over one hundred cycles.
913     MaxStoresPerMemset = 128;
914     MaxStoresPerMemcpy = 128;
915     MaxStoresPerMemmove = 128;
916   }
917 }
918
919 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
920 /// the desired ByVal argument alignment.
921 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
922                              unsigned MaxMaxAlign) {
923   if (MaxAlign == MaxMaxAlign)
924     return;
925   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
926     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
927       MaxAlign = 32;
928     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
929       MaxAlign = 16;
930   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
931     unsigned EltAlign = 0;
932     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
933     if (EltAlign > MaxAlign)
934       MaxAlign = EltAlign;
935   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
936     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
937       unsigned EltAlign = 0;
938       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
939       if (EltAlign > MaxAlign)
940         MaxAlign = EltAlign;
941       if (MaxAlign == MaxMaxAlign)
942         break;
943     }
944   }
945 }
946
947 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
948 /// function arguments in the caller parameter area.
949 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
950   // Darwin passes everything on 4 byte boundary.
951   if (Subtarget.isDarwin())
952     return 4;
953
954   // 16byte and wider vectors are passed on 16byte boundary.
955   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
956   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
957   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
958     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
959   return Align;
960 }
961
962 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
963   switch (Opcode) {
964   default: return nullptr;
965   case PPCISD::FSEL:            return "PPCISD::FSEL";
966   case PPCISD::FCFID:           return "PPCISD::FCFID";
967   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
968   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
969   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
970   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
971   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
972   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
973   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
974   case PPCISD::FRE:             return "PPCISD::FRE";
975   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
976   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
977   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
978   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
979   case PPCISD::VPERM:           return "PPCISD::VPERM";
980   case PPCISD::CMPB:            return "PPCISD::CMPB";
981   case PPCISD::Hi:              return "PPCISD::Hi";
982   case PPCISD::Lo:              return "PPCISD::Lo";
983   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
984   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
985   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
986   case PPCISD::SRL:             return "PPCISD::SRL";
987   case PPCISD::SRA:             return "PPCISD::SRA";
988   case PPCISD::SHL:             return "PPCISD::SHL";
989   case PPCISD::CALL:            return "PPCISD::CALL";
990   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
991   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
992   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
993   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
994   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
995   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
996   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
997   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
998   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
999   case PPCISD::VCMP:            return "PPCISD::VCMP";
1000   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1001   case PPCISD::LBRX:            return "PPCISD::LBRX";
1002   case PPCISD::STBRX:           return "PPCISD::STBRX";
1003   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1004   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1005   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1006   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1007   case PPCISD::BDZ:             return "PPCISD::BDZ";
1008   case PPCISD::MFFS:            return "PPCISD::MFFS";
1009   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1010   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1011   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1012   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1013   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1014   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1015   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1016   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1017   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1018   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1019   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1020   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1021   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1022   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1023   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1024   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1025   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1026   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1027   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1028   case PPCISD::SC:              return "PPCISD::SC";
1029   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1030   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1031   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1032   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1033   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1034   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1035   }
1036 }
1037
1038 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1039   if (!VT.isVector())
1040     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1041
1042   if (Subtarget.hasQPX())
1043     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1044
1045   return VT.changeVectorElementTypeToInteger();
1046 }
1047
1048 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1049   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1050   return true;
1051 }
1052
1053 //===----------------------------------------------------------------------===//
1054 // Node matching predicates, for use by the tblgen matching code.
1055 //===----------------------------------------------------------------------===//
1056
1057 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1058 static bool isFloatingPointZero(SDValue Op) {
1059   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1060     return CFP->getValueAPF().isZero();
1061   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1062     // Maybe this has already been legalized into the constant pool?
1063     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1064       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1065         return CFP->getValueAPF().isZero();
1066   }
1067   return false;
1068 }
1069
1070 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1071 /// true if Op is undef or if it matches the specified value.
1072 static bool isConstantOrUndef(int Op, int Val) {
1073   return Op < 0 || Op == Val;
1074 }
1075
1076 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1077 /// VPKUHUM instruction.
1078 /// The ShuffleKind distinguishes between big-endian operations with
1079 /// two different inputs (0), either-endian operations with two identical
1080 /// inputs (1), and little-endian operantion with two different inputs (2).
1081 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1082 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1083                                SelectionDAG &DAG) {
1084   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1085   if (ShuffleKind == 0) {
1086     if (IsLE)
1087       return false;
1088     for (unsigned i = 0; i != 16; ++i)
1089       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1090         return false;
1091   } else if (ShuffleKind == 2) {
1092     if (!IsLE)
1093       return false;
1094     for (unsigned i = 0; i != 16; ++i)
1095       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1096         return false;
1097   } else if (ShuffleKind == 1) {
1098     unsigned j = IsLE ? 0 : 1;
1099     for (unsigned i = 0; i != 8; ++i)
1100       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1101           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1102         return false;
1103   }
1104   return true;
1105 }
1106
1107 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1108 /// VPKUWUM instruction.
1109 /// The ShuffleKind distinguishes between big-endian operations with
1110 /// two different inputs (0), either-endian operations with two identical
1111 /// inputs (1), and little-endian operantion with two different inputs (2).
1112 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1113 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1114                                SelectionDAG &DAG) {
1115   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1116   if (ShuffleKind == 0) {
1117     if (IsLE)
1118       return false;
1119     for (unsigned i = 0; i != 16; i += 2)
1120       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1121           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1122         return false;
1123   } else if (ShuffleKind == 2) {
1124     if (!IsLE)
1125       return false;
1126     for (unsigned i = 0; i != 16; i += 2)
1127       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1128           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1129         return false;
1130   } else if (ShuffleKind == 1) {
1131     unsigned j = IsLE ? 0 : 2;
1132     for (unsigned i = 0; i != 8; i += 2)
1133       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1134           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1135           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1136           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1137         return false;
1138   }
1139   return true;
1140 }
1141
1142 /// isVMerge - Common function, used to match vmrg* shuffles.
1143 ///
1144 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1145                      unsigned LHSStart, unsigned RHSStart) {
1146   if (N->getValueType(0) != MVT::v16i8)
1147     return false;
1148   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1149          "Unsupported merge size!");
1150
1151   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1152     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1153       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1154                              LHSStart+j+i*UnitSize) ||
1155           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1156                              RHSStart+j+i*UnitSize))
1157         return false;
1158     }
1159   return true;
1160 }
1161
1162 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1163 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1164 /// The ShuffleKind distinguishes between big-endian merges with two 
1165 /// different inputs (0), either-endian merges with two identical inputs (1),
1166 /// and little-endian merges with two different inputs (2).  For the latter,
1167 /// the input operands are swapped (see PPCInstrAltivec.td).
1168 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1169                              unsigned ShuffleKind, SelectionDAG &DAG) {
1170   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1171     if (ShuffleKind == 1) // unary
1172       return isVMerge(N, UnitSize, 0, 0);
1173     else if (ShuffleKind == 2) // swapped
1174       return isVMerge(N, UnitSize, 0, 16);
1175     else
1176       return false;
1177   } else {
1178     if (ShuffleKind == 1) // unary
1179       return isVMerge(N, UnitSize, 8, 8);
1180     else if (ShuffleKind == 0) // normal
1181       return isVMerge(N, UnitSize, 8, 24);
1182     else
1183       return false;
1184   }
1185 }
1186
1187 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1188 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1189 /// The ShuffleKind distinguishes between big-endian merges with two 
1190 /// different inputs (0), either-endian merges with two identical inputs (1),
1191 /// and little-endian merges with two different inputs (2).  For the latter,
1192 /// the input operands are swapped (see PPCInstrAltivec.td).
1193 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1194                              unsigned ShuffleKind, SelectionDAG &DAG) {
1195   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1196     if (ShuffleKind == 1) // unary
1197       return isVMerge(N, UnitSize, 8, 8);
1198     else if (ShuffleKind == 2) // swapped
1199       return isVMerge(N, UnitSize, 8, 24);
1200     else
1201       return false;
1202   } else {
1203     if (ShuffleKind == 1) // unary
1204       return isVMerge(N, UnitSize, 0, 0);
1205     else if (ShuffleKind == 0) // normal
1206       return isVMerge(N, UnitSize, 0, 16);
1207     else
1208       return false;
1209   }
1210 }
1211
1212
1213 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1214 /// amount, otherwise return -1.
1215 /// The ShuffleKind distinguishes between big-endian operations with two 
1216 /// different inputs (0), either-endian operations with two identical inputs
1217 /// (1), and little-endian operations with two different inputs (2).  For the
1218 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1219 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1220                              SelectionDAG &DAG) {
1221   if (N->getValueType(0) != MVT::v16i8)
1222     return -1;
1223
1224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1225
1226   // Find the first non-undef value in the shuffle mask.
1227   unsigned i;
1228   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1229     /*search*/;
1230
1231   if (i == 16) return -1;  // all undef.
1232
1233   // Otherwise, check to see if the rest of the elements are consecutively
1234   // numbered from this value.
1235   unsigned ShiftAmt = SVOp->getMaskElt(i);
1236   if (ShiftAmt < i) return -1;
1237
1238   ShiftAmt -= i;
1239   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1240
1241   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1242     // Check the rest of the elements to see if they are consecutive.
1243     for (++i; i != 16; ++i)
1244       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1245         return -1;
1246   } else if (ShuffleKind == 1) {
1247     // Check the rest of the elements to see if they are consecutive.
1248     for (++i; i != 16; ++i)
1249       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1250         return -1;
1251   } else
1252     return -1;
1253
1254   if (ShuffleKind == 2 && isLE)
1255     ShiftAmt = 16 - ShiftAmt;
1256
1257   return ShiftAmt;
1258 }
1259
1260 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1261 /// specifies a splat of a single element that is suitable for input to
1262 /// VSPLTB/VSPLTH/VSPLTW.
1263 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1264   assert(N->getValueType(0) == MVT::v16i8 &&
1265          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1266
1267   // This is a splat operation if each element of the permute is the same, and
1268   // if the value doesn't reference the second vector.
1269   unsigned ElementBase = N->getMaskElt(0);
1270
1271   // FIXME: Handle UNDEF elements too!
1272   if (ElementBase >= 16)
1273     return false;
1274
1275   // Check that the indices are consecutive, in the case of a multi-byte element
1276   // splatted with a v16i8 mask.
1277   for (unsigned i = 1; i != EltSize; ++i)
1278     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1279       return false;
1280
1281   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1282     if (N->getMaskElt(i) < 0) continue;
1283     for (unsigned j = 0; j != EltSize; ++j)
1284       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1285         return false;
1286   }
1287   return true;
1288 }
1289
1290 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1291 /// are -0.0.
1292 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1293   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1294
1295   APInt APVal, APUndef;
1296   unsigned BitSize;
1297   bool HasAnyUndefs;
1298
1299   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1300     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1301       return CFP->getValueAPF().isNegZero();
1302
1303   return false;
1304 }
1305
1306 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1307 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1308 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1309                                 SelectionDAG &DAG) {
1310   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1311   assert(isSplatShuffleMask(SVOp, EltSize));
1312   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1313     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1314   else
1315     return SVOp->getMaskElt(0) / EltSize;
1316 }
1317
1318 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1319 /// by using a vspltis[bhw] instruction of the specified element size, return
1320 /// the constant being splatted.  The ByteSize field indicates the number of
1321 /// bytes of each element [124] -> [bhw].
1322 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1323   SDValue OpVal(nullptr, 0);
1324
1325   // If ByteSize of the splat is bigger than the element size of the
1326   // build_vector, then we have a case where we are checking for a splat where
1327   // multiple elements of the buildvector are folded together into a single
1328   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1329   unsigned EltSize = 16/N->getNumOperands();
1330   if (EltSize < ByteSize) {
1331     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1332     SDValue UniquedVals[4];
1333     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1334
1335     // See if all of the elements in the buildvector agree across.
1336     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1337       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1338       // If the element isn't a constant, bail fully out.
1339       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1340
1341
1342       if (!UniquedVals[i&(Multiple-1)].getNode())
1343         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1344       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1345         return SDValue();  // no match.
1346     }
1347
1348     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1349     // either constant or undef values that are identical for each chunk.  See
1350     // if these chunks can form into a larger vspltis*.
1351
1352     // Check to see if all of the leading entries are either 0 or -1.  If
1353     // neither, then this won't fit into the immediate field.
1354     bool LeadingZero = true;
1355     bool LeadingOnes = true;
1356     for (unsigned i = 0; i != Multiple-1; ++i) {
1357       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1358
1359       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1360       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1361     }
1362     // Finally, check the least significant entry.
1363     if (LeadingZero) {
1364       if (!UniquedVals[Multiple-1].getNode())
1365         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1366       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1367       if (Val < 16)
1368         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1369     }
1370     if (LeadingOnes) {
1371       if (!UniquedVals[Multiple-1].getNode())
1372         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1373       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1374       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1375         return DAG.getTargetConstant(Val, MVT::i32);
1376     }
1377
1378     return SDValue();
1379   }
1380
1381   // Check to see if this buildvec has a single non-undef value in its elements.
1382   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1383     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1384     if (!OpVal.getNode())
1385       OpVal = N->getOperand(i);
1386     else if (OpVal != N->getOperand(i))
1387       return SDValue();
1388   }
1389
1390   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1391
1392   unsigned ValSizeInBytes = EltSize;
1393   uint64_t Value = 0;
1394   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1395     Value = CN->getZExtValue();
1396   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1397     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1398     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1399   }
1400
1401   // If the splat value is larger than the element value, then we can never do
1402   // this splat.  The only case that we could fit the replicated bits into our
1403   // immediate field for would be zero, and we prefer to use vxor for it.
1404   if (ValSizeInBytes < ByteSize) return SDValue();
1405
1406   // If the element value is larger than the splat value, cut it in half and
1407   // check to see if the two halves are equal.  Continue doing this until we
1408   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1409   while (ValSizeInBytes > ByteSize) {
1410     ValSizeInBytes >>= 1;
1411
1412     // If the top half equals the bottom half, we're still ok.
1413     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1414          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1415       return SDValue();
1416   }
1417
1418   // Properly sign extend the value.
1419   int MaskVal = SignExtend32(Value, ByteSize * 8);
1420
1421   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1422   if (MaskVal == 0) return SDValue();
1423
1424   // Finally, if this value fits in a 5 bit sext field, return it
1425   if (SignExtend32<5>(MaskVal) == MaskVal)
1426     return DAG.getTargetConstant(MaskVal, MVT::i32);
1427   return SDValue();
1428 }
1429
1430 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1431 /// amount, otherwise return -1.
1432 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1433   EVT VT = N->getValueType(0);
1434   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1435     return -1;
1436
1437   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1438
1439   // Find the first non-undef value in the shuffle mask.
1440   unsigned i;
1441   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1442     /*search*/;
1443
1444   if (i == 4) return -1;  // all undef.
1445
1446   // Otherwise, check to see if the rest of the elements are consecutively
1447   // numbered from this value.
1448   unsigned ShiftAmt = SVOp->getMaskElt(i);
1449   if (ShiftAmt < i) return -1;
1450   ShiftAmt -= i;
1451
1452   // Check the rest of the elements to see if they are consecutive.
1453   for (++i; i != 4; ++i)
1454     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1455       return -1;
1456
1457   return ShiftAmt;
1458 }
1459
1460 //===----------------------------------------------------------------------===//
1461 //  Addressing Mode Selection
1462 //===----------------------------------------------------------------------===//
1463
1464 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1465 /// or 64-bit immediate, and if the value can be accurately represented as a
1466 /// sign extension from a 16-bit value.  If so, this returns true and the
1467 /// immediate.
1468 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1469   if (!isa<ConstantSDNode>(N))
1470     return false;
1471
1472   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1473   if (N->getValueType(0) == MVT::i32)
1474     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1475   else
1476     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1477 }
1478 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1479   return isIntS16Immediate(Op.getNode(), Imm);
1480 }
1481
1482
1483 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1484 /// can be represented as an indexed [r+r] operation.  Returns false if it
1485 /// can be more efficiently represented with [r+imm].
1486 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1487                                             SDValue &Index,
1488                                             SelectionDAG &DAG) const {
1489   short imm = 0;
1490   if (N.getOpcode() == ISD::ADD) {
1491     if (isIntS16Immediate(N.getOperand(1), imm))
1492       return false;    // r+i
1493     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1494       return false;    // r+i
1495
1496     Base = N.getOperand(0);
1497     Index = N.getOperand(1);
1498     return true;
1499   } else if (N.getOpcode() == ISD::OR) {
1500     if (isIntS16Immediate(N.getOperand(1), imm))
1501       return false;    // r+i can fold it if we can.
1502
1503     // If this is an or of disjoint bitfields, we can codegen this as an add
1504     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1505     // disjoint.
1506     APInt LHSKnownZero, LHSKnownOne;
1507     APInt RHSKnownZero, RHSKnownOne;
1508     DAG.computeKnownBits(N.getOperand(0),
1509                          LHSKnownZero, LHSKnownOne);
1510
1511     if (LHSKnownZero.getBoolValue()) {
1512       DAG.computeKnownBits(N.getOperand(1),
1513                            RHSKnownZero, RHSKnownOne);
1514       // If all of the bits are known zero on the LHS or RHS, the add won't
1515       // carry.
1516       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1517         Base = N.getOperand(0);
1518         Index = N.getOperand(1);
1519         return true;
1520       }
1521     }
1522   }
1523
1524   return false;
1525 }
1526
1527 // If we happen to be doing an i64 load or store into a stack slot that has
1528 // less than a 4-byte alignment, then the frame-index elimination may need to
1529 // use an indexed load or store instruction (because the offset may not be a
1530 // multiple of 4). The extra register needed to hold the offset comes from the
1531 // register scavenger, and it is possible that the scavenger will need to use
1532 // an emergency spill slot. As a result, we need to make sure that a spill slot
1533 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1534 // stack slot.
1535 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1536   // FIXME: This does not handle the LWA case.
1537   if (VT != MVT::i64)
1538     return;
1539
1540   // NOTE: We'll exclude negative FIs here, which come from argument
1541   // lowering, because there are no known test cases triggering this problem
1542   // using packed structures (or similar). We can remove this exclusion if
1543   // we find such a test case. The reason why this is so test-case driven is
1544   // because this entire 'fixup' is only to prevent crashes (from the
1545   // register scavenger) on not-really-valid inputs. For example, if we have:
1546   //   %a = alloca i1
1547   //   %b = bitcast i1* %a to i64*
1548   //   store i64* a, i64 b
1549   // then the store should really be marked as 'align 1', but is not. If it
1550   // were marked as 'align 1' then the indexed form would have been
1551   // instruction-selected initially, and the problem this 'fixup' is preventing
1552   // won't happen regardless.
1553   if (FrameIdx < 0)
1554     return;
1555
1556   MachineFunction &MF = DAG.getMachineFunction();
1557   MachineFrameInfo *MFI = MF.getFrameInfo();
1558
1559   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1560   if (Align >= 4)
1561     return;
1562
1563   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1564   FuncInfo->setHasNonRISpills();
1565 }
1566
1567 /// Returns true if the address N can be represented by a base register plus
1568 /// a signed 16-bit displacement [r+imm], and if it is not better
1569 /// represented as reg+reg.  If Aligned is true, only accept displacements
1570 /// suitable for STD and friends, i.e. multiples of 4.
1571 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1572                                             SDValue &Base,
1573                                             SelectionDAG &DAG,
1574                                             bool Aligned) const {
1575   // FIXME dl should come from parent load or store, not from address
1576   SDLoc dl(N);
1577   // If this can be more profitably realized as r+r, fail.
1578   if (SelectAddressRegReg(N, Disp, Base, DAG))
1579     return false;
1580
1581   if (N.getOpcode() == ISD::ADD) {
1582     short imm = 0;
1583     if (isIntS16Immediate(N.getOperand(1), imm) &&
1584         (!Aligned || (imm & 3) == 0)) {
1585       Disp = DAG.getTargetConstant(imm, N.getValueType());
1586       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1587         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1588         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1589       } else {
1590         Base = N.getOperand(0);
1591       }
1592       return true; // [r+i]
1593     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1594       // Match LOAD (ADD (X, Lo(G))).
1595       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1596              && "Cannot handle constant offsets yet!");
1597       Disp = N.getOperand(1).getOperand(0);  // The global address.
1598       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1599              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1600              Disp.getOpcode() == ISD::TargetConstantPool ||
1601              Disp.getOpcode() == ISD::TargetJumpTable);
1602       Base = N.getOperand(0);
1603       return true;  // [&g+r]
1604     }
1605   } else if (N.getOpcode() == ISD::OR) {
1606     short imm = 0;
1607     if (isIntS16Immediate(N.getOperand(1), imm) &&
1608         (!Aligned || (imm & 3) == 0)) {
1609       // If this is an or of disjoint bitfields, we can codegen this as an add
1610       // (for better address arithmetic) if the LHS and RHS of the OR are
1611       // provably disjoint.
1612       APInt LHSKnownZero, LHSKnownOne;
1613       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1614
1615       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1616         // If all of the bits are known zero on the LHS or RHS, the add won't
1617         // carry.
1618         if (FrameIndexSDNode *FI =
1619               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1620           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1621           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1622         } else {
1623           Base = N.getOperand(0);
1624         }
1625         Disp = DAG.getTargetConstant(imm, N.getValueType());
1626         return true;
1627       }
1628     }
1629   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1630     // Loading from a constant address.
1631
1632     // If this address fits entirely in a 16-bit sext immediate field, codegen
1633     // this as "d, 0"
1634     short Imm;
1635     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1636       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1637       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1638                              CN->getValueType(0));
1639       return true;
1640     }
1641
1642     // Handle 32-bit sext immediates with LIS + addr mode.
1643     if ((CN->getValueType(0) == MVT::i32 ||
1644          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1645         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1646       int Addr = (int)CN->getZExtValue();
1647
1648       // Otherwise, break this down into an LIS + disp.
1649       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1650
1651       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1652       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1653       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1654       return true;
1655     }
1656   }
1657
1658   Disp = DAG.getTargetConstant(0, getPointerTy());
1659   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1660     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1661     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1662   } else
1663     Base = N;
1664   return true;      // [r+0]
1665 }
1666
1667 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1668 /// represented as an indexed [r+r] operation.
1669 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1670                                                 SDValue &Index,
1671                                                 SelectionDAG &DAG) const {
1672   // Check to see if we can easily represent this as an [r+r] address.  This
1673   // will fail if it thinks that the address is more profitably represented as
1674   // reg+imm, e.g. where imm = 0.
1675   if (SelectAddressRegReg(N, Base, Index, DAG))
1676     return true;
1677
1678   // If the operand is an addition, always emit this as [r+r], since this is
1679   // better (for code size, and execution, as the memop does the add for free)
1680   // than emitting an explicit add.
1681   if (N.getOpcode() == ISD::ADD) {
1682     Base = N.getOperand(0);
1683     Index = N.getOperand(1);
1684     return true;
1685   }
1686
1687   // Otherwise, do it the hard way, using R0 as the base register.
1688   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1689                          N.getValueType());
1690   Index = N;
1691   return true;
1692 }
1693
1694 /// getPreIndexedAddressParts - returns true by value, base pointer and
1695 /// offset pointer and addressing mode by reference if the node's address
1696 /// can be legally represented as pre-indexed load / store address.
1697 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1698                                                   SDValue &Offset,
1699                                                   ISD::MemIndexedMode &AM,
1700                                                   SelectionDAG &DAG) const {
1701   if (DisablePPCPreinc) return false;
1702
1703   bool isLoad = true;
1704   SDValue Ptr;
1705   EVT VT;
1706   unsigned Alignment;
1707   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1708     Ptr = LD->getBasePtr();
1709     VT = LD->getMemoryVT();
1710     Alignment = LD->getAlignment();
1711   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1712     Ptr = ST->getBasePtr();
1713     VT  = ST->getMemoryVT();
1714     Alignment = ST->getAlignment();
1715     isLoad = false;
1716   } else
1717     return false;
1718
1719   // PowerPC doesn't have preinc load/store instructions for vectors (except
1720   // for QPX, which does have preinc r+r forms).
1721   if (VT.isVector()) {
1722     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1723       return false;
1724     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1725       AM = ISD::PRE_INC;
1726       return true;
1727     }
1728   }
1729
1730   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1731
1732     // Common code will reject creating a pre-inc form if the base pointer
1733     // is a frame index, or if N is a store and the base pointer is either
1734     // the same as or a predecessor of the value being stored.  Check for
1735     // those situations here, and try with swapped Base/Offset instead.
1736     bool Swap = false;
1737
1738     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1739       Swap = true;
1740     else if (!isLoad) {
1741       SDValue Val = cast<StoreSDNode>(N)->getValue();
1742       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1743         Swap = true;
1744     }
1745
1746     if (Swap)
1747       std::swap(Base, Offset);
1748
1749     AM = ISD::PRE_INC;
1750     return true;
1751   }
1752
1753   // LDU/STU can only handle immediates that are a multiple of 4.
1754   if (VT != MVT::i64) {
1755     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1756       return false;
1757   } else {
1758     // LDU/STU need an address with at least 4-byte alignment.
1759     if (Alignment < 4)
1760       return false;
1761
1762     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1763       return false;
1764   }
1765
1766   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1767     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1768     // sext i32 to i64 when addr mode is r+i.
1769     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1770         LD->getExtensionType() == ISD::SEXTLOAD &&
1771         isa<ConstantSDNode>(Offset))
1772       return false;
1773   }
1774
1775   AM = ISD::PRE_INC;
1776   return true;
1777 }
1778
1779 //===----------------------------------------------------------------------===//
1780 //  LowerOperation implementation
1781 //===----------------------------------------------------------------------===//
1782
1783 /// GetLabelAccessInfo - Return true if we should reference labels using a
1784 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1785 static bool GetLabelAccessInfo(const TargetMachine &TM,
1786                                const PPCSubtarget &Subtarget,
1787                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1788                                const GlobalValue *GV = nullptr) {
1789   HiOpFlags = PPCII::MO_HA;
1790   LoOpFlags = PPCII::MO_LO;
1791
1792   // Don't use the pic base if not in PIC relocation model.
1793   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1794
1795   if (isPIC) {
1796     HiOpFlags |= PPCII::MO_PIC_FLAG;
1797     LoOpFlags |= PPCII::MO_PIC_FLAG;
1798   }
1799
1800   // If this is a reference to a global value that requires a non-lazy-ptr, make
1801   // sure that instruction lowering adds it.
1802   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1803     HiOpFlags |= PPCII::MO_NLP_FLAG;
1804     LoOpFlags |= PPCII::MO_NLP_FLAG;
1805
1806     if (GV->hasHiddenVisibility()) {
1807       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1808       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1809     }
1810   }
1811
1812   return isPIC;
1813 }
1814
1815 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1816                              SelectionDAG &DAG) {
1817   EVT PtrVT = HiPart.getValueType();
1818   SDValue Zero = DAG.getConstant(0, PtrVT);
1819   SDLoc DL(HiPart);
1820
1821   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1822   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1823
1824   // With PIC, the first instruction is actually "GR+hi(&G)".
1825   if (isPIC)
1826     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1827                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1828
1829   // Generate non-pic code that has direct accesses to the constant pool.
1830   // The address of the global is just (hi(&g)+lo(&g)).
1831   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1832 }
1833
1834 static void setUsesTOCBasePtr(MachineFunction &MF) {
1835   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1836   FuncInfo->setUsesTOCBasePtr();
1837 }
1838
1839 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1840   setUsesTOCBasePtr(DAG.getMachineFunction());
1841 }
1842
1843 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1844                            SDValue GA) {
1845   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1846   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1847                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1848
1849   SDValue Ops[] = { GA, Reg };
1850   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1851                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1852                                  MachinePointerInfo::getGOT(), 0, false, true,
1853                                  false, 0);
1854 }
1855
1856 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1857                                              SelectionDAG &DAG) const {
1858   EVT PtrVT = Op.getValueType();
1859   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1860   const Constant *C = CP->getConstVal();
1861
1862   // 64-bit SVR4 ABI code is always position-independent.
1863   // The actual address of the GlobalValue is stored in the TOC.
1864   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1865     setUsesTOCBasePtr(DAG);
1866     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1867     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1868   }
1869
1870   unsigned MOHiFlag, MOLoFlag;
1871   bool isPIC =
1872       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1873
1874   if (isPIC && Subtarget.isSVR4ABI()) {
1875     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1876                                            PPCII::MO_PIC_FLAG);
1877     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1878   }
1879
1880   SDValue CPIHi =
1881     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1882   SDValue CPILo =
1883     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1884   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1885 }
1886
1887 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1888   EVT PtrVT = Op.getValueType();
1889   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1890
1891   // 64-bit SVR4 ABI code is always position-independent.
1892   // The actual address of the GlobalValue is stored in the TOC.
1893   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1894     setUsesTOCBasePtr(DAG);
1895     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1896     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1897   }
1898
1899   unsigned MOHiFlag, MOLoFlag;
1900   bool isPIC =
1901       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1902
1903   if (isPIC && Subtarget.isSVR4ABI()) {
1904     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1905                                         PPCII::MO_PIC_FLAG);
1906     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1907   }
1908
1909   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1910   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1911   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1912 }
1913
1914 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1915                                              SelectionDAG &DAG) const {
1916   EVT PtrVT = Op.getValueType();
1917   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1918   const BlockAddress *BA = BASDN->getBlockAddress();
1919
1920   // 64-bit SVR4 ABI code is always position-independent.
1921   // The actual BlockAddress is stored in the TOC.
1922   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1923     setUsesTOCBasePtr(DAG);
1924     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1925     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1926   }
1927
1928   unsigned MOHiFlag, MOLoFlag;
1929   bool isPIC =
1930       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1931   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1932   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1933   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1934 }
1935
1936 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1937                                               SelectionDAG &DAG) const {
1938
1939   // FIXME: TLS addresses currently use medium model code sequences,
1940   // which is the most useful form.  Eventually support for small and
1941   // large models could be added if users need it, at the cost of
1942   // additional complexity.
1943   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1944   SDLoc dl(GA);
1945   const GlobalValue *GV = GA->getGlobal();
1946   EVT PtrVT = getPointerTy();
1947   bool is64bit = Subtarget.isPPC64();
1948   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1949   PICLevel::Level picLevel = M->getPICLevel();
1950
1951   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1952
1953   if (Model == TLSModel::LocalExec) {
1954     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1955                                                PPCII::MO_TPREL_HA);
1956     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1957                                                PPCII::MO_TPREL_LO);
1958     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1959                                      is64bit ? MVT::i64 : MVT::i32);
1960     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1961     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1962   }
1963
1964   if (Model == TLSModel::InitialExec) {
1965     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1966     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1967                                                 PPCII::MO_TLS);
1968     SDValue GOTPtr;
1969     if (is64bit) {
1970       setUsesTOCBasePtr(DAG);
1971       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1972       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1973                            PtrVT, GOTReg, TGA);
1974     } else
1975       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1976     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1977                                    PtrVT, TGA, GOTPtr);
1978     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1979   }
1980
1981   if (Model == TLSModel::GeneralDynamic) {
1982     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1983     SDValue GOTPtr;
1984     if (is64bit) {
1985       setUsesTOCBasePtr(DAG);
1986       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1987       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1988                                    GOTReg, TGA);
1989     } else {
1990       if (picLevel == PICLevel::Small)
1991         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1992       else
1993         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1994     }
1995     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1996                        GOTPtr, TGA, TGA);
1997   }
1998
1999   if (Model == TLSModel::LocalDynamic) {
2000     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2001     SDValue GOTPtr;
2002     if (is64bit) {
2003       setUsesTOCBasePtr(DAG);
2004       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2005       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2006                            GOTReg, TGA);
2007     } else {
2008       if (picLevel == PICLevel::Small)
2009         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2010       else
2011         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2012     }
2013     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2014                                   PtrVT, GOTPtr, TGA, TGA);
2015     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2016                                       PtrVT, TLSAddr, TGA);
2017     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2018   }
2019
2020   llvm_unreachable("Unknown TLS model!");
2021 }
2022
2023 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2024                                               SelectionDAG &DAG) const {
2025   EVT PtrVT = Op.getValueType();
2026   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2027   SDLoc DL(GSDN);
2028   const GlobalValue *GV = GSDN->getGlobal();
2029
2030   // 64-bit SVR4 ABI code is always position-independent.
2031   // The actual address of the GlobalValue is stored in the TOC.
2032   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2033     setUsesTOCBasePtr(DAG);
2034     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2035     return getTOCEntry(DAG, DL, true, GA);
2036   }
2037
2038   unsigned MOHiFlag, MOLoFlag;
2039   bool isPIC =
2040       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2041
2042   if (isPIC && Subtarget.isSVR4ABI()) {
2043     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2044                                             GSDN->getOffset(),
2045                                             PPCII::MO_PIC_FLAG);
2046     return getTOCEntry(DAG, DL, false, GA);
2047   }
2048
2049   SDValue GAHi =
2050     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2051   SDValue GALo =
2052     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2053
2054   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2055
2056   // If the global reference is actually to a non-lazy-pointer, we have to do an
2057   // extra load to get the address of the global.
2058   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2059     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2060                       false, false, false, 0);
2061   return Ptr;
2062 }
2063
2064 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2065   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2066   SDLoc dl(Op);
2067
2068   if (Op.getValueType() == MVT::v2i64) {
2069     // When the operands themselves are v2i64 values, we need to do something
2070     // special because VSX has no underlying comparison operations for these.
2071     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2072       // Equality can be handled by casting to the legal type for Altivec
2073       // comparisons, everything else needs to be expanded.
2074       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2075         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2076                  DAG.getSetCC(dl, MVT::v4i32,
2077                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2078                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2079                    CC));
2080       }
2081
2082       return SDValue();
2083     }
2084
2085     // We handle most of these in the usual way.
2086     return Op;
2087   }
2088
2089   // If we're comparing for equality to zero, expose the fact that this is
2090   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2091   // fold the new nodes.
2092   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2093     if (C->isNullValue() && CC == ISD::SETEQ) {
2094       EVT VT = Op.getOperand(0).getValueType();
2095       SDValue Zext = Op.getOperand(0);
2096       if (VT.bitsLT(MVT::i32)) {
2097         VT = MVT::i32;
2098         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2099       }
2100       unsigned Log2b = Log2_32(VT.getSizeInBits());
2101       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2102       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2103                                 DAG.getConstant(Log2b, MVT::i32));
2104       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2105     }
2106     // Leave comparisons against 0 and -1 alone for now, since they're usually
2107     // optimized.  FIXME: revisit this when we can custom lower all setcc
2108     // optimizations.
2109     if (C->isAllOnesValue() || C->isNullValue())
2110       return SDValue();
2111   }
2112
2113   // If we have an integer seteq/setne, turn it into a compare against zero
2114   // by xor'ing the rhs with the lhs, which is faster than setting a
2115   // condition register, reading it back out, and masking the correct bit.  The
2116   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2117   // the result to other bit-twiddling opportunities.
2118   EVT LHSVT = Op.getOperand(0).getValueType();
2119   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2120     EVT VT = Op.getValueType();
2121     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2122                                 Op.getOperand(1));
2123     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2124   }
2125   return SDValue();
2126 }
2127
2128 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2129                                       const PPCSubtarget &Subtarget) const {
2130   SDNode *Node = Op.getNode();
2131   EVT VT = Node->getValueType(0);
2132   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2133   SDValue InChain = Node->getOperand(0);
2134   SDValue VAListPtr = Node->getOperand(1);
2135   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2136   SDLoc dl(Node);
2137
2138   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2139
2140   // gpr_index
2141   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2142                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2143                                     false, false, false, 0);
2144   InChain = GprIndex.getValue(1);
2145
2146   if (VT == MVT::i64) {
2147     // Check if GprIndex is even
2148     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2149                                  DAG.getConstant(1, MVT::i32));
2150     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2151                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2152     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2153                                           DAG.getConstant(1, MVT::i32));
2154     // Align GprIndex to be even if it isn't
2155     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2156                            GprIndex);
2157   }
2158
2159   // fpr index is 1 byte after gpr
2160   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2161                                DAG.getConstant(1, MVT::i32));
2162
2163   // fpr
2164   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2165                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2166                                     false, false, false, 0);
2167   InChain = FprIndex.getValue(1);
2168
2169   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2170                                        DAG.getConstant(8, MVT::i32));
2171
2172   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2173                                         DAG.getConstant(4, MVT::i32));
2174
2175   // areas
2176   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2177                                      MachinePointerInfo(), false, false,
2178                                      false, 0);
2179   InChain = OverflowArea.getValue(1);
2180
2181   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2182                                     MachinePointerInfo(), false, false,
2183                                     false, 0);
2184   InChain = RegSaveArea.getValue(1);
2185
2186   // select overflow_area if index > 8
2187   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2188                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
2189
2190   // adjustment constant gpr_index * 4/8
2191   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2192                                     VT.isInteger() ? GprIndex : FprIndex,
2193                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
2194                                                     MVT::i32));
2195
2196   // OurReg = RegSaveArea + RegConstant
2197   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2198                                RegConstant);
2199
2200   // Floating types are 32 bytes into RegSaveArea
2201   if (VT.isFloatingPoint())
2202     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2203                          DAG.getConstant(32, MVT::i32));
2204
2205   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2206   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2207                                    VT.isInteger() ? GprIndex : FprIndex,
2208                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2209                                                    MVT::i32));
2210
2211   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2212                               VT.isInteger() ? VAListPtr : FprPtr,
2213                               MachinePointerInfo(SV),
2214                               MVT::i8, false, false, 0);
2215
2216   // determine if we should load from reg_save_area or overflow_area
2217   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2218
2219   // increase overflow_area by 4/8 if gpr/fpr > 8
2220   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2221                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2222                                           MVT::i32));
2223
2224   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2225                              OverflowAreaPlusN);
2226
2227   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2228                               OverflowAreaPtr,
2229                               MachinePointerInfo(),
2230                               MVT::i32, false, false, 0);
2231
2232   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2233                      false, false, false, 0);
2234 }
2235
2236 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2237                                        const PPCSubtarget &Subtarget) const {
2238   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2239
2240   // We have to copy the entire va_list struct:
2241   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2242   return DAG.getMemcpy(Op.getOperand(0), Op,
2243                        Op.getOperand(1), Op.getOperand(2),
2244                        DAG.getConstant(12, MVT::i32), 8, false, true,
2245                        MachinePointerInfo(), MachinePointerInfo());
2246 }
2247
2248 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2249                                                   SelectionDAG &DAG) const {
2250   return Op.getOperand(0);
2251 }
2252
2253 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2254                                                 SelectionDAG &DAG) const {
2255   SDValue Chain = Op.getOperand(0);
2256   SDValue Trmp = Op.getOperand(1); // trampoline
2257   SDValue FPtr = Op.getOperand(2); // nested function
2258   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2259   SDLoc dl(Op);
2260
2261   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2262   bool isPPC64 = (PtrVT == MVT::i64);
2263   Type *IntPtrTy =
2264     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2265                                                              *DAG.getContext());
2266
2267   TargetLowering::ArgListTy Args;
2268   TargetLowering::ArgListEntry Entry;
2269
2270   Entry.Ty = IntPtrTy;
2271   Entry.Node = Trmp; Args.push_back(Entry);
2272
2273   // TrampSize == (isPPC64 ? 48 : 40);
2274   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2275                                isPPC64 ? MVT::i64 : MVT::i32);
2276   Args.push_back(Entry);
2277
2278   Entry.Node = FPtr; Args.push_back(Entry);
2279   Entry.Node = Nest; Args.push_back(Entry);
2280
2281   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2282   TargetLowering::CallLoweringInfo CLI(DAG);
2283   CLI.setDebugLoc(dl).setChain(Chain)
2284     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2285                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2286                std::move(Args), 0);
2287
2288   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2289   return CallResult.second;
2290 }
2291
2292 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2293                                         const PPCSubtarget &Subtarget) const {
2294   MachineFunction &MF = DAG.getMachineFunction();
2295   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2296
2297   SDLoc dl(Op);
2298
2299   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2300     // vastart just stores the address of the VarArgsFrameIndex slot into the
2301     // memory location argument.
2302     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2303     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2304     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2305     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2306                         MachinePointerInfo(SV),
2307                         false, false, 0);
2308   }
2309
2310   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2311   // We suppose the given va_list is already allocated.
2312   //
2313   // typedef struct {
2314   //  char gpr;     /* index into the array of 8 GPRs
2315   //                 * stored in the register save area
2316   //                 * gpr=0 corresponds to r3,
2317   //                 * gpr=1 to r4, etc.
2318   //                 */
2319   //  char fpr;     /* index into the array of 8 FPRs
2320   //                 * stored in the register save area
2321   //                 * fpr=0 corresponds to f1,
2322   //                 * fpr=1 to f2, etc.
2323   //                 */
2324   //  char *overflow_arg_area;
2325   //                /* location on stack that holds
2326   //                 * the next overflow argument
2327   //                 */
2328   //  char *reg_save_area;
2329   //               /* where r3:r10 and f1:f8 (if saved)
2330   //                * are stored
2331   //                */
2332   // } va_list[1];
2333
2334
2335   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2336   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2337
2338
2339   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2340
2341   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2342                                             PtrVT);
2343   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2344                                  PtrVT);
2345
2346   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2347   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2348
2349   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2350   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2351
2352   uint64_t FPROffset = 1;
2353   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2354
2355   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2356
2357   // Store first byte : number of int regs
2358   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2359                                          Op.getOperand(1),
2360                                          MachinePointerInfo(SV),
2361                                          MVT::i8, false, false, 0);
2362   uint64_t nextOffset = FPROffset;
2363   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2364                                   ConstFPROffset);
2365
2366   // Store second byte : number of float regs
2367   SDValue secondStore =
2368     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2369                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2370                       false, false, 0);
2371   nextOffset += StackOffset;
2372   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2373
2374   // Store second word : arguments given on stack
2375   SDValue thirdStore =
2376     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2377                  MachinePointerInfo(SV, nextOffset),
2378                  false, false, 0);
2379   nextOffset += FrameOffset;
2380   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2381
2382   // Store third word : arguments given in registers
2383   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2384                       MachinePointerInfo(SV, nextOffset),
2385                       false, false, 0);
2386
2387 }
2388
2389 #include "PPCGenCallingConv.inc"
2390
2391 // Function whose sole purpose is to kill compiler warnings 
2392 // stemming from unused functions included from PPCGenCallingConv.inc.
2393 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2394   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2395 }
2396
2397 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2398                                       CCValAssign::LocInfo &LocInfo,
2399                                       ISD::ArgFlagsTy &ArgFlags,
2400                                       CCState &State) {
2401   return true;
2402 }
2403
2404 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2405                                              MVT &LocVT,
2406                                              CCValAssign::LocInfo &LocInfo,
2407                                              ISD::ArgFlagsTy &ArgFlags,
2408                                              CCState &State) {
2409   static const MCPhysReg ArgRegs[] = {
2410     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2411     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2412   };
2413   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2414
2415   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2416
2417   // Skip one register if the first unallocated register has an even register
2418   // number and there are still argument registers available which have not been
2419   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2420   // need to skip a register if RegNum is odd.
2421   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2422     State.AllocateReg(ArgRegs[RegNum]);
2423   }
2424
2425   // Always return false here, as this function only makes sure that the first
2426   // unallocated register has an odd register number and does not actually
2427   // allocate a register for the current argument.
2428   return false;
2429 }
2430
2431 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2432                                                MVT &LocVT,
2433                                                CCValAssign::LocInfo &LocInfo,
2434                                                ISD::ArgFlagsTy &ArgFlags,
2435                                                CCState &State) {
2436   static const MCPhysReg ArgRegs[] = {
2437     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2438     PPC::F8
2439   };
2440
2441   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2442
2443   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2444
2445   // If there is only one Floating-point register left we need to put both f64
2446   // values of a split ppc_fp128 value on the stack.
2447   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2448     State.AllocateReg(ArgRegs[RegNum]);
2449   }
2450
2451   // Always return false here, as this function only makes sure that the two f64
2452   // values a ppc_fp128 value is split into are both passed in registers or both
2453   // passed on the stack and does not actually allocate a register for the
2454   // current argument.
2455   return false;
2456 }
2457
2458 /// FPR - The set of FP registers that should be allocated for arguments,
2459 /// on Darwin.
2460 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2461                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2462                                 PPC::F11, PPC::F12, PPC::F13};
2463
2464 /// QFPR - The set of QPX registers that should be allocated for arguments.
2465 static const MCPhysReg QFPR[] = {
2466     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2467     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2468
2469 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2470 /// the stack.
2471 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2472                                        unsigned PtrByteSize) {
2473   unsigned ArgSize = ArgVT.getStoreSize();
2474   if (Flags.isByVal())
2475     ArgSize = Flags.getByValSize();
2476
2477   // Round up to multiples of the pointer size, except for array members,
2478   // which are always packed.
2479   if (!Flags.isInConsecutiveRegs())
2480     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2481
2482   return ArgSize;
2483 }
2484
2485 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2486 /// on the stack.
2487 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2488                                             ISD::ArgFlagsTy Flags,
2489                                             unsigned PtrByteSize) {
2490   unsigned Align = PtrByteSize;
2491
2492   // Altivec parameters are padded to a 16 byte boundary.
2493   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2494       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2495       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2496     Align = 16;
2497   // QPX vector types stored in double-precision are padded to a 32 byte
2498   // boundary.
2499   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2500     Align = 32;
2501
2502   // ByVal parameters are aligned as requested.
2503   if (Flags.isByVal()) {
2504     unsigned BVAlign = Flags.getByValAlign();
2505     if (BVAlign > PtrByteSize) {
2506       if (BVAlign % PtrByteSize != 0)
2507           llvm_unreachable(
2508             "ByVal alignment is not a multiple of the pointer size");
2509
2510       Align = BVAlign;
2511     }
2512   }
2513
2514   // Array members are always packed to their original alignment.
2515   if (Flags.isInConsecutiveRegs()) {
2516     // If the array member was split into multiple registers, the first
2517     // needs to be aligned to the size of the full type.  (Except for
2518     // ppcf128, which is only aligned as its f64 components.)
2519     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2520       Align = OrigVT.getStoreSize();
2521     else
2522       Align = ArgVT.getStoreSize();
2523   }
2524
2525   return Align;
2526 }
2527
2528 /// CalculateStackSlotUsed - Return whether this argument will use its
2529 /// stack slot (instead of being passed in registers).  ArgOffset,
2530 /// AvailableFPRs, and AvailableVRs must hold the current argument
2531 /// position, and will be updated to account for this argument.
2532 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2533                                    ISD::ArgFlagsTy Flags,
2534                                    unsigned PtrByteSize,
2535                                    unsigned LinkageSize,
2536                                    unsigned ParamAreaSize,
2537                                    unsigned &ArgOffset,
2538                                    unsigned &AvailableFPRs,
2539                                    unsigned &AvailableVRs, bool HasQPX) {
2540   bool UseMemory = false;
2541
2542   // Respect alignment of argument on the stack.
2543   unsigned Align =
2544     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2545   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2546   // If there's no space left in the argument save area, we must
2547   // use memory (this check also catches zero-sized arguments).
2548   if (ArgOffset >= LinkageSize + ParamAreaSize)
2549     UseMemory = true;
2550
2551   // Allocate argument on the stack.
2552   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2553   if (Flags.isInConsecutiveRegsLast())
2554     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2555   // If we overran the argument save area, we must use memory
2556   // (this check catches arguments passed partially in memory)
2557   if (ArgOffset > LinkageSize + ParamAreaSize)
2558     UseMemory = true;
2559
2560   // However, if the argument is actually passed in an FPR or a VR,
2561   // we don't use memory after all.
2562   if (!Flags.isByVal()) {
2563     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2564         // QPX registers overlap with the scalar FP registers.
2565         (HasQPX && (ArgVT == MVT::v4f32 ||
2566                     ArgVT == MVT::v4f64 ||
2567                     ArgVT == MVT::v4i1)))
2568       if (AvailableFPRs > 0) {
2569         --AvailableFPRs;
2570         return false;
2571       }
2572     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2573         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2574         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2575       if (AvailableVRs > 0) {
2576         --AvailableVRs;
2577         return false;
2578       }
2579   }
2580
2581   return UseMemory;
2582 }
2583
2584 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2585 /// ensure minimum alignment required for target.
2586 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2587                                      unsigned NumBytes) {
2588   unsigned TargetAlign = Lowering->getStackAlignment();
2589   unsigned AlignMask = TargetAlign - 1;
2590   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2591   return NumBytes;
2592 }
2593
2594 SDValue
2595 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2596                                         CallingConv::ID CallConv, bool isVarArg,
2597                                         const SmallVectorImpl<ISD::InputArg>
2598                                           &Ins,
2599                                         SDLoc dl, SelectionDAG &DAG,
2600                                         SmallVectorImpl<SDValue> &InVals)
2601                                           const {
2602   if (Subtarget.isSVR4ABI()) {
2603     if (Subtarget.isPPC64())
2604       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2605                                          dl, DAG, InVals);
2606     else
2607       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2608                                          dl, DAG, InVals);
2609   } else {
2610     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2611                                        dl, DAG, InVals);
2612   }
2613 }
2614
2615 SDValue
2616 PPCTargetLowering::LowerFormalArguments_32SVR4(
2617                                       SDValue Chain,
2618                                       CallingConv::ID CallConv, bool isVarArg,
2619                                       const SmallVectorImpl<ISD::InputArg>
2620                                         &Ins,
2621                                       SDLoc dl, SelectionDAG &DAG,
2622                                       SmallVectorImpl<SDValue> &InVals) const {
2623
2624   // 32-bit SVR4 ABI Stack Frame Layout:
2625   //              +-----------------------------------+
2626   //        +-->  |            Back chain             |
2627   //        |     +-----------------------------------+
2628   //        |     | Floating-point register save area |
2629   //        |     +-----------------------------------+
2630   //        |     |    General register save area     |
2631   //        |     +-----------------------------------+
2632   //        |     |          CR save word             |
2633   //        |     +-----------------------------------+
2634   //        |     |         VRSAVE save word          |
2635   //        |     +-----------------------------------+
2636   //        |     |         Alignment padding         |
2637   //        |     +-----------------------------------+
2638   //        |     |     Vector register save area     |
2639   //        |     +-----------------------------------+
2640   //        |     |       Local variable space        |
2641   //        |     +-----------------------------------+
2642   //        |     |        Parameter list area        |
2643   //        |     +-----------------------------------+
2644   //        |     |           LR save word            |
2645   //        |     +-----------------------------------+
2646   // SP-->  +---  |            Back chain             |
2647   //              +-----------------------------------+
2648   //
2649   // Specifications:
2650   //   System V Application Binary Interface PowerPC Processor Supplement
2651   //   AltiVec Technology Programming Interface Manual
2652
2653   MachineFunction &MF = DAG.getMachineFunction();
2654   MachineFrameInfo *MFI = MF.getFrameInfo();
2655   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2656
2657   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2658   // Potential tail calls could cause overwriting of argument stack slots.
2659   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2660                        (CallConv == CallingConv::Fast));
2661   unsigned PtrByteSize = 4;
2662
2663   // Assign locations to all of the incoming arguments.
2664   SmallVector<CCValAssign, 16> ArgLocs;
2665   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2666                  *DAG.getContext());
2667
2668   // Reserve space for the linkage area on the stack.
2669   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2670   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2671
2672   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2673
2674   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2675     CCValAssign &VA = ArgLocs[i];
2676
2677     // Arguments stored in registers.
2678     if (VA.isRegLoc()) {
2679       const TargetRegisterClass *RC;
2680       EVT ValVT = VA.getValVT();
2681
2682       switch (ValVT.getSimpleVT().SimpleTy) {
2683         default:
2684           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2685         case MVT::i1:
2686         case MVT::i32:
2687           RC = &PPC::GPRCRegClass;
2688           break;
2689         case MVT::f32:
2690           RC = &PPC::F4RCRegClass;
2691           break;
2692         case MVT::f64:
2693           if (Subtarget.hasVSX())
2694             RC = &PPC::VSFRCRegClass;
2695           else
2696             RC = &PPC::F8RCRegClass;
2697           break;
2698         case MVT::v16i8:
2699         case MVT::v8i16:
2700         case MVT::v4i32:
2701           RC = &PPC::VRRCRegClass;
2702           break;
2703         case MVT::v4f32:
2704           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2705           break;
2706         case MVT::v2f64:
2707         case MVT::v2i64:
2708           RC = &PPC::VSHRCRegClass;
2709           break;
2710         case MVT::v4f64:
2711           RC = &PPC::QFRCRegClass;
2712           break;
2713         case MVT::v4i1:
2714           RC = &PPC::QBRCRegClass;
2715           break;
2716       }
2717
2718       // Transform the arguments stored in physical registers into virtual ones.
2719       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2720       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2721                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2722
2723       if (ValVT == MVT::i1)
2724         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2725
2726       InVals.push_back(ArgValue);
2727     } else {
2728       // Argument stored in memory.
2729       assert(VA.isMemLoc());
2730
2731       unsigned ArgSize = VA.getLocVT().getStoreSize();
2732       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2733                                       isImmutable);
2734
2735       // Create load nodes to retrieve arguments from the stack.
2736       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2737       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2738                                    MachinePointerInfo(),
2739                                    false, false, false, 0));
2740     }
2741   }
2742
2743   // Assign locations to all of the incoming aggregate by value arguments.
2744   // Aggregates passed by value are stored in the local variable space of the
2745   // caller's stack frame, right above the parameter list area.
2746   SmallVector<CCValAssign, 16> ByValArgLocs;
2747   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2748                       ByValArgLocs, *DAG.getContext());
2749
2750   // Reserve stack space for the allocations in CCInfo.
2751   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2752
2753   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2754
2755   // Area that is at least reserved in the caller of this function.
2756   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2757   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2758
2759   // Set the size that is at least reserved in caller of this function.  Tail
2760   // call optimized function's reserved stack space needs to be aligned so that
2761   // taking the difference between two stack areas will result in an aligned
2762   // stack.
2763   MinReservedArea =
2764       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2765   FuncInfo->setMinReservedArea(MinReservedArea);
2766
2767   SmallVector<SDValue, 8> MemOps;
2768
2769   // If the function takes variable number of arguments, make a frame index for
2770   // the start of the first vararg value... for expansion of llvm.va_start.
2771   if (isVarArg) {
2772     static const MCPhysReg GPArgRegs[] = {
2773       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2774       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2775     };
2776     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2777
2778     static const MCPhysReg FPArgRegs[] = {
2779       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2780       PPC::F8
2781     };
2782     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2783     if (DisablePPCFloatInVariadic)
2784       NumFPArgRegs = 0;
2785
2786     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2787     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2788
2789     // Make room for NumGPArgRegs and NumFPArgRegs.
2790     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2791                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2792
2793     FuncInfo->setVarArgsStackOffset(
2794       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2795                              CCInfo.getNextStackOffset(), true));
2796
2797     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2798     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2799
2800     // The fixed integer arguments of a variadic function are stored to the
2801     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2802     // the result of va_next.
2803     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2804       // Get an existing live-in vreg, or add a new one.
2805       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2806       if (!VReg)
2807         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2808
2809       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2810       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2811                                    MachinePointerInfo(), false, false, 0);
2812       MemOps.push_back(Store);
2813       // Increment the address by four for the next argument to store
2814       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2815       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2816     }
2817
2818     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2819     // is set.
2820     // The double arguments are stored to the VarArgsFrameIndex
2821     // on the stack.
2822     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2823       // Get an existing live-in vreg, or add a new one.
2824       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2825       if (!VReg)
2826         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2827
2828       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2829       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2830                                    MachinePointerInfo(), false, false, 0);
2831       MemOps.push_back(Store);
2832       // Increment the address by eight for the next argument to store
2833       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2834                                          PtrVT);
2835       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2836     }
2837   }
2838
2839   if (!MemOps.empty())
2840     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2841
2842   return Chain;
2843 }
2844
2845 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2846 // value to MVT::i64 and then truncate to the correct register size.
2847 SDValue
2848 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2849                                      SelectionDAG &DAG, SDValue ArgVal,
2850                                      SDLoc dl) const {
2851   if (Flags.isSExt())
2852     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2853                          DAG.getValueType(ObjectVT));
2854   else if (Flags.isZExt())
2855     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2856                          DAG.getValueType(ObjectVT));
2857
2858   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2859 }
2860
2861 SDValue
2862 PPCTargetLowering::LowerFormalArguments_64SVR4(
2863                                       SDValue Chain,
2864                                       CallingConv::ID CallConv, bool isVarArg,
2865                                       const SmallVectorImpl<ISD::InputArg>
2866                                         &Ins,
2867                                       SDLoc dl, SelectionDAG &DAG,
2868                                       SmallVectorImpl<SDValue> &InVals) const {
2869   // TODO: add description of PPC stack frame format, or at least some docs.
2870   //
2871   bool isELFv2ABI = Subtarget.isELFv2ABI();
2872   bool isLittleEndian = Subtarget.isLittleEndian();
2873   MachineFunction &MF = DAG.getMachineFunction();
2874   MachineFrameInfo *MFI = MF.getFrameInfo();
2875   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2876
2877   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2878          "fastcc not supported on varargs functions");
2879
2880   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2881   // Potential tail calls could cause overwriting of argument stack slots.
2882   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2883                        (CallConv == CallingConv::Fast));
2884   unsigned PtrByteSize = 8;
2885   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2886
2887   static const MCPhysReg GPR[] = {
2888     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2889     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2890   };
2891   static const MCPhysReg VR[] = {
2892     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2893     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2894   };
2895   static const MCPhysReg VSRH[] = {
2896     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2897     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2898   };
2899
2900   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2901   const unsigned Num_FPR_Regs = 13;
2902   const unsigned Num_VR_Regs  = array_lengthof(VR);
2903   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2904
2905   // Do a first pass over the arguments to determine whether the ABI
2906   // guarantees that our caller has allocated the parameter save area
2907   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2908   // in the ELFv2 ABI, it is true if this is a vararg function or if
2909   // any parameter is located in a stack slot.
2910
2911   bool HasParameterArea = !isELFv2ABI || isVarArg;
2912   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2913   unsigned NumBytes = LinkageSize;
2914   unsigned AvailableFPRs = Num_FPR_Regs;
2915   unsigned AvailableVRs = Num_VR_Regs;
2916   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2917     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2918                                PtrByteSize, LinkageSize, ParamAreaSize,
2919                                NumBytes, AvailableFPRs, AvailableVRs,
2920                                Subtarget.hasQPX()))
2921       HasParameterArea = true;
2922
2923   // Add DAG nodes to load the arguments or copy them out of registers.  On
2924   // entry to a function on PPC, the arguments start after the linkage area,
2925   // although the first ones are often in registers.
2926
2927   unsigned ArgOffset = LinkageSize;
2928   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2929   unsigned &QFPR_idx = FPR_idx;
2930   SmallVector<SDValue, 8> MemOps;
2931   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2932   unsigned CurArgIdx = 0;
2933   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2934     SDValue ArgVal;
2935     bool needsLoad = false;
2936     EVT ObjectVT = Ins[ArgNo].VT;
2937     EVT OrigVT = Ins[ArgNo].ArgVT;
2938     unsigned ObjSize = ObjectVT.getStoreSize();
2939     unsigned ArgSize = ObjSize;
2940     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2941     if (Ins[ArgNo].isOrigArg()) {
2942       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2943       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2944     }
2945     // We re-align the argument offset for each argument, except when using the
2946     // fast calling convention, when we need to make sure we do that only when
2947     // we'll actually use a stack slot.
2948     unsigned CurArgOffset, Align;
2949     auto ComputeArgOffset = [&]() {
2950       /* Respect alignment of argument on the stack.  */
2951       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2952       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2953       CurArgOffset = ArgOffset;
2954     };
2955
2956     if (CallConv != CallingConv::Fast) {
2957       ComputeArgOffset();
2958
2959       /* Compute GPR index associated with argument offset.  */
2960       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2961       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2962     }
2963
2964     // FIXME the codegen can be much improved in some cases.
2965     // We do not have to keep everything in memory.
2966     if (Flags.isByVal()) {
2967       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2968
2969       if (CallConv == CallingConv::Fast)
2970         ComputeArgOffset();
2971
2972       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2973       ObjSize = Flags.getByValSize();
2974       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2975       // Empty aggregate parameters do not take up registers.  Examples:
2976       //   struct { } a;
2977       //   union  { } b;
2978       //   int c[0];
2979       // etc.  However, we have to provide a place-holder in InVals, so
2980       // pretend we have an 8-byte item at the current address for that
2981       // purpose.
2982       if (!ObjSize) {
2983         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2984         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2985         InVals.push_back(FIN);
2986         continue;
2987       }
2988
2989       // Create a stack object covering all stack doublewords occupied
2990       // by the argument.  If the argument is (fully or partially) on
2991       // the stack, or if the argument is fully in registers but the
2992       // caller has allocated the parameter save anyway, we can refer
2993       // directly to the caller's stack frame.  Otherwise, create a
2994       // local copy in our own frame.
2995       int FI;
2996       if (HasParameterArea ||
2997           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2998         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2999       else
3000         FI = MFI->CreateStackObject(ArgSize, Align, false);
3001       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3002
3003       // Handle aggregates smaller than 8 bytes.
3004       if (ObjSize < PtrByteSize) {
3005         // The value of the object is its address, which differs from the
3006         // address of the enclosing doubleword on big-endian systems.
3007         SDValue Arg = FIN;
3008         if (!isLittleEndian) {
3009           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3010           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3011         }
3012         InVals.push_back(Arg);
3013
3014         if (GPR_idx != Num_GPR_Regs) {
3015           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3016           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3017           SDValue Store;
3018
3019           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3020             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3021                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3022             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3023                                       MachinePointerInfo(FuncArg),
3024                                       ObjType, false, false, 0);
3025           } else {
3026             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3027             // store the whole register as-is to the parameter save area
3028             // slot.
3029             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3030                                  MachinePointerInfo(FuncArg),
3031                                  false, false, 0);
3032           }
3033
3034           MemOps.push_back(Store);
3035         }
3036         // Whether we copied from a register or not, advance the offset
3037         // into the parameter save area by a full doubleword.
3038         ArgOffset += PtrByteSize;
3039         continue;
3040       }
3041
3042       // The value of the object is its address, which is the address of
3043       // its first stack doubleword.
3044       InVals.push_back(FIN);
3045
3046       // Store whatever pieces of the object are in registers to memory.
3047       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3048         if (GPR_idx == Num_GPR_Regs)
3049           break;
3050
3051         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3052         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3053         SDValue Addr = FIN;
3054         if (j) {
3055           SDValue Off = DAG.getConstant(j, PtrVT);
3056           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3057         }
3058         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3059                                      MachinePointerInfo(FuncArg, j),
3060                                      false, false, 0);
3061         MemOps.push_back(Store);
3062         ++GPR_idx;
3063       }
3064       ArgOffset += ArgSize;
3065       continue;
3066     }
3067
3068     switch (ObjectVT.getSimpleVT().SimpleTy) {
3069     default: llvm_unreachable("Unhandled argument type!");
3070     case MVT::i1:
3071     case MVT::i32:
3072     case MVT::i64:
3073       // These can be scalar arguments or elements of an integer array type
3074       // passed directly.  Clang may use those instead of "byval" aggregate
3075       // types to avoid forcing arguments to memory unnecessarily.
3076       if (GPR_idx != Num_GPR_Regs) {
3077         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3078         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3079
3080         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3081           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3082           // value to MVT::i64 and then truncate to the correct register size.
3083           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3084       } else {
3085         if (CallConv == CallingConv::Fast)
3086           ComputeArgOffset();
3087
3088         needsLoad = true;
3089         ArgSize = PtrByteSize;
3090       }
3091       if (CallConv != CallingConv::Fast || needsLoad)
3092         ArgOffset += 8;
3093       break;
3094
3095     case MVT::f32:
3096     case MVT::f64:
3097       // These can be scalar arguments or elements of a float array type
3098       // passed directly.  The latter are used to implement ELFv2 homogenous
3099       // float aggregates.
3100       if (FPR_idx != Num_FPR_Regs) {
3101         unsigned VReg;
3102
3103         if (ObjectVT == MVT::f32)
3104           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3105         else
3106           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3107                                                 ? &PPC::VSFRCRegClass
3108                                                 : &PPC::F8RCRegClass);
3109
3110         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3111         ++FPR_idx;
3112       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3113         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3114         // once we support fp <-> gpr moves.
3115
3116         // This can only ever happen in the presence of f32 array types,
3117         // since otherwise we never run out of FPRs before running out
3118         // of GPRs.
3119         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3120         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3121
3122         if (ObjectVT == MVT::f32) {
3123           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3124             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3125                                  DAG.getConstant(32, MVT::i32));
3126           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3127         }
3128
3129         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3130       } else {
3131         if (CallConv == CallingConv::Fast)
3132           ComputeArgOffset();
3133
3134         needsLoad = true;
3135       }
3136
3137       // When passing an array of floats, the array occupies consecutive
3138       // space in the argument area; only round up to the next doubleword
3139       // at the end of the array.  Otherwise, each float takes 8 bytes.
3140       if (CallConv != CallingConv::Fast || needsLoad) {
3141         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3142         ArgOffset += ArgSize;
3143         if (Flags.isInConsecutiveRegsLast())
3144           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3145       }
3146       break;
3147     case MVT::v4f32:
3148     case MVT::v4i32:
3149     case MVT::v8i16:
3150     case MVT::v16i8:
3151     case MVT::v2f64:
3152     case MVT::v2i64:
3153       if (!Subtarget.hasQPX()) {
3154       // These can be scalar arguments or elements of a vector array type
3155       // passed directly.  The latter are used to implement ELFv2 homogenous
3156       // vector aggregates.
3157       if (VR_idx != Num_VR_Regs) {
3158         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3159                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3160                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3161         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3162         ++VR_idx;
3163       } else {
3164         if (CallConv == CallingConv::Fast)
3165           ComputeArgOffset();
3166
3167         needsLoad = true;
3168       }
3169       if (CallConv != CallingConv::Fast || needsLoad)
3170         ArgOffset += 16;
3171       break;
3172       } // not QPX
3173
3174       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3175              "Invalid QPX parameter type");
3176       /* fall through */
3177
3178     case MVT::v4f64:
3179     case MVT::v4i1:
3180       // QPX vectors are treated like their scalar floating-point subregisters
3181       // (except that they're larger).
3182       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3183       if (QFPR_idx != Num_QFPR_Regs) {
3184         const TargetRegisterClass *RC;
3185         switch (ObjectVT.getSimpleVT().SimpleTy) {
3186         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3187         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3188         default:         RC = &PPC::QBRCRegClass; break;
3189         }
3190
3191         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3192         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3193         ++QFPR_idx;
3194       } else {
3195         if (CallConv == CallingConv::Fast)
3196           ComputeArgOffset();
3197         needsLoad = true;
3198       }
3199       if (CallConv != CallingConv::Fast || needsLoad)
3200         ArgOffset += Sz;
3201       break;
3202     }
3203
3204     // We need to load the argument to a virtual register if we determined
3205     // above that we ran out of physical registers of the appropriate type.
3206     if (needsLoad) {
3207       if (ObjSize < ArgSize && !isLittleEndian)
3208         CurArgOffset += ArgSize - ObjSize;
3209       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3210       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3211       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3212                            false, false, false, 0);
3213     }
3214
3215     InVals.push_back(ArgVal);
3216   }
3217
3218   // Area that is at least reserved in the caller of this function.
3219   unsigned MinReservedArea;
3220   if (HasParameterArea)
3221     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3222   else
3223     MinReservedArea = LinkageSize;
3224
3225   // Set the size that is at least reserved in caller of this function.  Tail
3226   // call optimized functions' reserved stack space needs to be aligned so that
3227   // taking the difference between two stack areas will result in an aligned
3228   // stack.
3229   MinReservedArea =
3230       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3231   FuncInfo->setMinReservedArea(MinReservedArea);
3232
3233   // If the function takes variable number of arguments, make a frame index for
3234   // the start of the first vararg value... for expansion of llvm.va_start.
3235   if (isVarArg) {
3236     int Depth = ArgOffset;
3237
3238     FuncInfo->setVarArgsFrameIndex(
3239       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3240     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3241
3242     // If this function is vararg, store any remaining integer argument regs
3243     // to their spots on the stack so that they may be loaded by deferencing the
3244     // result of va_next.
3245     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3246          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3247       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3248       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3249       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3250                                    MachinePointerInfo(), false, false, 0);
3251       MemOps.push_back(Store);
3252       // Increment the address by four for the next argument to store
3253       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3254       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3255     }
3256   }
3257
3258   if (!MemOps.empty())
3259     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3260
3261   return Chain;
3262 }
3263
3264 SDValue
3265 PPCTargetLowering::LowerFormalArguments_Darwin(
3266                                       SDValue Chain,
3267                                       CallingConv::ID CallConv, bool isVarArg,
3268                                       const SmallVectorImpl<ISD::InputArg>
3269                                         &Ins,
3270                                       SDLoc dl, SelectionDAG &DAG,
3271                                       SmallVectorImpl<SDValue> &InVals) const {
3272   // TODO: add description of PPC stack frame format, or at least some docs.
3273   //
3274   MachineFunction &MF = DAG.getMachineFunction();
3275   MachineFrameInfo *MFI = MF.getFrameInfo();
3276   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3277
3278   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3279   bool isPPC64 = PtrVT == MVT::i64;
3280   // Potential tail calls could cause overwriting of argument stack slots.
3281   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3282                        (CallConv == CallingConv::Fast));
3283   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3284   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3285   unsigned ArgOffset = LinkageSize;
3286   // Area that is at least reserved in caller of this function.
3287   unsigned MinReservedArea = ArgOffset;
3288
3289   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3290     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3291     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3292   };
3293   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3294     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3295     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3296   };
3297   static const MCPhysReg VR[] = {
3298     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3299     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3300   };
3301
3302   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3303   const unsigned Num_FPR_Regs = 13;
3304   const unsigned Num_VR_Regs  = array_lengthof( VR);
3305
3306   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3307
3308   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3309
3310   // In 32-bit non-varargs functions, the stack space for vectors is after the
3311   // stack space for non-vectors.  We do not use this space unless we have
3312   // too many vectors to fit in registers, something that only occurs in
3313   // constructed examples:), but we have to walk the arglist to figure
3314   // that out...for the pathological case, compute VecArgOffset as the
3315   // start of the vector parameter area.  Computing VecArgOffset is the
3316   // entire point of the following loop.
3317   unsigned VecArgOffset = ArgOffset;
3318   if (!isVarArg && !isPPC64) {
3319     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3320          ++ArgNo) {
3321       EVT ObjectVT = Ins[ArgNo].VT;
3322       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3323
3324       if (Flags.isByVal()) {
3325         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3326         unsigned ObjSize = Flags.getByValSize();
3327         unsigned ArgSize =
3328                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3329         VecArgOffset += ArgSize;
3330         continue;
3331       }
3332
3333       switch(ObjectVT.getSimpleVT().SimpleTy) {
3334       default: llvm_unreachable("Unhandled argument type!");
3335       case MVT::i1:
3336       case MVT::i32:
3337       case MVT::f32:
3338         VecArgOffset += 4;
3339         break;
3340       case MVT::i64:  // PPC64
3341       case MVT::f64:
3342         // FIXME: We are guaranteed to be !isPPC64 at this point.
3343         // Does MVT::i64 apply?
3344         VecArgOffset += 8;
3345         break;
3346       case MVT::v4f32:
3347       case MVT::v4i32:
3348       case MVT::v8i16:
3349       case MVT::v16i8:
3350         // Nothing to do, we're only looking at Nonvector args here.
3351         break;
3352       }
3353     }
3354   }
3355   // We've found where the vector parameter area in memory is.  Skip the
3356   // first 12 parameters; these don't use that memory.
3357   VecArgOffset = ((VecArgOffset+15)/16)*16;
3358   VecArgOffset += 12*16;
3359
3360   // Add DAG nodes to load the arguments or copy them out of registers.  On
3361   // entry to a function on PPC, the arguments start after the linkage area,
3362   // although the first ones are often in registers.
3363
3364   SmallVector<SDValue, 8> MemOps;
3365   unsigned nAltivecParamsAtEnd = 0;
3366   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3367   unsigned CurArgIdx = 0;
3368   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3369     SDValue ArgVal;
3370     bool needsLoad = false;
3371     EVT ObjectVT = Ins[ArgNo].VT;
3372     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3373     unsigned ArgSize = ObjSize;
3374     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3375     if (Ins[ArgNo].isOrigArg()) {
3376       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3377       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3378     }
3379     unsigned CurArgOffset = ArgOffset;
3380
3381     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3382     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3383         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3384       if (isVarArg || isPPC64) {
3385         MinReservedArea = ((MinReservedArea+15)/16)*16;
3386         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3387                                                   Flags,
3388                                                   PtrByteSize);
3389       } else  nAltivecParamsAtEnd++;
3390     } else
3391       // Calculate min reserved area.
3392       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3393                                                 Flags,
3394                                                 PtrByteSize);
3395
3396     // FIXME the codegen can be much improved in some cases.
3397     // We do not have to keep everything in memory.
3398     if (Flags.isByVal()) {
3399       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3400
3401       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3402       ObjSize = Flags.getByValSize();
3403       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3404       // Objects of size 1 and 2 are right justified, everything else is
3405       // left justified.  This means the memory address is adjusted forwards.
3406       if (ObjSize==1 || ObjSize==2) {
3407         CurArgOffset = CurArgOffset + (4 - ObjSize);
3408       }
3409       // The value of the object is its address.
3410       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3411       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3412       InVals.push_back(FIN);
3413       if (ObjSize==1 || ObjSize==2) {
3414         if (GPR_idx != Num_GPR_Regs) {
3415           unsigned VReg;
3416           if (isPPC64)
3417             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3418           else
3419             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3420           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3421           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3422           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3423                                             MachinePointerInfo(FuncArg),
3424                                             ObjType, false, false, 0);
3425           MemOps.push_back(Store);
3426           ++GPR_idx;
3427         }
3428
3429         ArgOffset += PtrByteSize;
3430
3431         continue;
3432       }
3433       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3434         // Store whatever pieces of the object are in registers
3435         // to memory.  ArgOffset will be the address of the beginning
3436         // of the object.
3437         if (GPR_idx != Num_GPR_Regs) {
3438           unsigned VReg;
3439           if (isPPC64)
3440             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3441           else
3442             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3443           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3444           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3445           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3446           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3447                                        MachinePointerInfo(FuncArg, j),
3448                                        false, false, 0);
3449           MemOps.push_back(Store);
3450           ++GPR_idx;
3451           ArgOffset += PtrByteSize;
3452         } else {
3453           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3454           break;
3455         }
3456       }
3457       continue;
3458     }
3459
3460     switch (ObjectVT.getSimpleVT().SimpleTy) {
3461     default: llvm_unreachable("Unhandled argument type!");
3462     case MVT::i1:
3463     case MVT::i32:
3464       if (!isPPC64) {
3465         if (GPR_idx != Num_GPR_Regs) {
3466           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3467           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3468
3469           if (ObjectVT == MVT::i1)
3470             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3471
3472           ++GPR_idx;
3473         } else {
3474           needsLoad = true;
3475           ArgSize = PtrByteSize;
3476         }
3477         // All int arguments reserve stack space in the Darwin ABI.
3478         ArgOffset += PtrByteSize;
3479         break;
3480       }
3481       // FALLTHROUGH
3482     case MVT::i64:  // PPC64
3483       if (GPR_idx != Num_GPR_Regs) {
3484         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3485         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3486
3487         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3488           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3489           // value to MVT::i64 and then truncate to the correct register size.
3490           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3491
3492         ++GPR_idx;
3493       } else {
3494         needsLoad = true;
3495         ArgSize = PtrByteSize;
3496       }
3497       // All int arguments reserve stack space in the Darwin ABI.
3498       ArgOffset += 8;
3499       break;
3500
3501     case MVT::f32:
3502     case MVT::f64:
3503       // Every 4 bytes of argument space consumes one of the GPRs available for
3504       // argument passing.
3505       if (GPR_idx != Num_GPR_Regs) {
3506         ++GPR_idx;
3507         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3508           ++GPR_idx;
3509       }
3510       if (FPR_idx != Num_FPR_Regs) {
3511         unsigned VReg;
3512
3513         if (ObjectVT == MVT::f32)
3514           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3515         else
3516           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3517
3518         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3519         ++FPR_idx;
3520       } else {
3521         needsLoad = true;
3522       }
3523
3524       // All FP arguments reserve stack space in the Darwin ABI.
3525       ArgOffset += isPPC64 ? 8 : ObjSize;
3526       break;
3527     case MVT::v4f32:
3528     case MVT::v4i32:
3529     case MVT::v8i16:
3530     case MVT::v16i8:
3531       // Note that vector arguments in registers don't reserve stack space,
3532       // except in varargs functions.
3533       if (VR_idx != Num_VR_Regs) {
3534         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3535         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3536         if (isVarArg) {
3537           while ((ArgOffset % 16) != 0) {
3538             ArgOffset += PtrByteSize;
3539             if (GPR_idx != Num_GPR_Regs)
3540               GPR_idx++;
3541           }
3542           ArgOffset += 16;
3543           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3544         }
3545         ++VR_idx;
3546       } else {
3547         if (!isVarArg && !isPPC64) {
3548           // Vectors go after all the nonvectors.
3549           CurArgOffset = VecArgOffset;
3550           VecArgOffset += 16;
3551         } else {
3552           // Vectors are aligned.
3553           ArgOffset = ((ArgOffset+15)/16)*16;
3554           CurArgOffset = ArgOffset;
3555           ArgOffset += 16;
3556         }
3557         needsLoad = true;
3558       }
3559       break;
3560     }
3561
3562     // We need to load the argument to a virtual register if we determined above
3563     // that we ran out of physical registers of the appropriate type.
3564     if (needsLoad) {
3565       int FI = MFI->CreateFixedObject(ObjSize,
3566                                       CurArgOffset + (ArgSize - ObjSize),
3567                                       isImmutable);
3568       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3569       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3570                            false, false, false, 0);
3571     }
3572
3573     InVals.push_back(ArgVal);
3574   }
3575
3576   // Allow for Altivec parameters at the end, if needed.
3577   if (nAltivecParamsAtEnd) {
3578     MinReservedArea = ((MinReservedArea+15)/16)*16;
3579     MinReservedArea += 16*nAltivecParamsAtEnd;
3580   }
3581
3582   // Area that is at least reserved in the caller of this function.
3583   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3584
3585   // Set the size that is at least reserved in caller of this function.  Tail
3586   // call optimized functions' reserved stack space needs to be aligned so that
3587   // taking the difference between two stack areas will result in an aligned
3588   // stack.
3589   MinReservedArea =
3590       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3591   FuncInfo->setMinReservedArea(MinReservedArea);
3592
3593   // If the function takes variable number of arguments, make a frame index for
3594   // the start of the first vararg value... for expansion of llvm.va_start.
3595   if (isVarArg) {
3596     int Depth = ArgOffset;
3597
3598     FuncInfo->setVarArgsFrameIndex(
3599       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3600                              Depth, true));
3601     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3602
3603     // If this function is vararg, store any remaining integer argument regs
3604     // to their spots on the stack so that they may be loaded by deferencing the
3605     // result of va_next.
3606     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3607       unsigned VReg;
3608
3609       if (isPPC64)
3610         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3611       else
3612         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3613
3614       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3615       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3616                                    MachinePointerInfo(), false, false, 0);
3617       MemOps.push_back(Store);
3618       // Increment the address by four for the next argument to store
3619       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3620       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3621     }
3622   }
3623
3624   if (!MemOps.empty())
3625     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3626
3627   return Chain;
3628 }
3629
3630 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3631 /// adjusted to accommodate the arguments for the tailcall.
3632 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3633                                    unsigned ParamSize) {
3634
3635   if (!isTailCall) return 0;
3636
3637   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3638   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3639   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3640   // Remember only if the new adjustement is bigger.
3641   if (SPDiff < FI->getTailCallSPDelta())
3642     FI->setTailCallSPDelta(SPDiff);
3643
3644   return SPDiff;
3645 }
3646
3647 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3648 /// for tail call optimization. Targets which want to do tail call
3649 /// optimization should implement this function.
3650 bool
3651 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3652                                                      CallingConv::ID CalleeCC,
3653                                                      bool isVarArg,
3654                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3655                                                      SelectionDAG& DAG) const {
3656   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3657     return false;
3658
3659   // Variable argument functions are not supported.
3660   if (isVarArg)
3661     return false;
3662
3663   MachineFunction &MF = DAG.getMachineFunction();
3664   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3665   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3666     // Functions containing by val parameters are not supported.
3667     for (unsigned i = 0; i != Ins.size(); i++) {
3668        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3669        if (Flags.isByVal()) return false;
3670     }
3671
3672     // Non-PIC/GOT tail calls are supported.
3673     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3674       return true;
3675
3676     // At the moment we can only do local tail calls (in same module, hidden
3677     // or protected) if we are generating PIC.
3678     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3679       return G->getGlobal()->hasHiddenVisibility()
3680           || G->getGlobal()->hasProtectedVisibility();
3681   }
3682
3683   return false;
3684 }
3685
3686 /// isCallCompatibleAddress - Return the immediate to use if the specified
3687 /// 32-bit value is representable in the immediate field of a BxA instruction.
3688 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3689   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3690   if (!C) return nullptr;
3691
3692   int Addr = C->getZExtValue();
3693   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3694       SignExtend32<26>(Addr) != Addr)
3695     return nullptr;  // Top 6 bits have to be sext of immediate.
3696
3697   return DAG.getConstant((int)C->getZExtValue() >> 2,
3698                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3699 }
3700
3701 namespace {
3702
3703 struct TailCallArgumentInfo {
3704   SDValue Arg;
3705   SDValue FrameIdxOp;
3706   int       FrameIdx;
3707
3708   TailCallArgumentInfo() : FrameIdx(0) {}
3709 };
3710
3711 }
3712
3713 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3714 static void
3715 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3716                                            SDValue Chain,
3717                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3718                    SmallVectorImpl<SDValue> &MemOpChains,
3719                    SDLoc dl) {
3720   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3721     SDValue Arg = TailCallArgs[i].Arg;
3722     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3723     int FI = TailCallArgs[i].FrameIdx;
3724     // Store relative to framepointer.
3725     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3726                                        MachinePointerInfo::getFixedStack(FI),
3727                                        false, false, 0));
3728   }
3729 }
3730
3731 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3732 /// the appropriate stack slot for the tail call optimized function call.
3733 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3734                                                MachineFunction &MF,
3735                                                SDValue Chain,
3736                                                SDValue OldRetAddr,
3737                                                SDValue OldFP,
3738                                                int SPDiff,
3739                                                bool isPPC64,
3740                                                bool isDarwinABI,
3741                                                SDLoc dl) {
3742   if (SPDiff) {
3743     // Calculate the new stack slot for the return address.
3744     int SlotSize = isPPC64 ? 8 : 4;
3745     const PPCFrameLowering *FL =
3746         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3747     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3748     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3749                                                           NewRetAddrLoc, true);
3750     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3751     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3752     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3753                          MachinePointerInfo::getFixedStack(NewRetAddr),
3754                          false, false, 0);
3755
3756     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3757     // slot as the FP is never overwritten.
3758     if (isDarwinABI) {
3759       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3760       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3761                                                           true);
3762       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3763       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3764                            MachinePointerInfo::getFixedStack(NewFPIdx),
3765                            false, false, 0);
3766     }
3767   }
3768   return Chain;
3769 }
3770
3771 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3772 /// the position of the argument.
3773 static void
3774 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3775                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3776                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3777   int Offset = ArgOffset + SPDiff;
3778   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3779   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3780   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3781   SDValue FIN = DAG.getFrameIndex(FI, VT);
3782   TailCallArgumentInfo Info;
3783   Info.Arg = Arg;
3784   Info.FrameIdxOp = FIN;
3785   Info.FrameIdx = FI;
3786   TailCallArguments.push_back(Info);
3787 }
3788
3789 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3790 /// stack slot. Returns the chain as result and the loaded frame pointers in
3791 /// LROpOut/FPOpout. Used when tail calling.
3792 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3793                                                         int SPDiff,
3794                                                         SDValue Chain,
3795                                                         SDValue &LROpOut,
3796                                                         SDValue &FPOpOut,
3797                                                         bool isDarwinABI,
3798                                                         SDLoc dl) const {
3799   if (SPDiff) {
3800     // Load the LR and FP stack slot for later adjusting.
3801     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3802     LROpOut = getReturnAddrFrameIndex(DAG);
3803     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3804                           false, false, false, 0);
3805     Chain = SDValue(LROpOut.getNode(), 1);
3806
3807     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3808     // slot as the FP is never overwritten.
3809     if (isDarwinABI) {
3810       FPOpOut = getFramePointerFrameIndex(DAG);
3811       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3812                             false, false, false, 0);
3813       Chain = SDValue(FPOpOut.getNode(), 1);
3814     }
3815   }
3816   return Chain;
3817 }
3818
3819 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3820 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3821 /// specified by the specific parameter attribute. The copy will be passed as
3822 /// a byval function parameter.
3823 /// Sometimes what we are copying is the end of a larger object, the part that
3824 /// does not fit in registers.
3825 static SDValue
3826 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3827                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3828                           SDLoc dl) {
3829   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3830   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3831                        false, false, MachinePointerInfo(),
3832                        MachinePointerInfo());
3833 }
3834
3835 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3836 /// tail calls.
3837 static void
3838 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3839                  SDValue Arg, SDValue PtrOff, int SPDiff,
3840                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3841                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3842                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3843                  SDLoc dl) {
3844   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3845   if (!isTailCall) {
3846     if (isVector) {
3847       SDValue StackPtr;
3848       if (isPPC64)
3849         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3850       else
3851         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3852       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3853                            DAG.getConstant(ArgOffset, PtrVT));
3854     }
3855     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3856                                        MachinePointerInfo(), false, false, 0));
3857   // Calculate and remember argument location.
3858   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3859                                   TailCallArguments);
3860 }
3861
3862 static
3863 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3864                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3865                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3866                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3867   MachineFunction &MF = DAG.getMachineFunction();
3868
3869   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3870   // might overwrite each other in case of tail call optimization.
3871   SmallVector<SDValue, 8> MemOpChains2;
3872   // Do not flag preceding copytoreg stuff together with the following stuff.
3873   InFlag = SDValue();
3874   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3875                                     MemOpChains2, dl);
3876   if (!MemOpChains2.empty())
3877     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3878
3879   // Store the return address to the appropriate stack slot.
3880   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3881                                         isPPC64, isDarwinABI, dl);
3882
3883   // Emit callseq_end just before tailcall node.
3884   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3885                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3886   InFlag = Chain.getValue(1);
3887 }
3888
3889 // Is this global address that of a function that can be called by name? (as
3890 // opposed to something that must hold a descriptor for an indirect call).
3891 static bool isFunctionGlobalAddress(SDValue Callee) {
3892   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3893     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3894         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3895       return false;
3896
3897     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3898   }
3899
3900   return false;
3901 }
3902
3903 static
3904 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3905                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3906                      bool isTailCall, bool IsPatchPoint,
3907                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3908                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3909                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3910
3911   bool isPPC64 = Subtarget.isPPC64();
3912   bool isSVR4ABI = Subtarget.isSVR4ABI();
3913   bool isELFv2ABI = Subtarget.isELFv2ABI();
3914
3915   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3916   NodeTys.push_back(MVT::Other);   // Returns a chain
3917   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3918
3919   unsigned CallOpc = PPCISD::CALL;
3920
3921   bool needIndirectCall = true;
3922   if (!isSVR4ABI || !isPPC64)
3923     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3924       // If this is an absolute destination address, use the munged value.
3925       Callee = SDValue(Dest, 0);
3926       needIndirectCall = false;
3927     }
3928
3929   if (isFunctionGlobalAddress(Callee)) {
3930     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3931     // A call to a TLS address is actually an indirect call to a
3932     // thread-specific pointer.
3933     unsigned OpFlags = 0;
3934     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3935          (Subtarget.getTargetTriple().isMacOSX() &&
3936           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3937          (G->getGlobal()->isDeclaration() ||
3938           G->getGlobal()->isWeakForLinker())) ||
3939         (Subtarget.isTargetELF() && !isPPC64 &&
3940          !G->getGlobal()->hasLocalLinkage() &&
3941          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3942       // PC-relative references to external symbols should go through $stub,
3943       // unless we're building with the leopard linker or later, which
3944       // automatically synthesizes these stubs.
3945       OpFlags = PPCII::MO_PLT_OR_STUB;
3946     }
3947
3948     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3949     // every direct call is) turn it into a TargetGlobalAddress /
3950     // TargetExternalSymbol node so that legalize doesn't hack it.
3951     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3952                                         Callee.getValueType(), 0, OpFlags);
3953     needIndirectCall = false;
3954   }
3955
3956   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3957     unsigned char OpFlags = 0;
3958
3959     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3960          (Subtarget.getTargetTriple().isMacOSX() &&
3961           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3962         (Subtarget.isTargetELF() && !isPPC64 &&
3963          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3964       // PC-relative references to external symbols should go through $stub,
3965       // unless we're building with the leopard linker or later, which
3966       // automatically synthesizes these stubs.
3967       OpFlags = PPCII::MO_PLT_OR_STUB;
3968     }
3969
3970     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3971                                          OpFlags);
3972     needIndirectCall = false;
3973   }
3974
3975   if (IsPatchPoint) {
3976     // We'll form an invalid direct call when lowering a patchpoint; the full
3977     // sequence for an indirect call is complicated, and many of the
3978     // instructions introduced might have side effects (and, thus, can't be
3979     // removed later). The call itself will be removed as soon as the
3980     // argument/return lowering is complete, so the fact that it has the wrong
3981     // kind of operands should not really matter.
3982     needIndirectCall = false;
3983   }
3984
3985   if (needIndirectCall) {
3986     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3987     // to do the call, we can't use PPCISD::CALL.
3988     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3989
3990     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3991       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3992       // entry point, but to the function descriptor (the function entry point
3993       // address is part of the function descriptor though).
3994       // The function descriptor is a three doubleword structure with the
3995       // following fields: function entry point, TOC base address and
3996       // environment pointer.
3997       // Thus for a call through a function pointer, the following actions need
3998       // to be performed:
3999       //   1. Save the TOC of the caller in the TOC save area of its stack
4000       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4001       //   2. Load the address of the function entry point from the function
4002       //      descriptor.
4003       //   3. Load the TOC of the callee from the function descriptor into r2.
4004       //   4. Load the environment pointer from the function descriptor into
4005       //      r11.
4006       //   5. Branch to the function entry point address.
4007       //   6. On return of the callee, the TOC of the caller needs to be
4008       //      restored (this is done in FinishCall()).
4009       //
4010       // The loads are scheduled at the beginning of the call sequence, and the
4011       // register copies are flagged together to ensure that no other
4012       // operations can be scheduled in between. E.g. without flagging the
4013       // copies together, a TOC access in the caller could be scheduled between
4014       // the assignment of the callee TOC and the branch to the callee, which
4015       // results in the TOC access going through the TOC of the callee instead
4016       // of going through the TOC of the caller, which leads to incorrect code.
4017
4018       // Load the address of the function entry point from the function
4019       // descriptor.
4020       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4021       if (LDChain.getValueType() == MVT::Glue)
4022         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4023
4024       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4025
4026       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4027       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4028                                         false, false, LoadsInv, 8);
4029
4030       // Load environment pointer into r11.
4031       SDValue PtrOff = DAG.getIntPtrConstant(16);
4032       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4033       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4034                                        MPI.getWithOffset(16), false, false,
4035                                        LoadsInv, 8);
4036
4037       SDValue TOCOff = DAG.getIntPtrConstant(8);
4038       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4039       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4040                                    MPI.getWithOffset(8), false, false,
4041                                    LoadsInv, 8);
4042
4043       setUsesTOCBasePtr(DAG);
4044       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4045                                         InFlag);
4046       Chain = TOCVal.getValue(0);
4047       InFlag = TOCVal.getValue(1);
4048
4049       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4050                                         InFlag);
4051
4052       Chain = EnvVal.getValue(0);
4053       InFlag = EnvVal.getValue(1);
4054
4055       MTCTROps[0] = Chain;
4056       MTCTROps[1] = LoadFuncPtr;
4057       MTCTROps[2] = InFlag;
4058     }
4059
4060     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4061                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4062     InFlag = Chain.getValue(1);
4063
4064     NodeTys.clear();
4065     NodeTys.push_back(MVT::Other);
4066     NodeTys.push_back(MVT::Glue);
4067     Ops.push_back(Chain);
4068     CallOpc = PPCISD::BCTRL;
4069     Callee.setNode(nullptr);
4070     // Add use of X11 (holding environment pointer)
4071     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4072       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4073     // Add CTR register as callee so a bctr can be emitted later.
4074     if (isTailCall)
4075       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4076   }
4077
4078   // If this is a direct call, pass the chain and the callee.
4079   if (Callee.getNode()) {
4080     Ops.push_back(Chain);
4081     Ops.push_back(Callee);
4082   }
4083   // If this is a tail call add stack pointer delta.
4084   if (isTailCall)
4085     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4086
4087   // Add argument registers to the end of the list so that they are known live
4088   // into the call.
4089   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4090     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4091                                   RegsToPass[i].second.getValueType()));
4092
4093   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4094   // into the call.
4095   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4096     setUsesTOCBasePtr(DAG);
4097     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4098   }
4099
4100   return CallOpc;
4101 }
4102
4103 static
4104 bool isLocalCall(const SDValue &Callee)
4105 {
4106   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4107     return !G->getGlobal()->isDeclaration() &&
4108            !G->getGlobal()->isWeakForLinker();
4109   return false;
4110 }
4111
4112 SDValue
4113 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4114                                    CallingConv::ID CallConv, bool isVarArg,
4115                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4116                                    SDLoc dl, SelectionDAG &DAG,
4117                                    SmallVectorImpl<SDValue> &InVals) const {
4118
4119   SmallVector<CCValAssign, 16> RVLocs;
4120   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4121                     *DAG.getContext());
4122   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4123
4124   // Copy all of the result registers out of their specified physreg.
4125   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4126     CCValAssign &VA = RVLocs[i];
4127     assert(VA.isRegLoc() && "Can only return in registers!");
4128
4129     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4130                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4131     Chain = Val.getValue(1);
4132     InFlag = Val.getValue(2);
4133
4134     switch (VA.getLocInfo()) {
4135     default: llvm_unreachable("Unknown loc info!");
4136     case CCValAssign::Full: break;
4137     case CCValAssign::AExt:
4138       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4139       break;
4140     case CCValAssign::ZExt:
4141       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4142                         DAG.getValueType(VA.getValVT()));
4143       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4144       break;
4145     case CCValAssign::SExt:
4146       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4147                         DAG.getValueType(VA.getValVT()));
4148       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4149       break;
4150     }
4151
4152     InVals.push_back(Val);
4153   }
4154
4155   return Chain;
4156 }
4157
4158 SDValue
4159 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4160                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4161                               SelectionDAG &DAG,
4162                               SmallVector<std::pair<unsigned, SDValue>, 8>
4163                                 &RegsToPass,
4164                               SDValue InFlag, SDValue Chain,
4165                               SDValue CallSeqStart, SDValue &Callee,
4166                               int SPDiff, unsigned NumBytes,
4167                               const SmallVectorImpl<ISD::InputArg> &Ins,
4168                               SmallVectorImpl<SDValue> &InVals,
4169                               ImmutableCallSite *CS) const {
4170
4171   std::vector<EVT> NodeTys;
4172   SmallVector<SDValue, 8> Ops;
4173   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4174                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4175                                  Ops, NodeTys, CS, Subtarget);
4176
4177   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4178   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4179     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4180
4181   // When performing tail call optimization the callee pops its arguments off
4182   // the stack. Account for this here so these bytes can be pushed back on in
4183   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4184   int BytesCalleePops =
4185     (CallConv == CallingConv::Fast &&
4186      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4187
4188   // Add a register mask operand representing the call-preserved registers.
4189   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4190   const uint32_t *Mask =
4191       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4192   assert(Mask && "Missing call preserved mask for calling convention");
4193   Ops.push_back(DAG.getRegisterMask(Mask));
4194
4195   if (InFlag.getNode())
4196     Ops.push_back(InFlag);
4197
4198   // Emit tail call.
4199   if (isTailCall) {
4200     assert(((Callee.getOpcode() == ISD::Register &&
4201              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4202             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4203             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4204             isa<ConstantSDNode>(Callee)) &&
4205     "Expecting an global address, external symbol, absolute value or register");
4206
4207     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4208   }
4209
4210   // Add a NOP immediately after the branch instruction when using the 64-bit
4211   // SVR4 ABI. At link time, if caller and callee are in a different module and
4212   // thus have a different TOC, the call will be replaced with a call to a stub
4213   // function which saves the current TOC, loads the TOC of the callee and
4214   // branches to the callee. The NOP will be replaced with a load instruction
4215   // which restores the TOC of the caller from the TOC save slot of the current
4216   // stack frame. If caller and callee belong to the same module (and have the
4217   // same TOC), the NOP will remain unchanged.
4218
4219   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4220       !IsPatchPoint) {
4221     if (CallOpc == PPCISD::BCTRL) {
4222       // This is a call through a function pointer.
4223       // Restore the caller TOC from the save area into R2.
4224       // See PrepareCall() for more information about calls through function
4225       // pointers in the 64-bit SVR4 ABI.
4226       // We are using a target-specific load with r2 hard coded, because the
4227       // result of a target-independent load would never go directly into r2,
4228       // since r2 is a reserved register (which prevents the register allocator
4229       // from allocating it), resulting in an additional register being
4230       // allocated and an unnecessary move instruction being generated.
4231       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4232
4233       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4234       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4235       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4236       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4237       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4238
4239       // The address needs to go after the chain input but before the flag (or
4240       // any other variadic arguments).
4241       Ops.insert(std::next(Ops.begin()), AddTOC);
4242     } else if ((CallOpc == PPCISD::CALL) &&
4243                (!isLocalCall(Callee) ||
4244                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4245       // Otherwise insert NOP for non-local calls.
4246       CallOpc = PPCISD::CALL_NOP;
4247   }
4248
4249   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4250   InFlag = Chain.getValue(1);
4251
4252   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4253                              DAG.getIntPtrConstant(BytesCalleePops, true),
4254                              InFlag, dl);
4255   if (!Ins.empty())
4256     InFlag = Chain.getValue(1);
4257
4258   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4259                          Ins, dl, DAG, InVals);
4260 }
4261
4262 SDValue
4263 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4264                              SmallVectorImpl<SDValue> &InVals) const {
4265   SelectionDAG &DAG                     = CLI.DAG;
4266   SDLoc &dl                             = CLI.DL;
4267   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4268   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4269   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4270   SDValue Chain                         = CLI.Chain;
4271   SDValue Callee                        = CLI.Callee;
4272   bool &isTailCall                      = CLI.IsTailCall;
4273   CallingConv::ID CallConv              = CLI.CallConv;
4274   bool isVarArg                         = CLI.IsVarArg;
4275   bool IsPatchPoint                     = CLI.IsPatchPoint;
4276   ImmutableCallSite *CS                 = CLI.CS;
4277
4278   if (isTailCall)
4279     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4280                                                    Ins, DAG);
4281
4282   if (!isTailCall && CS && CS->isMustTailCall())
4283     report_fatal_error("failed to perform tail call elimination on a call "
4284                        "site marked musttail");
4285
4286   if (Subtarget.isSVR4ABI()) {
4287     if (Subtarget.isPPC64())
4288       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4289                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4290                               dl, DAG, InVals, CS);
4291     else
4292       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4293                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4294                               dl, DAG, InVals, CS);
4295   }
4296
4297   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4298                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4299                           dl, DAG, InVals, CS);
4300 }
4301
4302 SDValue
4303 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4304                                     CallingConv::ID CallConv, bool isVarArg,
4305                                     bool isTailCall, bool IsPatchPoint,
4306                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4307                                     const SmallVectorImpl<SDValue> &OutVals,
4308                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4309                                     SDLoc dl, SelectionDAG &DAG,
4310                                     SmallVectorImpl<SDValue> &InVals,
4311                                     ImmutableCallSite *CS) const {
4312   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4313   // of the 32-bit SVR4 ABI stack frame layout.
4314
4315   assert((CallConv == CallingConv::C ||
4316           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4317
4318   unsigned PtrByteSize = 4;
4319
4320   MachineFunction &MF = DAG.getMachineFunction();
4321
4322   // Mark this function as potentially containing a function that contains a
4323   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4324   // and restoring the callers stack pointer in this functions epilog. This is
4325   // done because by tail calling the called function might overwrite the value
4326   // in this function's (MF) stack pointer stack slot 0(SP).
4327   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4328       CallConv == CallingConv::Fast)
4329     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4330
4331   // Count how many bytes are to be pushed on the stack, including the linkage
4332   // area, parameter list area and the part of the local variable space which
4333   // contains copies of aggregates which are passed by value.
4334
4335   // Assign locations to all of the outgoing arguments.
4336   SmallVector<CCValAssign, 16> ArgLocs;
4337   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4338                  *DAG.getContext());
4339
4340   // Reserve space for the linkage area on the stack.
4341   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4342                        PtrByteSize);
4343
4344   if (isVarArg) {
4345     // Handle fixed and variable vector arguments differently.
4346     // Fixed vector arguments go into registers as long as registers are
4347     // available. Variable vector arguments always go into memory.
4348     unsigned NumArgs = Outs.size();
4349
4350     for (unsigned i = 0; i != NumArgs; ++i) {
4351       MVT ArgVT = Outs[i].VT;
4352       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4353       bool Result;
4354
4355       if (Outs[i].IsFixed) {
4356         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4357                                CCInfo);
4358       } else {
4359         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4360                                       ArgFlags, CCInfo);
4361       }
4362
4363       if (Result) {
4364 #ifndef NDEBUG
4365         errs() << "Call operand #" << i << " has unhandled type "
4366              << EVT(ArgVT).getEVTString() << "\n";
4367 #endif
4368         llvm_unreachable(nullptr);
4369       }
4370     }
4371   } else {
4372     // All arguments are treated the same.
4373     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4374   }
4375
4376   // Assign locations to all of the outgoing aggregate by value arguments.
4377   SmallVector<CCValAssign, 16> ByValArgLocs;
4378   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4379                       ByValArgLocs, *DAG.getContext());
4380
4381   // Reserve stack space for the allocations in CCInfo.
4382   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4383
4384   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4385
4386   // Size of the linkage area, parameter list area and the part of the local
4387   // space variable where copies of aggregates which are passed by value are
4388   // stored.
4389   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4390
4391   // Calculate by how many bytes the stack has to be adjusted in case of tail
4392   // call optimization.
4393   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4394
4395   // Adjust the stack pointer for the new arguments...
4396   // These operations are automatically eliminated by the prolog/epilog pass
4397   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4398                                dl);
4399   SDValue CallSeqStart = Chain;
4400
4401   // Load the return address and frame pointer so it can be moved somewhere else
4402   // later.
4403   SDValue LROp, FPOp;
4404   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4405                                        dl);
4406
4407   // Set up a copy of the stack pointer for use loading and storing any
4408   // arguments that may not fit in the registers available for argument
4409   // passing.
4410   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4411
4412   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4413   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4414   SmallVector<SDValue, 8> MemOpChains;
4415
4416   bool seenFloatArg = false;
4417   // Walk the register/memloc assignments, inserting copies/loads.
4418   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4419        i != e;
4420        ++i) {
4421     CCValAssign &VA = ArgLocs[i];
4422     SDValue Arg = OutVals[i];
4423     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4424
4425     if (Flags.isByVal()) {
4426       // Argument is an aggregate which is passed by value, thus we need to
4427       // create a copy of it in the local variable space of the current stack
4428       // frame (which is the stack frame of the caller) and pass the address of
4429       // this copy to the callee.
4430       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4431       CCValAssign &ByValVA = ByValArgLocs[j++];
4432       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4433
4434       // Memory reserved in the local variable space of the callers stack frame.
4435       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4436
4437       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4438       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4439
4440       // Create a copy of the argument in the local area of the current
4441       // stack frame.
4442       SDValue MemcpyCall =
4443         CreateCopyOfByValArgument(Arg, PtrOff,
4444                                   CallSeqStart.getNode()->getOperand(0),
4445                                   Flags, DAG, dl);
4446
4447       // This must go outside the CALLSEQ_START..END.
4448       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4449                            CallSeqStart.getNode()->getOperand(1),
4450                            SDLoc(MemcpyCall));
4451       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4452                              NewCallSeqStart.getNode());
4453       Chain = CallSeqStart = NewCallSeqStart;
4454
4455       // Pass the address of the aggregate copy on the stack either in a
4456       // physical register or in the parameter list area of the current stack
4457       // frame to the callee.
4458       Arg = PtrOff;
4459     }
4460
4461     if (VA.isRegLoc()) {
4462       if (Arg.getValueType() == MVT::i1)
4463         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4464
4465       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4466       // Put argument in a physical register.
4467       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4468     } else {
4469       // Put argument in the parameter list area of the current stack frame.
4470       assert(VA.isMemLoc());
4471       unsigned LocMemOffset = VA.getLocMemOffset();
4472
4473       if (!isTailCall) {
4474         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4475         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4476
4477         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4478                                            MachinePointerInfo(),
4479                                            false, false, 0));
4480       } else {
4481         // Calculate and remember argument location.
4482         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4483                                  TailCallArguments);
4484       }
4485     }
4486   }
4487
4488   if (!MemOpChains.empty())
4489     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4490
4491   // Build a sequence of copy-to-reg nodes chained together with token chain
4492   // and flag operands which copy the outgoing args into the appropriate regs.
4493   SDValue InFlag;
4494   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4495     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4496                              RegsToPass[i].second, InFlag);
4497     InFlag = Chain.getValue(1);
4498   }
4499
4500   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4501   // registers.
4502   if (isVarArg) {
4503     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4504     SDValue Ops[] = { Chain, InFlag };
4505
4506     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4507                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4508
4509     InFlag = Chain.getValue(1);
4510   }
4511
4512   if (isTailCall)
4513     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4514                     false, TailCallArguments);
4515
4516   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4517                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4518                     NumBytes, Ins, InVals, CS);
4519 }
4520
4521 // Copy an argument into memory, being careful to do this outside the
4522 // call sequence for the call to which the argument belongs.
4523 SDValue
4524 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4525                                               SDValue CallSeqStart,
4526                                               ISD::ArgFlagsTy Flags,
4527                                               SelectionDAG &DAG,
4528                                               SDLoc dl) const {
4529   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4530                         CallSeqStart.getNode()->getOperand(0),
4531                         Flags, DAG, dl);
4532   // The MEMCPY must go outside the CALLSEQ_START..END.
4533   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4534                              CallSeqStart.getNode()->getOperand(1),
4535                              SDLoc(MemcpyCall));
4536   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4537                          NewCallSeqStart.getNode());
4538   return NewCallSeqStart;
4539 }
4540
4541 SDValue
4542 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4543                                     CallingConv::ID CallConv, bool isVarArg,
4544                                     bool isTailCall, bool IsPatchPoint,
4545                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4546                                     const SmallVectorImpl<SDValue> &OutVals,
4547                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4548                                     SDLoc dl, SelectionDAG &DAG,
4549                                     SmallVectorImpl<SDValue> &InVals,
4550                                     ImmutableCallSite *CS) const {
4551
4552   bool isELFv2ABI = Subtarget.isELFv2ABI();
4553   bool isLittleEndian = Subtarget.isLittleEndian();
4554   unsigned NumOps = Outs.size();
4555
4556   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4557   unsigned PtrByteSize = 8;
4558
4559   MachineFunction &MF = DAG.getMachineFunction();
4560
4561   // Mark this function as potentially containing a function that contains a
4562   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4563   // and restoring the callers stack pointer in this functions epilog. This is
4564   // done because by tail calling the called function might overwrite the value
4565   // in this function's (MF) stack pointer stack slot 0(SP).
4566   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4567       CallConv == CallingConv::Fast)
4568     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4569
4570   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4571          "fastcc not supported on varargs functions");
4572
4573   // Count how many bytes are to be pushed on the stack, including the linkage
4574   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4575   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4576   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4577   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4578   unsigned NumBytes = LinkageSize;
4579   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4580   unsigned &QFPR_idx = FPR_idx;
4581
4582   static const MCPhysReg GPR[] = {
4583     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4584     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4585   };
4586   static const MCPhysReg VR[] = {
4587     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4588     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4589   };
4590   static const MCPhysReg VSRH[] = {
4591     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4592     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4593   };
4594
4595   const unsigned NumGPRs = array_lengthof(GPR);
4596   const unsigned NumFPRs = 13;
4597   const unsigned NumVRs  = array_lengthof(VR);
4598   const unsigned NumQFPRs = NumFPRs;
4599
4600   // When using the fast calling convention, we don't provide backing for
4601   // arguments that will be in registers.
4602   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4603
4604   // Add up all the space actually used.
4605   for (unsigned i = 0; i != NumOps; ++i) {
4606     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4607     EVT ArgVT = Outs[i].VT;
4608     EVT OrigVT = Outs[i].ArgVT;
4609
4610     if (CallConv == CallingConv::Fast) {
4611       if (Flags.isByVal())
4612         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4613       else
4614         switch (ArgVT.getSimpleVT().SimpleTy) {
4615         default: llvm_unreachable("Unexpected ValueType for argument!");
4616         case MVT::i1:
4617         case MVT::i32:
4618         case MVT::i64:
4619           if (++NumGPRsUsed <= NumGPRs)
4620             continue;
4621           break;
4622         case MVT::v4i32:
4623         case MVT::v8i16:
4624         case MVT::v16i8:
4625         case MVT::v2f64:
4626         case MVT::v2i64:
4627           if (++NumVRsUsed <= NumVRs)
4628             continue;
4629           break;
4630         case MVT::v4f32:
4631           // When using QPX, this is handled like a FP register, otherwise, it
4632           // is an Altivec register.
4633           if (Subtarget.hasQPX()) {
4634             if (++NumFPRsUsed <= NumFPRs)
4635               continue;
4636           } else {
4637             if (++NumVRsUsed <= NumVRs)
4638               continue;
4639           }
4640           break;
4641         case MVT::f32:
4642         case MVT::f64:
4643         case MVT::v4f64: // QPX
4644         case MVT::v4i1:  // QPX
4645           if (++NumFPRsUsed <= NumFPRs)
4646             continue;
4647           break;
4648         }
4649     }
4650
4651     /* Respect alignment of argument on the stack.  */
4652     unsigned Align =
4653       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4654     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4655
4656     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4657     if (Flags.isInConsecutiveRegsLast())
4658       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4659   }
4660
4661   unsigned NumBytesActuallyUsed = NumBytes;
4662
4663   // The prolog code of the callee may store up to 8 GPR argument registers to
4664   // the stack, allowing va_start to index over them in memory if its varargs.
4665   // Because we cannot tell if this is needed on the caller side, we have to
4666   // conservatively assume that it is needed.  As such, make sure we have at
4667   // least enough stack space for the caller to store the 8 GPRs.
4668   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4669   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4670
4671   // Tail call needs the stack to be aligned.
4672   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4673       CallConv == CallingConv::Fast)
4674     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4675
4676   // Calculate by how many bytes the stack has to be adjusted in case of tail
4677   // call optimization.
4678   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4679
4680   // To protect arguments on the stack from being clobbered in a tail call,
4681   // force all the loads to happen before doing any other lowering.
4682   if (isTailCall)
4683     Chain = DAG.getStackArgumentTokenFactor(Chain);
4684
4685   // Adjust the stack pointer for the new arguments...
4686   // These operations are automatically eliminated by the prolog/epilog pass
4687   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4688                                dl);
4689   SDValue CallSeqStart = Chain;
4690
4691   // Load the return address and frame pointer so it can be move somewhere else
4692   // later.
4693   SDValue LROp, FPOp;
4694   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4695                                        dl);
4696
4697   // Set up a copy of the stack pointer for use loading and storing any
4698   // arguments that may not fit in the registers available for argument
4699   // passing.
4700   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4701
4702   // Figure out which arguments are going to go in registers, and which in
4703   // memory.  Also, if this is a vararg function, floating point operations
4704   // must be stored to our stack, and loaded into integer regs as well, if
4705   // any integer regs are available for argument passing.
4706   unsigned ArgOffset = LinkageSize;
4707
4708   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4709   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4710
4711   SmallVector<SDValue, 8> MemOpChains;
4712   for (unsigned i = 0; i != NumOps; ++i) {
4713     SDValue Arg = OutVals[i];
4714     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4715     EVT ArgVT = Outs[i].VT;
4716     EVT OrigVT = Outs[i].ArgVT;
4717
4718     // PtrOff will be used to store the current argument to the stack if a
4719     // register cannot be found for it.
4720     SDValue PtrOff;
4721
4722     // We re-align the argument offset for each argument, except when using the
4723     // fast calling convention, when we need to make sure we do that only when
4724     // we'll actually use a stack slot.
4725     auto ComputePtrOff = [&]() {
4726       /* Respect alignment of argument on the stack.  */
4727       unsigned Align =
4728         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4729       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4730
4731       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4732
4733       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4734     };
4735
4736     if (CallConv != CallingConv::Fast) {
4737       ComputePtrOff();
4738
4739       /* Compute GPR index associated with argument offset.  */
4740       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4741       GPR_idx = std::min(GPR_idx, NumGPRs);
4742     }
4743
4744     // Promote integers to 64-bit values.
4745     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4746       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4747       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4748       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4749     }
4750
4751     // FIXME memcpy is used way more than necessary.  Correctness first.
4752     // Note: "by value" is code for passing a structure by value, not
4753     // basic types.
4754     if (Flags.isByVal()) {
4755       // Note: Size includes alignment padding, so
4756       //   struct x { short a; char b; }
4757       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4758       // These are the proper values we need for right-justifying the
4759       // aggregate in a parameter register.
4760       unsigned Size = Flags.getByValSize();
4761
4762       // An empty aggregate parameter takes up no storage and no
4763       // registers.
4764       if (Size == 0)
4765         continue;
4766
4767       if (CallConv == CallingConv::Fast)
4768         ComputePtrOff();
4769
4770       // All aggregates smaller than 8 bytes must be passed right-justified.
4771       if (Size==1 || Size==2 || Size==4) {
4772         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4773         if (GPR_idx != NumGPRs) {
4774           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4775                                         MachinePointerInfo(), VT,
4776                                         false, false, false, 0);
4777           MemOpChains.push_back(Load.getValue(1));
4778           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4779
4780           ArgOffset += PtrByteSize;
4781           continue;
4782         }
4783       }
4784
4785       if (GPR_idx == NumGPRs && Size < 8) {
4786         SDValue AddPtr = PtrOff;
4787         if (!isLittleEndian) {
4788           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4789                                           PtrOff.getValueType());
4790           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4791         }
4792         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4793                                                           CallSeqStart,
4794                                                           Flags, DAG, dl);
4795         ArgOffset += PtrByteSize;
4796         continue;
4797       }
4798       // Copy entire object into memory.  There are cases where gcc-generated
4799       // code assumes it is there, even if it could be put entirely into
4800       // registers.  (This is not what the doc says.)
4801
4802       // FIXME: The above statement is likely due to a misunderstanding of the
4803       // documents.  All arguments must be copied into the parameter area BY
4804       // THE CALLEE in the event that the callee takes the address of any
4805       // formal argument.  That has not yet been implemented.  However, it is
4806       // reasonable to use the stack area as a staging area for the register
4807       // load.
4808
4809       // Skip this for small aggregates, as we will use the same slot for a
4810       // right-justified copy, below.
4811       if (Size >= 8)
4812         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4813                                                           CallSeqStart,
4814                                                           Flags, DAG, dl);
4815
4816       // When a register is available, pass a small aggregate right-justified.
4817       if (Size < 8 && GPR_idx != NumGPRs) {
4818         // The easiest way to get this right-justified in a register
4819         // is to copy the structure into the rightmost portion of a
4820         // local variable slot, then load the whole slot into the
4821         // register.
4822         // FIXME: The memcpy seems to produce pretty awful code for
4823         // small aggregates, particularly for packed ones.
4824         // FIXME: It would be preferable to use the slot in the
4825         // parameter save area instead of a new local variable.
4826         SDValue AddPtr = PtrOff;
4827         if (!isLittleEndian) {
4828           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4829           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4830         }
4831         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4832                                                           CallSeqStart,
4833                                                           Flags, DAG, dl);
4834
4835         // Load the slot into the register.
4836         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4837                                    MachinePointerInfo(),
4838                                    false, false, false, 0);
4839         MemOpChains.push_back(Load.getValue(1));
4840         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4841
4842         // Done with this argument.
4843         ArgOffset += PtrByteSize;
4844         continue;
4845       }
4846
4847       // For aggregates larger than PtrByteSize, copy the pieces of the
4848       // object that fit into registers from the parameter save area.
4849       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4850         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4851         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4852         if (GPR_idx != NumGPRs) {
4853           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4854                                      MachinePointerInfo(),
4855                                      false, false, false, 0);
4856           MemOpChains.push_back(Load.getValue(1));
4857           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4858           ArgOffset += PtrByteSize;
4859         } else {
4860           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4861           break;
4862         }
4863       }
4864       continue;
4865     }
4866
4867     switch (Arg.getSimpleValueType().SimpleTy) {
4868     default: llvm_unreachable("Unexpected ValueType for argument!");
4869     case MVT::i1:
4870     case MVT::i32:
4871     case MVT::i64:
4872       // These can be scalar arguments or elements of an integer array type
4873       // passed directly.  Clang may use those instead of "byval" aggregate
4874       // types to avoid forcing arguments to memory unnecessarily.
4875       if (GPR_idx != NumGPRs) {
4876         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4877       } else {
4878         if (CallConv == CallingConv::Fast)
4879           ComputePtrOff();
4880
4881         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4882                          true, isTailCall, false, MemOpChains,
4883                          TailCallArguments, dl);
4884         if (CallConv == CallingConv::Fast)
4885           ArgOffset += PtrByteSize;
4886       }
4887       if (CallConv != CallingConv::Fast)
4888         ArgOffset += PtrByteSize;
4889       break;
4890     case MVT::f32:
4891     case MVT::f64: {
4892       // These can be scalar arguments or elements of a float array type
4893       // passed directly.  The latter are used to implement ELFv2 homogenous
4894       // float aggregates.
4895
4896       // Named arguments go into FPRs first, and once they overflow, the
4897       // remaining arguments go into GPRs and then the parameter save area.
4898       // Unnamed arguments for vararg functions always go to GPRs and
4899       // then the parameter save area.  For now, put all arguments to vararg
4900       // routines always in both locations (FPR *and* GPR or stack slot).
4901       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4902       bool NeededLoad = false;
4903
4904       // First load the argument into the next available FPR.
4905       if (FPR_idx != NumFPRs)
4906         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4907
4908       // Next, load the argument into GPR or stack slot if needed.
4909       if (!NeedGPROrStack)
4910         ;
4911       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4912         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4913         // once we support fp <-> gpr moves.
4914
4915         // In the non-vararg case, this can only ever happen in the
4916         // presence of f32 array types, since otherwise we never run
4917         // out of FPRs before running out of GPRs.
4918         SDValue ArgVal;
4919
4920         // Double values are always passed in a single GPR.
4921         if (Arg.getValueType() != MVT::f32) {
4922           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4923
4924         // Non-array float values are extended and passed in a GPR.
4925         } else if (!Flags.isInConsecutiveRegs()) {
4926           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4927           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4928
4929         // If we have an array of floats, we collect every odd element
4930         // together with its predecessor into one GPR.
4931         } else if (ArgOffset % PtrByteSize != 0) {
4932           SDValue Lo, Hi;
4933           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4934           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4935           if (!isLittleEndian)
4936             std::swap(Lo, Hi);
4937           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4938
4939         // The final element, if even, goes into the first half of a GPR.
4940         } else if (Flags.isInConsecutiveRegsLast()) {
4941           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4942           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4943           if (!isLittleEndian)
4944             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4945                                  DAG.getConstant(32, MVT::i32));
4946
4947         // Non-final even elements are skipped; they will be handled
4948         // together the with subsequent argument on the next go-around.
4949         } else
4950           ArgVal = SDValue();
4951
4952         if (ArgVal.getNode())
4953           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4954       } else {
4955         if (CallConv == CallingConv::Fast)
4956           ComputePtrOff();
4957
4958         // Single-precision floating-point values are mapped to the
4959         // second (rightmost) word of the stack doubleword.
4960         if (Arg.getValueType() == MVT::f32 &&
4961             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4962           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4963           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4964         }
4965
4966         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4967                          true, isTailCall, false, MemOpChains,
4968                          TailCallArguments, dl);
4969
4970         NeededLoad = true;
4971       }
4972       // When passing an array of floats, the array occupies consecutive
4973       // space in the argument area; only round up to the next doubleword
4974       // at the end of the array.  Otherwise, each float takes 8 bytes.
4975       if (CallConv != CallingConv::Fast || NeededLoad) {
4976         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4977                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4978         if (Flags.isInConsecutiveRegsLast())
4979           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4980       }
4981       break;
4982     }
4983     case MVT::v4f32:
4984     case MVT::v4i32:
4985     case MVT::v8i16:
4986     case MVT::v16i8:
4987     case MVT::v2f64:
4988     case MVT::v2i64:
4989       if (!Subtarget.hasQPX()) {
4990       // These can be scalar arguments or elements of a vector array type
4991       // passed directly.  The latter are used to implement ELFv2 homogenous
4992       // vector aggregates.
4993
4994       // For a varargs call, named arguments go into VRs or on the stack as
4995       // usual; unnamed arguments always go to the stack or the corresponding
4996       // GPRs when within range.  For now, we always put the value in both
4997       // locations (or even all three).
4998       if (isVarArg) {
4999         // We could elide this store in the case where the object fits
5000         // entirely in R registers.  Maybe later.
5001         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5002                                      MachinePointerInfo(), false, false, 0);
5003         MemOpChains.push_back(Store);
5004         if (VR_idx != NumVRs) {
5005           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5006                                      MachinePointerInfo(),
5007                                      false, false, false, 0);
5008           MemOpChains.push_back(Load.getValue(1));
5009
5010           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5011                            Arg.getSimpleValueType() == MVT::v2i64) ?
5012                           VSRH[VR_idx] : VR[VR_idx];
5013           ++VR_idx;
5014
5015           RegsToPass.push_back(std::make_pair(VReg, Load));
5016         }
5017         ArgOffset += 16;
5018         for (unsigned i=0; i<16; i+=PtrByteSize) {
5019           if (GPR_idx == NumGPRs)
5020             break;
5021           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5022                                   DAG.getConstant(i, PtrVT));
5023           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5024                                      false, false, false, 0);
5025           MemOpChains.push_back(Load.getValue(1));
5026           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5027         }
5028         break;
5029       }
5030
5031       // Non-varargs Altivec params go into VRs or on the stack.
5032       if (VR_idx != NumVRs) {
5033         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5034                          Arg.getSimpleValueType() == MVT::v2i64) ?
5035                         VSRH[VR_idx] : VR[VR_idx];
5036         ++VR_idx;
5037
5038         RegsToPass.push_back(std::make_pair(VReg, Arg));
5039       } else {
5040         if (CallConv == CallingConv::Fast)
5041           ComputePtrOff();
5042
5043         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5044                          true, isTailCall, true, MemOpChains,
5045                          TailCallArguments, dl);
5046         if (CallConv == CallingConv::Fast)
5047           ArgOffset += 16;
5048       }
5049
5050       if (CallConv != CallingConv::Fast)
5051         ArgOffset += 16;
5052       break;
5053       } // not QPX
5054
5055       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5056              "Invalid QPX parameter type");
5057
5058       /* fall through */
5059     case MVT::v4f64:
5060     case MVT::v4i1: {
5061       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5062       if (isVarArg) {
5063         // We could elide this store in the case where the object fits
5064         // entirely in R registers.  Maybe later.
5065         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5066                                      MachinePointerInfo(), false, false, 0);
5067         MemOpChains.push_back(Store);
5068         if (QFPR_idx != NumQFPRs) {
5069           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5070                                      Store, PtrOff, MachinePointerInfo(),
5071                                      false, false, false, 0);
5072           MemOpChains.push_back(Load.getValue(1));
5073           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5074         }
5075         ArgOffset += (IsF32 ? 16 : 32);
5076         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5077           if (GPR_idx == NumGPRs)
5078             break;
5079           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5080                                   DAG.getConstant(i, PtrVT));
5081           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5082                                      false, false, false, 0);
5083           MemOpChains.push_back(Load.getValue(1));
5084           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5085         }
5086         break;
5087       }
5088
5089       // Non-varargs QPX params go into registers or on the stack.
5090       if (QFPR_idx != NumQFPRs) {
5091         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5092       } else {
5093         if (CallConv == CallingConv::Fast)
5094           ComputePtrOff();
5095
5096         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5097                          true, isTailCall, true, MemOpChains,
5098                          TailCallArguments, dl);
5099         if (CallConv == CallingConv::Fast)
5100           ArgOffset += (IsF32 ? 16 : 32);
5101       }
5102
5103       if (CallConv != CallingConv::Fast)
5104         ArgOffset += (IsF32 ? 16 : 32);
5105       break;
5106       }
5107     }
5108   }
5109
5110   assert(NumBytesActuallyUsed == ArgOffset);
5111   (void)NumBytesActuallyUsed;
5112
5113   if (!MemOpChains.empty())
5114     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5115
5116   // Check if this is an indirect call (MTCTR/BCTRL).
5117   // See PrepareCall() for more information about calls through function
5118   // pointers in the 64-bit SVR4 ABI.
5119   if (!isTailCall && !IsPatchPoint &&
5120       !isFunctionGlobalAddress(Callee) &&
5121       !isa<ExternalSymbolSDNode>(Callee)) {
5122     // Load r2 into a virtual register and store it to the TOC save area.
5123     setUsesTOCBasePtr(DAG);
5124     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5125     // TOC save area offset.
5126     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5127     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5128     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5129     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5130                          MachinePointerInfo::getStack(TOCSaveOffset),
5131                          false, false, 0);
5132     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5133     // This does not mean the MTCTR instruction must use R12; it's easier
5134     // to model this as an extra parameter, so do that.
5135     if (isELFv2ABI && !IsPatchPoint)
5136       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5137   }
5138
5139   // Build a sequence of copy-to-reg nodes chained together with token chain
5140   // and flag operands which copy the outgoing args into the appropriate regs.
5141   SDValue InFlag;
5142   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5143     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5144                              RegsToPass[i].second, InFlag);
5145     InFlag = Chain.getValue(1);
5146   }
5147
5148   if (isTailCall)
5149     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5150                     FPOp, true, TailCallArguments);
5151
5152   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5153                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5154                     NumBytes, Ins, InVals, CS);
5155 }
5156
5157 SDValue
5158 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5159                                     CallingConv::ID CallConv, bool isVarArg,
5160                                     bool isTailCall, bool IsPatchPoint,
5161                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5162                                     const SmallVectorImpl<SDValue> &OutVals,
5163                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5164                                     SDLoc dl, SelectionDAG &DAG,
5165                                     SmallVectorImpl<SDValue> &InVals,
5166                                     ImmutableCallSite *CS) const {
5167
5168   unsigned NumOps = Outs.size();
5169
5170   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5171   bool isPPC64 = PtrVT == MVT::i64;
5172   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5173
5174   MachineFunction &MF = DAG.getMachineFunction();
5175
5176   // Mark this function as potentially containing a function that contains a
5177   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5178   // and restoring the callers stack pointer in this functions epilog. This is
5179   // done because by tail calling the called function might overwrite the value
5180   // in this function's (MF) stack pointer stack slot 0(SP).
5181   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5182       CallConv == CallingConv::Fast)
5183     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5184
5185   // Count how many bytes are to be pushed on the stack, including the linkage
5186   // area, and parameter passing area.  We start with 24/48 bytes, which is
5187   // prereserved space for [SP][CR][LR][3 x unused].
5188   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5189   unsigned NumBytes = LinkageSize;
5190
5191   // Add up all the space actually used.
5192   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5193   // they all go in registers, but we must reserve stack space for them for
5194   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5195   // assigned stack space in order, with padding so Altivec parameters are
5196   // 16-byte aligned.
5197   unsigned nAltivecParamsAtEnd = 0;
5198   for (unsigned i = 0; i != NumOps; ++i) {
5199     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5200     EVT ArgVT = Outs[i].VT;
5201     // Varargs Altivec parameters are padded to a 16 byte boundary.
5202     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5203         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5204         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5205       if (!isVarArg && !isPPC64) {
5206         // Non-varargs Altivec parameters go after all the non-Altivec
5207         // parameters; handle those later so we know how much padding we need.
5208         nAltivecParamsAtEnd++;
5209         continue;
5210       }
5211       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5212       NumBytes = ((NumBytes+15)/16)*16;
5213     }
5214     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5215   }
5216
5217   // Allow for Altivec parameters at the end, if needed.
5218   if (nAltivecParamsAtEnd) {
5219     NumBytes = ((NumBytes+15)/16)*16;
5220     NumBytes += 16*nAltivecParamsAtEnd;
5221   }
5222
5223   // The prolog code of the callee may store up to 8 GPR argument registers to
5224   // the stack, allowing va_start to index over them in memory if its varargs.
5225   // Because we cannot tell if this is needed on the caller side, we have to
5226   // conservatively assume that it is needed.  As such, make sure we have at
5227   // least enough stack space for the caller to store the 8 GPRs.
5228   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5229
5230   // Tail call needs the stack to be aligned.
5231   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5232       CallConv == CallingConv::Fast)
5233     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5234
5235   // Calculate by how many bytes the stack has to be adjusted in case of tail
5236   // call optimization.
5237   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5238
5239   // To protect arguments on the stack from being clobbered in a tail call,
5240   // force all the loads to happen before doing any other lowering.
5241   if (isTailCall)
5242     Chain = DAG.getStackArgumentTokenFactor(Chain);
5243
5244   // Adjust the stack pointer for the new arguments...
5245   // These operations are automatically eliminated by the prolog/epilog pass
5246   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5247                                dl);
5248   SDValue CallSeqStart = Chain;
5249
5250   // Load the return address and frame pointer so it can be move somewhere else
5251   // later.
5252   SDValue LROp, FPOp;
5253   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5254                                        dl);
5255
5256   // Set up a copy of the stack pointer for use loading and storing any
5257   // arguments that may not fit in the registers available for argument
5258   // passing.
5259   SDValue StackPtr;
5260   if (isPPC64)
5261     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5262   else
5263     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5264
5265   // Figure out which arguments are going to go in registers, and which in
5266   // memory.  Also, if this is a vararg function, floating point operations
5267   // must be stored to our stack, and loaded into integer regs as well, if
5268   // any integer regs are available for argument passing.
5269   unsigned ArgOffset = LinkageSize;
5270   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5271
5272   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5273     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5274     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5275   };
5276   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5277     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5278     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5279   };
5280   static const MCPhysReg VR[] = {
5281     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5282     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5283   };
5284   const unsigned NumGPRs = array_lengthof(GPR_32);
5285   const unsigned NumFPRs = 13;
5286   const unsigned NumVRs  = array_lengthof(VR);
5287
5288   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5289
5290   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5291   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5292
5293   SmallVector<SDValue, 8> MemOpChains;
5294   for (unsigned i = 0; i != NumOps; ++i) {
5295     SDValue Arg = OutVals[i];
5296     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5297
5298     // PtrOff will be used to store the current argument to the stack if a
5299     // register cannot be found for it.
5300     SDValue PtrOff;
5301
5302     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5303
5304     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5305
5306     // On PPC64, promote integers to 64-bit values.
5307     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5308       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5309       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5310       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5311     }
5312
5313     // FIXME memcpy is used way more than necessary.  Correctness first.
5314     // Note: "by value" is code for passing a structure by value, not
5315     // basic types.
5316     if (Flags.isByVal()) {
5317       unsigned Size = Flags.getByValSize();
5318       // Very small objects are passed right-justified.  Everything else is
5319       // passed left-justified.
5320       if (Size==1 || Size==2) {
5321         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5322         if (GPR_idx != NumGPRs) {
5323           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5324                                         MachinePointerInfo(), VT,
5325                                         false, false, false, 0);
5326           MemOpChains.push_back(Load.getValue(1));
5327           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5328
5329           ArgOffset += PtrByteSize;
5330         } else {
5331           SDValue Const = DAG.getConstant(PtrByteSize - Size,
5332                                           PtrOff.getValueType());
5333           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5334           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5335                                                             CallSeqStart,
5336                                                             Flags, DAG, dl);
5337           ArgOffset += PtrByteSize;
5338         }
5339         continue;
5340       }
5341       // Copy entire object into memory.  There are cases where gcc-generated
5342       // code assumes it is there, even if it could be put entirely into
5343       // registers.  (This is not what the doc says.)
5344       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5345                                                         CallSeqStart,
5346                                                         Flags, DAG, dl);
5347
5348       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5349       // copy the pieces of the object that fit into registers from the
5350       // parameter save area.
5351       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5352         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5353         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5354         if (GPR_idx != NumGPRs) {
5355           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5356                                      MachinePointerInfo(),
5357                                      false, false, false, 0);
5358           MemOpChains.push_back(Load.getValue(1));
5359           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5360           ArgOffset += PtrByteSize;
5361         } else {
5362           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5363           break;
5364         }
5365       }
5366       continue;
5367     }
5368
5369     switch (Arg.getSimpleValueType().SimpleTy) {
5370     default: llvm_unreachable("Unexpected ValueType for argument!");
5371     case MVT::i1:
5372     case MVT::i32:
5373     case MVT::i64:
5374       if (GPR_idx != NumGPRs) {
5375         if (Arg.getValueType() == MVT::i1)
5376           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5377
5378         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5379       } else {
5380         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5381                          isPPC64, isTailCall, false, MemOpChains,
5382                          TailCallArguments, dl);
5383       }
5384       ArgOffset += PtrByteSize;
5385       break;
5386     case MVT::f32:
5387     case MVT::f64:
5388       if (FPR_idx != NumFPRs) {
5389         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5390
5391         if (isVarArg) {
5392           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5393                                        MachinePointerInfo(), false, false, 0);
5394           MemOpChains.push_back(Store);
5395
5396           // Float varargs are always shadowed in available integer registers
5397           if (GPR_idx != NumGPRs) {
5398             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5399                                        MachinePointerInfo(), false, false,
5400                                        false, 0);
5401             MemOpChains.push_back(Load.getValue(1));
5402             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5403           }
5404           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5405             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5406             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5407             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5408                                        MachinePointerInfo(),
5409                                        false, false, false, 0);
5410             MemOpChains.push_back(Load.getValue(1));
5411             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5412           }
5413         } else {
5414           // If we have any FPRs remaining, we may also have GPRs remaining.
5415           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5416           // GPRs.
5417           if (GPR_idx != NumGPRs)
5418             ++GPR_idx;
5419           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5420               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5421             ++GPR_idx;
5422         }
5423       } else
5424         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5425                          isPPC64, isTailCall, false, MemOpChains,
5426                          TailCallArguments, dl);
5427       if (isPPC64)
5428         ArgOffset += 8;
5429       else
5430         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5431       break;
5432     case MVT::v4f32:
5433     case MVT::v4i32:
5434     case MVT::v8i16:
5435     case MVT::v16i8:
5436       if (isVarArg) {
5437         // These go aligned on the stack, or in the corresponding R registers
5438         // when within range.  The Darwin PPC ABI doc claims they also go in
5439         // V registers; in fact gcc does this only for arguments that are
5440         // prototyped, not for those that match the ...  We do it for all
5441         // arguments, seems to work.
5442         while (ArgOffset % 16 !=0) {
5443           ArgOffset += PtrByteSize;
5444           if (GPR_idx != NumGPRs)
5445             GPR_idx++;
5446         }
5447         // We could elide this store in the case where the object fits
5448         // entirely in R registers.  Maybe later.
5449         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5450                             DAG.getConstant(ArgOffset, PtrVT));
5451         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5452                                      MachinePointerInfo(), false, false, 0);
5453         MemOpChains.push_back(Store);
5454         if (VR_idx != NumVRs) {
5455           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5456                                      MachinePointerInfo(),
5457                                      false, false, false, 0);
5458           MemOpChains.push_back(Load.getValue(1));
5459           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5460         }
5461         ArgOffset += 16;
5462         for (unsigned i=0; i<16; i+=PtrByteSize) {
5463           if (GPR_idx == NumGPRs)
5464             break;
5465           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5466                                   DAG.getConstant(i, PtrVT));
5467           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5468                                      false, false, false, 0);
5469           MemOpChains.push_back(Load.getValue(1));
5470           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5471         }
5472         break;
5473       }
5474
5475       // Non-varargs Altivec params generally go in registers, but have
5476       // stack space allocated at the end.
5477       if (VR_idx != NumVRs) {
5478         // Doesn't have GPR space allocated.
5479         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5480       } else if (nAltivecParamsAtEnd==0) {
5481         // We are emitting Altivec params in order.
5482         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5483                          isPPC64, isTailCall, true, MemOpChains,
5484                          TailCallArguments, dl);
5485         ArgOffset += 16;
5486       }
5487       break;
5488     }
5489   }
5490   // If all Altivec parameters fit in registers, as they usually do,
5491   // they get stack space following the non-Altivec parameters.  We
5492   // don't track this here because nobody below needs it.
5493   // If there are more Altivec parameters than fit in registers emit
5494   // the stores here.
5495   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5496     unsigned j = 0;
5497     // Offset is aligned; skip 1st 12 params which go in V registers.
5498     ArgOffset = ((ArgOffset+15)/16)*16;
5499     ArgOffset += 12*16;
5500     for (unsigned i = 0; i != NumOps; ++i) {
5501       SDValue Arg = OutVals[i];
5502       EVT ArgType = Outs[i].VT;
5503       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5504           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5505         if (++j > NumVRs) {
5506           SDValue PtrOff;
5507           // We are emitting Altivec params in order.
5508           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5509                            isPPC64, isTailCall, true, MemOpChains,
5510                            TailCallArguments, dl);
5511           ArgOffset += 16;
5512         }
5513       }
5514     }
5515   }
5516
5517   if (!MemOpChains.empty())
5518     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5519
5520   // On Darwin, R12 must contain the address of an indirect callee.  This does
5521   // not mean the MTCTR instruction must use R12; it's easier to model this as
5522   // an extra parameter, so do that.
5523   if (!isTailCall &&
5524       !isFunctionGlobalAddress(Callee) &&
5525       !isa<ExternalSymbolSDNode>(Callee) &&
5526       !isBLACompatibleAddress(Callee, DAG))
5527     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5528                                                    PPC::R12), Callee));
5529
5530   // Build a sequence of copy-to-reg nodes chained together with token chain
5531   // and flag operands which copy the outgoing args into the appropriate regs.
5532   SDValue InFlag;
5533   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5534     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5535                              RegsToPass[i].second, InFlag);
5536     InFlag = Chain.getValue(1);
5537   }
5538
5539   if (isTailCall)
5540     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5541                     FPOp, true, TailCallArguments);
5542
5543   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5544                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5545                     NumBytes, Ins, InVals, CS);
5546 }
5547
5548 bool
5549 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5550                                   MachineFunction &MF, bool isVarArg,
5551                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5552                                   LLVMContext &Context) const {
5553   SmallVector<CCValAssign, 16> RVLocs;
5554   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5555   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5556 }
5557
5558 SDValue
5559 PPCTargetLowering::LowerReturn(SDValue Chain,
5560                                CallingConv::ID CallConv, bool isVarArg,
5561                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5562                                const SmallVectorImpl<SDValue> &OutVals,
5563                                SDLoc dl, SelectionDAG &DAG) const {
5564
5565   SmallVector<CCValAssign, 16> RVLocs;
5566   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5567                  *DAG.getContext());
5568   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5569
5570   SDValue Flag;
5571   SmallVector<SDValue, 4> RetOps(1, Chain);
5572
5573   // Copy the result values into the output registers.
5574   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5575     CCValAssign &VA = RVLocs[i];
5576     assert(VA.isRegLoc() && "Can only return in registers!");
5577
5578     SDValue Arg = OutVals[i];
5579
5580     switch (VA.getLocInfo()) {
5581     default: llvm_unreachable("Unknown loc info!");
5582     case CCValAssign::Full: break;
5583     case CCValAssign::AExt:
5584       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5585       break;
5586     case CCValAssign::ZExt:
5587       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5588       break;
5589     case CCValAssign::SExt:
5590       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5591       break;
5592     }
5593
5594     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5595     Flag = Chain.getValue(1);
5596     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5597   }
5598
5599   RetOps[0] = Chain;  // Update chain.
5600
5601   // Add the flag if we have it.
5602   if (Flag.getNode())
5603     RetOps.push_back(Flag);
5604
5605   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5606 }
5607
5608 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5609                                    const PPCSubtarget &Subtarget) const {
5610   // When we pop the dynamic allocation we need to restore the SP link.
5611   SDLoc dl(Op);
5612
5613   // Get the corect type for pointers.
5614   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5615
5616   // Construct the stack pointer operand.
5617   bool isPPC64 = Subtarget.isPPC64();
5618   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5619   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5620
5621   // Get the operands for the STACKRESTORE.
5622   SDValue Chain = Op.getOperand(0);
5623   SDValue SaveSP = Op.getOperand(1);
5624
5625   // Load the old link SP.
5626   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5627                                    MachinePointerInfo(),
5628                                    false, false, false, 0);
5629
5630   // Restore the stack pointer.
5631   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5632
5633   // Store the old link SP.
5634   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5635                       false, false, 0);
5636 }
5637
5638
5639
5640 SDValue
5641 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5642   MachineFunction &MF = DAG.getMachineFunction();
5643   bool isPPC64 = Subtarget.isPPC64();
5644   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5645
5646   // Get current frame pointer save index.  The users of this index will be
5647   // primarily DYNALLOC instructions.
5648   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5649   int RASI = FI->getReturnAddrSaveIndex();
5650
5651   // If the frame pointer save index hasn't been defined yet.
5652   if (!RASI) {
5653     // Find out what the fix offset of the frame pointer save area.
5654     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5655     // Allocate the frame index for frame pointer save area.
5656     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5657     // Save the result.
5658     FI->setReturnAddrSaveIndex(RASI);
5659   }
5660   return DAG.getFrameIndex(RASI, PtrVT);
5661 }
5662
5663 SDValue
5664 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5665   MachineFunction &MF = DAG.getMachineFunction();
5666   bool isPPC64 = Subtarget.isPPC64();
5667   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5668
5669   // Get current frame pointer save index.  The users of this index will be
5670   // primarily DYNALLOC instructions.
5671   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5672   int FPSI = FI->getFramePointerSaveIndex();
5673
5674   // If the frame pointer save index hasn't been defined yet.
5675   if (!FPSI) {
5676     // Find out what the fix offset of the frame pointer save area.
5677     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5678     // Allocate the frame index for frame pointer save area.
5679     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5680     // Save the result.
5681     FI->setFramePointerSaveIndex(FPSI);
5682   }
5683   return DAG.getFrameIndex(FPSI, PtrVT);
5684 }
5685
5686 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5687                                          SelectionDAG &DAG,
5688                                          const PPCSubtarget &Subtarget) const {
5689   // Get the inputs.
5690   SDValue Chain = Op.getOperand(0);
5691   SDValue Size  = Op.getOperand(1);
5692   SDLoc dl(Op);
5693
5694   // Get the corect type for pointers.
5695   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5696   // Negate the size.
5697   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5698                                   DAG.getConstant(0, PtrVT), Size);
5699   // Construct a node for the frame pointer save index.
5700   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5701   // Build a DYNALLOC node.
5702   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5703   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5704   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5705 }
5706
5707 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5708                                                SelectionDAG &DAG) const {
5709   SDLoc DL(Op);
5710   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5711                      DAG.getVTList(MVT::i32, MVT::Other),
5712                      Op.getOperand(0), Op.getOperand(1));
5713 }
5714
5715 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5716                                                 SelectionDAG &DAG) const {
5717   SDLoc DL(Op);
5718   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5719                      Op.getOperand(0), Op.getOperand(1));
5720 }
5721
5722 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5723   if (Op.getValueType().isVector())
5724     return LowerVectorLoad(Op, DAG);
5725
5726   assert(Op.getValueType() == MVT::i1 &&
5727          "Custom lowering only for i1 loads");
5728
5729   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5730
5731   SDLoc dl(Op);
5732   LoadSDNode *LD = cast<LoadSDNode>(Op);
5733
5734   SDValue Chain = LD->getChain();
5735   SDValue BasePtr = LD->getBasePtr();
5736   MachineMemOperand *MMO = LD->getMemOperand();
5737
5738   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5739                                  BasePtr, MVT::i8, MMO);
5740   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5741
5742   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5743   return DAG.getMergeValues(Ops, dl);
5744 }
5745
5746 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5747   if (Op.getOperand(1).getValueType().isVector())
5748     return LowerVectorStore(Op, DAG);
5749
5750   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5751          "Custom lowering only for i1 stores");
5752
5753   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5754
5755   SDLoc dl(Op);
5756   StoreSDNode *ST = cast<StoreSDNode>(Op);
5757
5758   SDValue Chain = ST->getChain();
5759   SDValue BasePtr = ST->getBasePtr();
5760   SDValue Value = ST->getValue();
5761   MachineMemOperand *MMO = ST->getMemOperand();
5762
5763   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5764   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5765 }
5766
5767 // FIXME: Remove this once the ANDI glue bug is fixed:
5768 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5769   assert(Op.getValueType() == MVT::i1 &&
5770          "Custom lowering only for i1 results");
5771
5772   SDLoc DL(Op);
5773   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5774                      Op.getOperand(0));
5775 }
5776
5777 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5778 /// possible.
5779 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5780   // Not FP? Not a fsel.
5781   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5782       !Op.getOperand(2).getValueType().isFloatingPoint())
5783     return Op;
5784
5785   // We might be able to do better than this under some circumstances, but in
5786   // general, fsel-based lowering of select is a finite-math-only optimization.
5787   // For more information, see section F.3 of the 2.06 ISA specification.
5788   if (!DAG.getTarget().Options.NoInfsFPMath ||
5789       !DAG.getTarget().Options.NoNaNsFPMath)
5790     return Op;
5791
5792   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5793
5794   EVT ResVT = Op.getValueType();
5795   EVT CmpVT = Op.getOperand(0).getValueType();
5796   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5797   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5798   SDLoc dl(Op);
5799
5800   // If the RHS of the comparison is a 0.0, we don't need to do the
5801   // subtraction at all.
5802   SDValue Sel1;
5803   if (isFloatingPointZero(RHS))
5804     switch (CC) {
5805     default: break;       // SETUO etc aren't handled by fsel.
5806     case ISD::SETNE:
5807       std::swap(TV, FV);
5808     case ISD::SETEQ:
5809       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5810         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5811       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5812       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5813         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5814       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5815                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5816     case ISD::SETULT:
5817     case ISD::SETLT:
5818       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5819     case ISD::SETOGE:
5820     case ISD::SETGE:
5821       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5822         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5823       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5824     case ISD::SETUGT:
5825     case ISD::SETGT:
5826       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5827     case ISD::SETOLE:
5828     case ISD::SETLE:
5829       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5830         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5831       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5832                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5833     }
5834
5835   SDValue Cmp;
5836   switch (CC) {
5837   default: break;       // SETUO etc aren't handled by fsel.
5838   case ISD::SETNE:
5839     std::swap(TV, FV);
5840   case ISD::SETEQ:
5841     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5842     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5843       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5844     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5845     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5846       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5847     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5848                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5849   case ISD::SETULT:
5850   case ISD::SETLT:
5851     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5852     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5853       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5854     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5855   case ISD::SETOGE:
5856   case ISD::SETGE:
5857     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5858     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5859       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5860     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5861   case ISD::SETUGT:
5862   case ISD::SETGT:
5863     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5864     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5865       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5866     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5867   case ISD::SETOLE:
5868   case ISD::SETLE:
5869     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5870     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5871       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5872     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5873   }
5874   return Op;
5875 }
5876
5877 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5878                                                SelectionDAG &DAG,
5879                                                SDLoc dl) const {
5880   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5881   SDValue Src = Op.getOperand(0);
5882   if (Src.getValueType() == MVT::f32)
5883     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5884
5885   SDValue Tmp;
5886   switch (Op.getSimpleValueType().SimpleTy) {
5887   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5888   case MVT::i32:
5889     Tmp = DAG.getNode(
5890         Op.getOpcode() == ISD::FP_TO_SINT
5891             ? PPCISD::FCTIWZ
5892             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5893         dl, MVT::f64, Src);
5894     break;
5895   case MVT::i64:
5896     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5897            "i64 FP_TO_UINT is supported only with FPCVT");
5898     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5899                                                         PPCISD::FCTIDUZ,
5900                       dl, MVT::f64, Src);
5901     break;
5902   }
5903
5904   // Convert the FP value to an int value through memory.
5905   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5906     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5907   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5908   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5909   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5910
5911   // Emit a store to the stack slot.
5912   SDValue Chain;
5913   if (i32Stack) {
5914     MachineFunction &MF = DAG.getMachineFunction();
5915     MachineMemOperand *MMO =
5916       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5917     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5918     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5919               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5920   } else
5921     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5922                          MPI, false, false, 0);
5923
5924   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5925   // add in a bias.
5926   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5927     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5928                         DAG.getConstant(4, FIPtr.getValueType()));
5929     MPI = MPI.getWithOffset(4);
5930   }
5931
5932   RLI.Chain = Chain;
5933   RLI.Ptr = FIPtr;
5934   RLI.MPI = MPI;
5935 }
5936
5937 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5938                                           SDLoc dl) const {
5939   ReuseLoadInfo RLI;
5940   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5941
5942   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5943                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5944                      RLI.Ranges);
5945 }
5946
5947 // We're trying to insert a regular store, S, and then a load, L. If the
5948 // incoming value, O, is a load, we might just be able to have our load use the
5949 // address used by O. However, we don't know if anything else will store to
5950 // that address before we can load from it. To prevent this situation, we need
5951 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5952 // the same chain operand as O, we create a token factor from the chain results
5953 // of O and L, and we replace all uses of O's chain result with that token
5954 // factor (see spliceIntoChain below for this last part).
5955 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5956                                             ReuseLoadInfo &RLI,
5957                                             SelectionDAG &DAG,
5958                                             ISD::LoadExtType ET) const {
5959   SDLoc dl(Op);
5960   if (ET == ISD::NON_EXTLOAD &&
5961       (Op.getOpcode() == ISD::FP_TO_UINT ||
5962        Op.getOpcode() == ISD::FP_TO_SINT) &&
5963       isOperationLegalOrCustom(Op.getOpcode(),
5964                                Op.getOperand(0).getValueType())) {
5965
5966     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5967     return true;
5968   }
5969
5970   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5971   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5972       LD->isNonTemporal())
5973     return false;
5974   if (LD->getMemoryVT() != MemVT)
5975     return false;
5976
5977   RLI.Ptr = LD->getBasePtr();
5978   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5979     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5980            "Non-pre-inc AM on PPC?");
5981     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5982                           LD->getOffset());
5983   }
5984
5985   RLI.Chain = LD->getChain();
5986   RLI.MPI = LD->getPointerInfo();
5987   RLI.IsInvariant = LD->isInvariant();
5988   RLI.Alignment = LD->getAlignment();
5989   RLI.AAInfo = LD->getAAInfo();
5990   RLI.Ranges = LD->getRanges();
5991
5992   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5993   return true;
5994 }
5995
5996 // Given the head of the old chain, ResChain, insert a token factor containing
5997 // it and NewResChain, and make users of ResChain now be users of that token
5998 // factor.
5999 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6000                                         SDValue NewResChain,
6001                                         SelectionDAG &DAG) const {
6002   if (!ResChain)
6003     return;
6004
6005   SDLoc dl(NewResChain);
6006
6007   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6008                            NewResChain, DAG.getUNDEF(MVT::Other));
6009   assert(TF.getNode() != NewResChain.getNode() &&
6010          "A new TF really is required here");
6011
6012   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6013   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6014 }
6015
6016 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6017                                           SelectionDAG &DAG) const {
6018   SDLoc dl(Op);
6019
6020   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6021     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6022       return SDValue();
6023
6024     SDValue Value = Op.getOperand(0);
6025     // The values are now known to be -1 (false) or 1 (true). To convert this
6026     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6027     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6028     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6029   
6030     SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6031     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6032                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6033   
6034     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6035
6036     if (Op.getValueType() != MVT::v4f64)
6037       Value = DAG.getNode(ISD::FP_ROUND, dl,
6038                           Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6039     return Value;
6040   }
6041
6042   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6043   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6044     return SDValue();
6045
6046   if (Op.getOperand(0).getValueType() == MVT::i1)
6047     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6048                        DAG.getConstantFP(1.0, Op.getValueType()),
6049                        DAG.getConstantFP(0.0, Op.getValueType()));
6050
6051   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6052          "UINT_TO_FP is supported only with FPCVT");
6053
6054   // If we have FCFIDS, then use it when converting to single-precision.
6055   // Otherwise, convert to double-precision and then round.
6056   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6057                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6058                                                             : PPCISD::FCFIDS)
6059                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6060                                                             : PPCISD::FCFID);
6061   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6062                   ? MVT::f32
6063                   : MVT::f64;
6064
6065   if (Op.getOperand(0).getValueType() == MVT::i64) {
6066     SDValue SINT = Op.getOperand(0);
6067     // When converting to single-precision, we actually need to convert
6068     // to double-precision first and then round to single-precision.
6069     // To avoid double-rounding effects during that operation, we have
6070     // to prepare the input operand.  Bits that might be truncated when
6071     // converting to double-precision are replaced by a bit that won't
6072     // be lost at this stage, but is below the single-precision rounding
6073     // position.
6074     //
6075     // However, if -enable-unsafe-fp-math is in effect, accept double
6076     // rounding to avoid the extra overhead.
6077     if (Op.getValueType() == MVT::f32 &&
6078         !Subtarget.hasFPCVT() &&
6079         !DAG.getTarget().Options.UnsafeFPMath) {
6080
6081       // Twiddle input to make sure the low 11 bits are zero.  (If this
6082       // is the case, we are guaranteed the value will fit into the 53 bit
6083       // mantissa of an IEEE double-precision value without rounding.)
6084       // If any of those low 11 bits were not zero originally, make sure
6085       // bit 12 (value 2048) is set instead, so that the final rounding
6086       // to single-precision gets the correct result.
6087       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6088                                   SINT, DAG.getConstant(2047, MVT::i64));
6089       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6090                           Round, DAG.getConstant(2047, MVT::i64));
6091       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6092       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6093                           Round, DAG.getConstant(-2048, MVT::i64));
6094
6095       // However, we cannot use that value unconditionally: if the magnitude
6096       // of the input value is small, the bit-twiddling we did above might
6097       // end up visibly changing the output.  Fortunately, in that case, we
6098       // don't need to twiddle bits since the original input will convert
6099       // exactly to double-precision floating-point already.  Therefore,
6100       // construct a conditional to use the original value if the top 11
6101       // bits are all sign-bit copies, and use the rounded value computed
6102       // above otherwise.
6103       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6104                                  SINT, DAG.getConstant(53, MVT::i32));
6105       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6106                          Cond, DAG.getConstant(1, MVT::i64));
6107       Cond = DAG.getSetCC(dl, MVT::i32,
6108                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6109
6110       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6111     }
6112
6113     ReuseLoadInfo RLI;
6114     SDValue Bits;
6115
6116     MachineFunction &MF = DAG.getMachineFunction();
6117     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6118       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6119                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6120                          RLI.Ranges);
6121       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6122     } else if (Subtarget.hasLFIWAX() &&
6123                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6124       MachineMemOperand *MMO =
6125         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6126                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6127       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6128       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6129                                      DAG.getVTList(MVT::f64, MVT::Other),
6130                                      Ops, MVT::i32, MMO);
6131       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6132     } else if (Subtarget.hasFPCVT() &&
6133                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6134       MachineMemOperand *MMO =
6135         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6136                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6137       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6138       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6139                                      DAG.getVTList(MVT::f64, MVT::Other),
6140                                      Ops, MVT::i32, MMO);
6141       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6142     } else if (((Subtarget.hasLFIWAX() &&
6143                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6144                 (Subtarget.hasFPCVT() &&
6145                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6146                SINT.getOperand(0).getValueType() == MVT::i32) {
6147       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6148       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6149
6150       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6151       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6152
6153       SDValue Store =
6154         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6155                      MachinePointerInfo::getFixedStack(FrameIdx),
6156                      false, false, 0);
6157
6158       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6159              "Expected an i32 store");
6160
6161       RLI.Ptr = FIdx;
6162       RLI.Chain = Store;
6163       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6164       RLI.Alignment = 4;
6165
6166       MachineMemOperand *MMO =
6167         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6168                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6169       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6170       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6171                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6172                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6173                                      Ops, MVT::i32, MMO);
6174     } else
6175       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6176
6177     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6178
6179     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6180       FP = DAG.getNode(ISD::FP_ROUND, dl,
6181                        MVT::f32, FP, DAG.getIntPtrConstant(0));
6182     return FP;
6183   }
6184
6185   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6186          "Unhandled INT_TO_FP type in custom expander!");
6187   // Since we only generate this in 64-bit mode, we can take advantage of
6188   // 64-bit registers.  In particular, sign extend the input value into the
6189   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6190   // then lfd it and fcfid it.
6191   MachineFunction &MF = DAG.getMachineFunction();
6192   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6193   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6194
6195   SDValue Ld;
6196   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6197     ReuseLoadInfo RLI;
6198     bool ReusingLoad;
6199     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6200                                             DAG))) {
6201       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6202       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6203
6204       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6205                                    MachinePointerInfo::getFixedStack(FrameIdx),
6206                                    false, false, 0);
6207
6208       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6209              "Expected an i32 store");
6210
6211       RLI.Ptr = FIdx;
6212       RLI.Chain = Store;
6213       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6214       RLI.Alignment = 4;
6215     }
6216
6217     MachineMemOperand *MMO =
6218       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6219                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6220     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6221     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6222                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6223                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6224                                  Ops, MVT::i32, MMO);
6225     if (ReusingLoad)
6226       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6227   } else {
6228     assert(Subtarget.isPPC64() &&
6229            "i32->FP without LFIWAX supported only on PPC64");
6230
6231     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6232     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6233
6234     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6235                                 Op.getOperand(0));
6236
6237     // STD the extended value into the stack slot.
6238     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6239                                  MachinePointerInfo::getFixedStack(FrameIdx),
6240                                  false, false, 0);
6241
6242     // Load the value as a double.
6243     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6244                      MachinePointerInfo::getFixedStack(FrameIdx),
6245                      false, false, false, 0);
6246   }
6247
6248   // FCFID it and return it.
6249   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6250   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6251     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6252   return FP;
6253 }
6254
6255 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6256                                             SelectionDAG &DAG) const {
6257   SDLoc dl(Op);
6258   /*
6259    The rounding mode is in bits 30:31 of FPSR, and has the following
6260    settings:
6261      00 Round to nearest
6262      01 Round to 0
6263      10 Round to +inf
6264      11 Round to -inf
6265
6266   FLT_ROUNDS, on the other hand, expects the following:
6267     -1 Undefined
6268      0 Round to 0
6269      1 Round to nearest
6270      2 Round to +inf
6271      3 Round to -inf
6272
6273   To perform the conversion, we do:
6274     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6275   */
6276
6277   MachineFunction &MF = DAG.getMachineFunction();
6278   EVT VT = Op.getValueType();
6279   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6280
6281   // Save FP Control Word to register
6282   EVT NodeTys[] = {
6283     MVT::f64,    // return register
6284     MVT::Glue    // unused in this context
6285   };
6286   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6287
6288   // Save FP register to stack slot
6289   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6290   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6291   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6292                                StackSlot, MachinePointerInfo(), false, false,0);
6293
6294   // Load FP Control Word from low 32 bits of stack slot.
6295   SDValue Four = DAG.getConstant(4, PtrVT);
6296   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6297   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6298                             false, false, false, 0);
6299
6300   // Transform as necessary
6301   SDValue CWD1 =
6302     DAG.getNode(ISD::AND, dl, MVT::i32,
6303                 CWD, DAG.getConstant(3, MVT::i32));
6304   SDValue CWD2 =
6305     DAG.getNode(ISD::SRL, dl, MVT::i32,
6306                 DAG.getNode(ISD::AND, dl, MVT::i32,
6307                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6308                                         CWD, DAG.getConstant(3, MVT::i32)),
6309                             DAG.getConstant(3, MVT::i32)),
6310                 DAG.getConstant(1, MVT::i32));
6311
6312   SDValue RetVal =
6313     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6314
6315   return DAG.getNode((VT.getSizeInBits() < 16 ?
6316                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6317 }
6318
6319 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6320   EVT VT = Op.getValueType();
6321   unsigned BitWidth = VT.getSizeInBits();
6322   SDLoc dl(Op);
6323   assert(Op.getNumOperands() == 3 &&
6324          VT == Op.getOperand(1).getValueType() &&
6325          "Unexpected SHL!");
6326
6327   // Expand into a bunch of logical ops.  Note that these ops
6328   // depend on the PPC behavior for oversized shift amounts.
6329   SDValue Lo = Op.getOperand(0);
6330   SDValue Hi = Op.getOperand(1);
6331   SDValue Amt = Op.getOperand(2);
6332   EVT AmtVT = Amt.getValueType();
6333
6334   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6335                              DAG.getConstant(BitWidth, AmtVT), Amt);
6336   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6337   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6338   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6339   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6340                              DAG.getConstant(-BitWidth, AmtVT));
6341   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6342   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6343   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6344   SDValue OutOps[] = { OutLo, OutHi };
6345   return DAG.getMergeValues(OutOps, dl);
6346 }
6347
6348 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6349   EVT VT = Op.getValueType();
6350   SDLoc dl(Op);
6351   unsigned BitWidth = VT.getSizeInBits();
6352   assert(Op.getNumOperands() == 3 &&
6353          VT == Op.getOperand(1).getValueType() &&
6354          "Unexpected SRL!");
6355
6356   // Expand into a bunch of logical ops.  Note that these ops
6357   // depend on the PPC behavior for oversized shift amounts.
6358   SDValue Lo = Op.getOperand(0);
6359   SDValue Hi = Op.getOperand(1);
6360   SDValue Amt = Op.getOperand(2);
6361   EVT AmtVT = Amt.getValueType();
6362
6363   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6364                              DAG.getConstant(BitWidth, AmtVT), Amt);
6365   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6366   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6367   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6368   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6369                              DAG.getConstant(-BitWidth, AmtVT));
6370   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6371   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6372   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6373   SDValue OutOps[] = { OutLo, OutHi };
6374   return DAG.getMergeValues(OutOps, dl);
6375 }
6376
6377 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6378   SDLoc dl(Op);
6379   EVT VT = Op.getValueType();
6380   unsigned BitWidth = VT.getSizeInBits();
6381   assert(Op.getNumOperands() == 3 &&
6382          VT == Op.getOperand(1).getValueType() &&
6383          "Unexpected SRA!");
6384
6385   // Expand into a bunch of logical ops, followed by a select_cc.
6386   SDValue Lo = Op.getOperand(0);
6387   SDValue Hi = Op.getOperand(1);
6388   SDValue Amt = Op.getOperand(2);
6389   EVT AmtVT = Amt.getValueType();
6390
6391   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6392                              DAG.getConstant(BitWidth, AmtVT), Amt);
6393   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6394   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6395   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6396   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6397                              DAG.getConstant(-BitWidth, AmtVT));
6398   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6399   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6400   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6401                                   Tmp4, Tmp6, ISD::SETLE);
6402   SDValue OutOps[] = { OutLo, OutHi };
6403   return DAG.getMergeValues(OutOps, dl);
6404 }
6405
6406 //===----------------------------------------------------------------------===//
6407 // Vector related lowering.
6408 //
6409
6410 /// BuildSplatI - Build a canonical splati of Val with an element size of
6411 /// SplatSize.  Cast the result to VT.
6412 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6413                              SelectionDAG &DAG, SDLoc dl) {
6414   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6415
6416   static const MVT VTys[] = { // canonical VT to use for each size.
6417     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6418   };
6419
6420   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6421
6422   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6423   if (Val == -1)
6424     SplatSize = 1;
6425
6426   EVT CanonicalVT = VTys[SplatSize-1];
6427
6428   // Build a canonical splat for this value.
6429   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6430   SmallVector<SDValue, 8> Ops;
6431   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6432   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6433   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6434 }
6435
6436 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6437 /// specified intrinsic ID.
6438 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6439                                 SelectionDAG &DAG, SDLoc dl,
6440                                 EVT DestVT = MVT::Other) {
6441   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6442   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6443                      DAG.getConstant(IID, MVT::i32), Op);
6444 }
6445
6446 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6447 /// specified intrinsic ID.
6448 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6449                                 SelectionDAG &DAG, SDLoc dl,
6450                                 EVT DestVT = MVT::Other) {
6451   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6452   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6453                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6454 }
6455
6456 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6457 /// specified intrinsic ID.
6458 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6459                                 SDValue Op2, SelectionDAG &DAG,
6460                                 SDLoc dl, EVT DestVT = MVT::Other) {
6461   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6462   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6463                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6464 }
6465
6466
6467 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6468 /// amount.  The result has the specified value type.
6469 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6470                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6471   // Force LHS/RHS to be the right type.
6472   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6473   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6474
6475   int Ops[16];
6476   for (unsigned i = 0; i != 16; ++i)
6477     Ops[i] = i + Amt;
6478   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6479   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6480 }
6481
6482 // If this is a case we can't handle, return null and let the default
6483 // expansion code take care of it.  If we CAN select this case, and if it
6484 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6485 // this case more efficiently than a constant pool load, lower it to the
6486 // sequence of ops that should be used.
6487 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6488                                              SelectionDAG &DAG) const {
6489   SDLoc dl(Op);
6490   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6491   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6492
6493   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6494     // We first build an i32 vector, load it into a QPX register,
6495     // then convert it to a floating-point vector and compare it
6496     // to a zero vector to get the boolean result.
6497     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6498     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6499     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6500     EVT PtrVT = getPointerTy();
6501     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6502
6503     assert(BVN->getNumOperands() == 4 &&
6504       "BUILD_VECTOR for v4i1 does not have 4 operands");
6505
6506     bool IsConst = true;
6507     for (unsigned i = 0; i < 4; ++i) {
6508       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6509       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6510         IsConst = false;
6511         break;
6512       }
6513     }
6514
6515     if (IsConst) {
6516       Constant *One =
6517         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6518       Constant *NegOne =
6519         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6520
6521       SmallVector<Constant*, 4> CV(4, NegOne);
6522       for (unsigned i = 0; i < 4; ++i) {
6523         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6524           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6525         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6526                    getConstantIntValue()->isZero())
6527           continue;
6528         else
6529           CV[i] = One;
6530       }
6531
6532       Constant *CP = ConstantVector::get(CV);
6533       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6534                       16 /* alignment */);
6535  
6536       SmallVector<SDValue, 2> Ops;
6537       Ops.push_back(DAG.getEntryNode());
6538       Ops.push_back(CPIdx);
6539
6540       SmallVector<EVT, 2> ValueVTs;
6541       ValueVTs.push_back(MVT::v4i1);
6542       ValueVTs.push_back(MVT::Other); // chain
6543       SDVTList VTs = DAG.getVTList(ValueVTs);
6544
6545       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6546         dl, VTs, Ops, MVT::v4f32,
6547         MachinePointerInfo::getConstantPool());
6548     }
6549
6550     SmallVector<SDValue, 4> Stores;
6551     for (unsigned i = 0; i < 4; ++i) {
6552       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6553
6554       unsigned Offset = 4*i;
6555       SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6556       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6557
6558       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6559       if (StoreSize > 4) {
6560         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6561                                            BVN->getOperand(i), Idx,
6562                                            PtrInfo.getWithOffset(Offset),
6563                                            MVT::i32, false, false, 0));
6564       } else {
6565         SDValue StoreValue = BVN->getOperand(i);
6566         if (StoreSize < 4)
6567           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6568
6569         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6570                                       StoreValue, Idx,
6571                                       PtrInfo.getWithOffset(Offset),
6572                                       false, false, 0));
6573       }
6574     }
6575
6576     SDValue StoreChain;
6577     if (!Stores.empty())
6578       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6579     else
6580       StoreChain = DAG.getEntryNode();
6581
6582     // Now load from v4i32 into the QPX register; this will extend it to
6583     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6584     // is typed as v4f64 because the QPX register integer states are not
6585     // explicitly represented.
6586
6587     SmallVector<SDValue, 2> Ops;
6588     Ops.push_back(StoreChain);
6589     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6590     Ops.push_back(FIdx);
6591
6592     SmallVector<EVT, 2> ValueVTs;
6593     ValueVTs.push_back(MVT::v4f64);
6594     ValueVTs.push_back(MVT::Other); // chain
6595     SDVTList VTs = DAG.getVTList(ValueVTs);
6596
6597     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6598       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6599     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6600       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6601       LoadedVect);
6602
6603     SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6604     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6605                           FPZeros, FPZeros, FPZeros, FPZeros);
6606
6607     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6608   }
6609
6610   // All other QPX vectors are handled by generic code.
6611   if (Subtarget.hasQPX())
6612     return SDValue();
6613
6614   // Check if this is a splat of a constant value.
6615   APInt APSplatBits, APSplatUndef;
6616   unsigned SplatBitSize;
6617   bool HasAnyUndefs;
6618   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6619                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6620     return SDValue();
6621
6622   unsigned SplatBits = APSplatBits.getZExtValue();
6623   unsigned SplatUndef = APSplatUndef.getZExtValue();
6624   unsigned SplatSize = SplatBitSize / 8;
6625
6626   // First, handle single instruction cases.
6627
6628   // All zeros?
6629   if (SplatBits == 0) {
6630     // Canonicalize all zero vectors to be v4i32.
6631     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6632       SDValue Z = DAG.getConstant(0, MVT::i32);
6633       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6634       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6635     }
6636     return Op;
6637   }
6638
6639   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6640   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6641                     (32-SplatBitSize));
6642   if (SextVal >= -16 && SextVal <= 15)
6643     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6644
6645
6646   // Two instruction sequences.
6647
6648   // If this value is in the range [-32,30] and is even, use:
6649   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6650   // If this value is in the range [17,31] and is odd, use:
6651   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6652   // If this value is in the range [-31,-17] and is odd, use:
6653   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6654   // Note the last two are three-instruction sequences.
6655   if (SextVal >= -32 && SextVal <= 31) {
6656     // To avoid having these optimizations undone by constant folding,
6657     // we convert to a pseudo that will be expanded later into one of
6658     // the above forms.
6659     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6660     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6661               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6662     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6663     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6664     if (VT == Op.getValueType())
6665       return RetVal;
6666     else
6667       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6668   }
6669
6670   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6671   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6672   // for fneg/fabs.
6673   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6674     // Make -1 and vspltisw -1:
6675     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6676
6677     // Make the VSLW intrinsic, computing 0x8000_0000.
6678     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6679                                    OnesV, DAG, dl);
6680
6681     // xor by OnesV to invert it.
6682     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6683     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6684   }
6685
6686   // The remaining cases assume either big endian element order or
6687   // a splat-size that equates to the element size of the vector
6688   // to be built.  An example that doesn't work for little endian is
6689   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6690   // and a vector element size of 16 bits.  The code below will
6691   // produce the vector in big endian element order, which for little
6692   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6693
6694   // For now, just avoid these optimizations in that case.
6695   // FIXME: Develop correct optimizations for LE with mismatched
6696   // splat and element sizes.
6697
6698   if (Subtarget.isLittleEndian() &&
6699       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6700     return SDValue();
6701
6702   // Check to see if this is a wide variety of vsplti*, binop self cases.
6703   static const signed char SplatCsts[] = {
6704     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6705     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6706   };
6707
6708   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6709     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6710     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6711     int i = SplatCsts[idx];
6712
6713     // Figure out what shift amount will be used by altivec if shifted by i in
6714     // this splat size.
6715     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6716
6717     // vsplti + shl self.
6718     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6719       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6720       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6721         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6722         Intrinsic::ppc_altivec_vslw
6723       };
6724       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6725       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6726     }
6727
6728     // vsplti + srl self.
6729     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6730       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6731       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6732         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6733         Intrinsic::ppc_altivec_vsrw
6734       };
6735       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6736       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6737     }
6738
6739     // vsplti + sra self.
6740     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6741       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6742       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6743         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6744         Intrinsic::ppc_altivec_vsraw
6745       };
6746       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6747       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6748     }
6749
6750     // vsplti + rol self.
6751     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6752                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6753       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6754       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6755         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6756         Intrinsic::ppc_altivec_vrlw
6757       };
6758       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6759       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6760     }
6761
6762     // t = vsplti c, result = vsldoi t, t, 1
6763     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6764       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6765       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6766     }
6767     // t = vsplti c, result = vsldoi t, t, 2
6768     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6769       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6770       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6771     }
6772     // t = vsplti c, result = vsldoi t, t, 3
6773     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6774       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6775       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6776     }
6777   }
6778
6779   return SDValue();
6780 }
6781
6782 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6783 /// the specified operations to build the shuffle.
6784 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6785                                       SDValue RHS, SelectionDAG &DAG,
6786                                       SDLoc dl) {
6787   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6788   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6789   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6790
6791   enum {
6792     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6793     OP_VMRGHW,
6794     OP_VMRGLW,
6795     OP_VSPLTISW0,
6796     OP_VSPLTISW1,
6797     OP_VSPLTISW2,
6798     OP_VSPLTISW3,
6799     OP_VSLDOI4,
6800     OP_VSLDOI8,
6801     OP_VSLDOI12
6802   };
6803
6804   if (OpNum == OP_COPY) {
6805     if (LHSID == (1*9+2)*9+3) return LHS;
6806     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6807     return RHS;
6808   }
6809
6810   SDValue OpLHS, OpRHS;
6811   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6812   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6813
6814   int ShufIdxs[16];
6815   switch (OpNum) {
6816   default: llvm_unreachable("Unknown i32 permute!");
6817   case OP_VMRGHW:
6818     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6819     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6820     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6821     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6822     break;
6823   case OP_VMRGLW:
6824     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6825     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6826     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6827     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6828     break;
6829   case OP_VSPLTISW0:
6830     for (unsigned i = 0; i != 16; ++i)
6831       ShufIdxs[i] = (i&3)+0;
6832     break;
6833   case OP_VSPLTISW1:
6834     for (unsigned i = 0; i != 16; ++i)
6835       ShufIdxs[i] = (i&3)+4;
6836     break;
6837   case OP_VSPLTISW2:
6838     for (unsigned i = 0; i != 16; ++i)
6839       ShufIdxs[i] = (i&3)+8;
6840     break;
6841   case OP_VSPLTISW3:
6842     for (unsigned i = 0; i != 16; ++i)
6843       ShufIdxs[i] = (i&3)+12;
6844     break;
6845   case OP_VSLDOI4:
6846     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6847   case OP_VSLDOI8:
6848     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6849   case OP_VSLDOI12:
6850     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6851   }
6852   EVT VT = OpLHS.getValueType();
6853   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6854   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6855   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6856   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6857 }
6858
6859 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6860 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6861 /// return the code it can be lowered into.  Worst case, it can always be
6862 /// lowered into a vperm.
6863 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6864                                                SelectionDAG &DAG) const {
6865   SDLoc dl(Op);
6866   SDValue V1 = Op.getOperand(0);
6867   SDValue V2 = Op.getOperand(1);
6868   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6869   EVT VT = Op.getValueType();
6870   bool isLittleEndian = Subtarget.isLittleEndian();
6871
6872   if (Subtarget.hasQPX()) {
6873     if (VT.getVectorNumElements() != 4)
6874       return SDValue();
6875
6876     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6877
6878     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6879     if (AlignIdx != -1) {
6880       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6881                          DAG.getConstant(AlignIdx, MVT::i32));
6882     } else if (SVOp->isSplat()) {
6883       int SplatIdx = SVOp->getSplatIndex();
6884       if (SplatIdx >= 4) {
6885         std::swap(V1, V2);
6886         SplatIdx -= 4;
6887       }
6888
6889       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6890       // nothing to do.
6891
6892       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6893                          DAG.getConstant(SplatIdx, MVT::i32));
6894     }
6895
6896     // Lower this into a qvgpci/qvfperm pair.
6897
6898     // Compute the qvgpci literal
6899     unsigned idx = 0;
6900     for (unsigned i = 0; i < 4; ++i) {
6901       int m = SVOp->getMaskElt(i);
6902       unsigned mm = m >= 0 ? (unsigned) m : i;
6903       idx |= mm << (3-i)*3;
6904     }
6905
6906     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6907                              DAG.getConstant(idx, MVT::i32));
6908     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6909   }
6910
6911   // Cases that are handled by instructions that take permute immediates
6912   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6913   // selected by the instruction selector.
6914   if (V2.getOpcode() == ISD::UNDEF) {
6915     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6916         PPC::isSplatShuffleMask(SVOp, 2) ||
6917         PPC::isSplatShuffleMask(SVOp, 4) ||
6918         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6919         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6920         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6921         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6922         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6923         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6924         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6925         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6926         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6927       return Op;
6928     }
6929   }
6930
6931   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6932   // and produce a fixed permutation.  If any of these match, do not lower to
6933   // VPERM.
6934   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6935   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6936       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6937       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6938       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6939       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6940       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6941       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6942       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6943       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6944     return Op;
6945
6946   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6947   // perfect shuffle table to emit an optimal matching sequence.
6948   ArrayRef<int> PermMask = SVOp->getMask();
6949
6950   unsigned PFIndexes[4];
6951   bool isFourElementShuffle = true;
6952   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6953     unsigned EltNo = 8;   // Start out undef.
6954     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6955       if (PermMask[i*4+j] < 0)
6956         continue;   // Undef, ignore it.
6957
6958       unsigned ByteSource = PermMask[i*4+j];
6959       if ((ByteSource & 3) != j) {
6960         isFourElementShuffle = false;
6961         break;
6962       }
6963
6964       if (EltNo == 8) {
6965         EltNo = ByteSource/4;
6966       } else if (EltNo != ByteSource/4) {
6967         isFourElementShuffle = false;
6968         break;
6969       }
6970     }
6971     PFIndexes[i] = EltNo;
6972   }
6973
6974   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6975   // perfect shuffle vector to determine if it is cost effective to do this as
6976   // discrete instructions, or whether we should use a vperm.
6977   // For now, we skip this for little endian until such time as we have a
6978   // little-endian perfect shuffle table.
6979   if (isFourElementShuffle && !isLittleEndian) {
6980     // Compute the index in the perfect shuffle table.
6981     unsigned PFTableIndex =
6982       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6983
6984     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6985     unsigned Cost  = (PFEntry >> 30);
6986
6987     // Determining when to avoid vperm is tricky.  Many things affect the cost
6988     // of vperm, particularly how many times the perm mask needs to be computed.
6989     // For example, if the perm mask can be hoisted out of a loop or is already
6990     // used (perhaps because there are multiple permutes with the same shuffle
6991     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6992     // the loop requires an extra register.
6993     //
6994     // As a compromise, we only emit discrete instructions if the shuffle can be
6995     // generated in 3 or fewer operations.  When we have loop information
6996     // available, if this block is within a loop, we should avoid using vperm
6997     // for 3-operation perms and use a constant pool load instead.
6998     if (Cost < 3)
6999       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7000   }
7001
7002   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7003   // vector that will get spilled to the constant pool.
7004   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7005
7006   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7007   // that it is in input element units, not in bytes.  Convert now.
7008
7009   // For little endian, the order of the input vectors is reversed, and
7010   // the permutation mask is complemented with respect to 31.  This is
7011   // necessary to produce proper semantics with the big-endian-biased vperm
7012   // instruction.
7013   EVT EltVT = V1.getValueType().getVectorElementType();
7014   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7015
7016   SmallVector<SDValue, 16> ResultMask;
7017   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7018     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7019
7020     for (unsigned j = 0; j != BytesPerElement; ++j)
7021       if (isLittleEndian)
7022         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7023                                              MVT::i32));
7024       else
7025         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7026                                              MVT::i32));
7027   }
7028
7029   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7030                                   ResultMask);
7031   if (isLittleEndian)
7032     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7033                        V2, V1, VPermMask);
7034   else
7035     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7036                        V1, V2, VPermMask);
7037 }
7038
7039 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7040 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7041 /// information about the intrinsic.
7042 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7043                                   bool &isDot, const PPCSubtarget &Subtarget) {
7044   unsigned IntrinsicID =
7045     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7046   CompareOpc = -1;
7047   isDot = false;
7048   switch (IntrinsicID) {
7049   default: return false;
7050     // Comparison predicates.
7051   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7052   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7053   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7054   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7055   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7056   case Intrinsic::ppc_altivec_vcmpequd_p: 
7057     if (Subtarget.hasP8Altivec()) {
7058       CompareOpc = 199; 
7059       isDot = 1; 
7060     }
7061     else 
7062       return false;
7063
7064     break;
7065   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7066   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7067   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7068   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7069   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7070   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7071     if (Subtarget.hasP8Altivec()) {
7072       CompareOpc = 967; 
7073       isDot = 1; 
7074     }
7075     else 
7076       return false;
7077
7078     break;
7079   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7080   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7081   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7082   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7083     if (Subtarget.hasP8Altivec()) {
7084       CompareOpc = 711; 
7085       isDot = 1; 
7086     }
7087     else 
7088       return false;
7089
7090     break;
7091       
7092     // Normal Comparisons.
7093   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7094   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7095   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7096   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7097   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7098   case Intrinsic::ppc_altivec_vcmpequd:
7099     if (Subtarget.hasP8Altivec()) {
7100       CompareOpc = 199; 
7101       isDot = 0; 
7102     }
7103     else
7104       return false;
7105
7106     break;
7107   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7108   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7109   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7110   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7111   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7112   case Intrinsic::ppc_altivec_vcmpgtsd:   
7113     if (Subtarget.hasP8Altivec()) {
7114       CompareOpc = 967; 
7115       isDot = 0; 
7116     }
7117     else
7118       return false;
7119
7120     break;
7121   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7122   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7123   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7124   case Intrinsic::ppc_altivec_vcmpgtud:   
7125     if (Subtarget.hasP8Altivec()) {
7126       CompareOpc = 711; 
7127       isDot = 0; 
7128     }
7129     else
7130       return false;
7131
7132     break;
7133   }
7134   return true;
7135 }
7136
7137 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7138 /// lower, do it, otherwise return null.
7139 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7140                                                    SelectionDAG &DAG) const {
7141   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7142   // opcode number of the comparison.
7143   SDLoc dl(Op);
7144   int CompareOpc;
7145   bool isDot;
7146   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7147     return SDValue();    // Don't custom lower most intrinsics.
7148
7149   // If this is a non-dot comparison, make the VCMP node and we are done.
7150   if (!isDot) {
7151     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7152                               Op.getOperand(1), Op.getOperand(2),
7153                               DAG.getConstant(CompareOpc, MVT::i32));
7154     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7155   }
7156
7157   // Create the PPCISD altivec 'dot' comparison node.
7158   SDValue Ops[] = {
7159     Op.getOperand(2),  // LHS
7160     Op.getOperand(3),  // RHS
7161     DAG.getConstant(CompareOpc, MVT::i32)
7162   };
7163   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7164   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7165
7166   // Now that we have the comparison, emit a copy from the CR to a GPR.
7167   // This is flagged to the above dot comparison.
7168   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7169                                 DAG.getRegister(PPC::CR6, MVT::i32),
7170                                 CompNode.getValue(1));
7171
7172   // Unpack the result based on how the target uses it.
7173   unsigned BitNo;   // Bit # of CR6.
7174   bool InvertBit;   // Invert result?
7175   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7176   default:  // Can't happen, don't crash on invalid number though.
7177   case 0:   // Return the value of the EQ bit of CR6.
7178     BitNo = 0; InvertBit = false;
7179     break;
7180   case 1:   // Return the inverted value of the EQ bit of CR6.
7181     BitNo = 0; InvertBit = true;
7182     break;
7183   case 2:   // Return the value of the LT bit of CR6.
7184     BitNo = 2; InvertBit = false;
7185     break;
7186   case 3:   // Return the inverted value of the LT bit of CR6.
7187     BitNo = 2; InvertBit = true;
7188     break;
7189   }
7190
7191   // Shift the bit into the low position.
7192   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7193                       DAG.getConstant(8-(3-BitNo), MVT::i32));
7194   // Isolate the bit.
7195   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7196                       DAG.getConstant(1, MVT::i32));
7197
7198   // If we are supposed to, toggle the bit.
7199   if (InvertBit)
7200     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7201                         DAG.getConstant(1, MVT::i32));
7202   return Flags;
7203 }
7204
7205 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7206                                                   SelectionDAG &DAG) const {
7207   SDLoc dl(Op);
7208   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7209   // instructions), but for smaller types, we need to first extend up to v2i32
7210   // before doing going farther.
7211   if (Op.getValueType() == MVT::v2i64) {
7212     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7213     if (ExtVT != MVT::v2i32) {
7214       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7215       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7216                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7217                                         ExtVT.getVectorElementType(), 4)));
7218       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7219       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7220                        DAG.getValueType(MVT::v2i32));
7221     }
7222
7223     return Op;
7224   }
7225
7226   return SDValue();
7227 }
7228
7229 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7230                                                    SelectionDAG &DAG) const {
7231   SDLoc dl(Op);
7232   // Create a stack slot that is 16-byte aligned.
7233   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7234   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7235   EVT PtrVT = getPointerTy();
7236   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7237
7238   // Store the input value into Value#0 of the stack slot.
7239   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7240                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7241                                false, false, 0);
7242   // Load it out.
7243   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7244                      false, false, false, 0);
7245 }
7246
7247 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7248                                                    SelectionDAG &DAG) const {
7249   SDLoc dl(Op);
7250   SDNode *N = Op.getNode();
7251
7252   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7253          "Unknown extract_vector_elt type");
7254
7255   SDValue Value = N->getOperand(0);
7256
7257   // The first part of this is like the store lowering except that we don't
7258   // need to track the chain.
7259
7260   // The values are now known to be -1 (false) or 1 (true). To convert this
7261   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7262   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7263   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7264
7265   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7266   // understand how to form the extending load.
7267   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7268   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7269                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7270
7271   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7272
7273   // Now convert to an integer and store.
7274   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7275     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7276     Value);
7277
7278   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7279   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7280   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7281   EVT PtrVT = getPointerTy();
7282   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7283
7284   SDValue StoreChain = DAG.getEntryNode();
7285   SmallVector<SDValue, 2> Ops;
7286   Ops.push_back(StoreChain);
7287   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7288   Ops.push_back(Value);
7289   Ops.push_back(FIdx);
7290
7291   SmallVector<EVT, 2> ValueVTs;
7292   ValueVTs.push_back(MVT::Other); // chain
7293   SDVTList VTs = DAG.getVTList(ValueVTs);
7294
7295   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7296     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7297
7298   // Extract the value requested.
7299   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7300   SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7301   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7302
7303   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7304                                PtrInfo.getWithOffset(Offset),
7305                                false, false, false, 0);
7306
7307   if (!Subtarget.useCRBits())
7308     return IntVal;
7309
7310   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7311 }
7312
7313 /// Lowering for QPX v4i1 loads
7314 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7315                                            SelectionDAG &DAG) const {
7316   SDLoc dl(Op);
7317   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7318   SDValue LoadChain = LN->getChain();
7319   SDValue BasePtr = LN->getBasePtr();
7320
7321   if (Op.getValueType() == MVT::v4f64 ||
7322       Op.getValueType() == MVT::v4f32) {
7323     EVT MemVT = LN->getMemoryVT();
7324     unsigned Alignment = LN->getAlignment();
7325
7326     // If this load is properly aligned, then it is legal.
7327     if (Alignment >= MemVT.getStoreSize())
7328       return Op;
7329
7330     EVT ScalarVT = Op.getValueType().getScalarType(),
7331         ScalarMemVT = MemVT.getScalarType();
7332     unsigned Stride = ScalarMemVT.getStoreSize();
7333
7334     SmallVector<SDValue, 8> Vals, LoadChains;
7335     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7336       SDValue Load;
7337       if (ScalarVT != ScalarMemVT)
7338         Load =
7339           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7340                          BasePtr,
7341                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7342                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7343                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7344                          LN->getAAInfo());
7345       else
7346         Load =
7347           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7348                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7349                        LN->isVolatile(), LN->isNonTemporal(),
7350                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7351                        LN->getAAInfo());
7352
7353       if (Idx == 0 && LN->isIndexed()) {
7354         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7355                "Unknown addressing mode on vector load");
7356         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7357                                   LN->getAddressingMode());
7358       }
7359
7360       Vals.push_back(Load);
7361       LoadChains.push_back(Load.getValue(1));
7362
7363       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7364                             DAG.getConstant(Stride, BasePtr.getValueType()));
7365     }
7366
7367     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7368     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7369                                    Op.getValueType(), Vals);
7370
7371     if (LN->isIndexed()) {
7372       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7373       return DAG.getMergeValues(RetOps, dl);
7374     }
7375
7376     SDValue RetOps[] = { Value, TF };
7377     return DAG.getMergeValues(RetOps, dl);
7378   }
7379
7380   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7381   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7382
7383   // To lower v4i1 from a byte array, we load the byte elements of the
7384   // vector and then reuse the BUILD_VECTOR logic.
7385
7386   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7387   for (unsigned i = 0; i < 4; ++i) {
7388     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7389     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7390
7391     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7392                         dl, MVT::i32, LoadChain, Idx,
7393                         LN->getPointerInfo().getWithOffset(i),
7394                         MVT::i8 /* memory type */,
7395                         LN->isVolatile(), LN->isNonTemporal(),
7396                         LN->isInvariant(),
7397                         1 /* alignment */, LN->getAAInfo()));
7398     VectElmtChains.push_back(VectElmts[i].getValue(1));
7399   }
7400
7401   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7402   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7403
7404   SDValue RVals[] = { Value, LoadChain };
7405   return DAG.getMergeValues(RVals, dl);
7406 }
7407
7408 /// Lowering for QPX v4i1 stores
7409 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7410                                             SelectionDAG &DAG) const {
7411   SDLoc dl(Op);
7412   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7413   SDValue StoreChain = SN->getChain();
7414   SDValue BasePtr = SN->getBasePtr();
7415   SDValue Value = SN->getValue();
7416
7417   if (Value.getValueType() == MVT::v4f64 ||
7418       Value.getValueType() == MVT::v4f32) {
7419     EVT MemVT = SN->getMemoryVT();
7420     unsigned Alignment = SN->getAlignment();
7421
7422     // If this store is properly aligned, then it is legal.
7423     if (Alignment >= MemVT.getStoreSize())
7424       return Op;
7425
7426     EVT ScalarVT = Value.getValueType().getScalarType(),
7427         ScalarMemVT = MemVT.getScalarType();
7428     unsigned Stride = ScalarMemVT.getStoreSize();
7429
7430     SmallVector<SDValue, 8> Stores;
7431     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7432       SDValue Ex =
7433         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7434                     DAG.getConstant(Idx, getVectorIdxTy()));
7435       SDValue Store;
7436       if (ScalarVT != ScalarMemVT)
7437         Store =
7438           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7439                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7440                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7441                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7442       else
7443         Store =
7444           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7445                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7446                        SN->isVolatile(), SN->isNonTemporal(),
7447                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7448
7449       if (Idx == 0 && SN->isIndexed()) {
7450         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7451                "Unknown addressing mode on vector store");
7452         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7453                                     SN->getAddressingMode());
7454       }
7455
7456       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7457                             DAG.getConstant(Stride, BasePtr.getValueType()));
7458       Stores.push_back(Store);
7459     }
7460
7461     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7462
7463     if (SN->isIndexed()) {
7464       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7465       return DAG.getMergeValues(RetOps, dl);
7466     }
7467
7468     return TF;
7469   }
7470
7471   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7472   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7473
7474   // The values are now known to be -1 (false) or 1 (true). To convert this
7475   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7476   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7477   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7478
7479   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7480   // understand how to form the extending load.
7481   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7482   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7483                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7484
7485   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7486
7487   // Now convert to an integer and store.
7488   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7489     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7490     Value);
7491
7492   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7493   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7494   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7495   EVT PtrVT = getPointerTy();
7496   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7497
7498   SmallVector<SDValue, 2> Ops;
7499   Ops.push_back(StoreChain);
7500   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7501   Ops.push_back(Value);
7502   Ops.push_back(FIdx);
7503
7504   SmallVector<EVT, 2> ValueVTs;
7505   ValueVTs.push_back(MVT::Other); // chain
7506   SDVTList VTs = DAG.getVTList(ValueVTs);
7507
7508   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7509     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7510
7511   // Move data into the byte array.
7512   SmallVector<SDValue, 4> Loads, LoadChains;
7513   for (unsigned i = 0; i < 4; ++i) {
7514     unsigned Offset = 4*i;
7515     SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7516     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7517
7518     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7519                                    PtrInfo.getWithOffset(Offset),
7520                                    false, false, false, 0));
7521     LoadChains.push_back(Loads[i].getValue(1));
7522   }
7523
7524   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7525
7526   SmallVector<SDValue, 4> Stores;
7527   for (unsigned i = 0; i < 4; ++i) {
7528     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7529     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7530
7531     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7532                                        SN->getPointerInfo().getWithOffset(i),
7533                                        MVT::i8 /* memory type */,
7534                                        SN->isNonTemporal(), SN->isVolatile(), 
7535                                        1 /* alignment */, SN->getAAInfo()));
7536   }
7537
7538   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7539
7540   return StoreChain;
7541 }
7542
7543 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7544   SDLoc dl(Op);
7545   if (Op.getValueType() == MVT::v4i32) {
7546     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7547
7548     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7549     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7550
7551     SDValue RHSSwap =   // = vrlw RHS, 16
7552       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7553
7554     // Shrinkify inputs to v8i16.
7555     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7556     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7557     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7558
7559     // Low parts multiplied together, generating 32-bit results (we ignore the
7560     // top parts).
7561     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7562                                         LHS, RHS, DAG, dl, MVT::v4i32);
7563
7564     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7565                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7566     // Shift the high parts up 16 bits.
7567     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7568                               Neg16, DAG, dl);
7569     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7570   } else if (Op.getValueType() == MVT::v8i16) {
7571     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7572
7573     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7574
7575     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7576                             LHS, RHS, Zero, DAG, dl);
7577   } else if (Op.getValueType() == MVT::v16i8) {
7578     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7579     bool isLittleEndian = Subtarget.isLittleEndian();
7580
7581     // Multiply the even 8-bit parts, producing 16-bit sums.
7582     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7583                                            LHS, RHS, DAG, dl, MVT::v8i16);
7584     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7585
7586     // Multiply the odd 8-bit parts, producing 16-bit sums.
7587     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7588                                           LHS, RHS, DAG, dl, MVT::v8i16);
7589     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7590
7591     // Merge the results together.  Because vmuleub and vmuloub are
7592     // instructions with a big-endian bias, we must reverse the
7593     // element numbering and reverse the meaning of "odd" and "even"
7594     // when generating little endian code.
7595     int Ops[16];
7596     for (unsigned i = 0; i != 8; ++i) {
7597       if (isLittleEndian) {
7598         Ops[i*2  ] = 2*i;
7599         Ops[i*2+1] = 2*i+16;
7600       } else {
7601         Ops[i*2  ] = 2*i+1;
7602         Ops[i*2+1] = 2*i+1+16;
7603       }
7604     }
7605     if (isLittleEndian)
7606       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7607     else
7608       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7609   } else {
7610     llvm_unreachable("Unknown mul to lower!");
7611   }
7612 }
7613
7614 /// LowerOperation - Provide custom lowering hooks for some operations.
7615 ///
7616 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7617   switch (Op.getOpcode()) {
7618   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7619   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7620   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7621   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7622   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7623   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7624   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7625   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7626   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7627   case ISD::VASTART:
7628     return LowerVASTART(Op, DAG, Subtarget);
7629
7630   case ISD::VAARG:
7631     return LowerVAARG(Op, DAG, Subtarget);
7632
7633   case ISD::VACOPY:
7634     return LowerVACOPY(Op, DAG, Subtarget);
7635
7636   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7637   case ISD::DYNAMIC_STACKALLOC:
7638     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7639
7640   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7641   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7642
7643   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7644   case ISD::STORE:              return LowerSTORE(Op, DAG);
7645   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7646   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7647   case ISD::FP_TO_UINT:
7648   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7649                                                       SDLoc(Op));
7650   case ISD::UINT_TO_FP:
7651   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7652   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7653
7654   // Lower 64-bit shifts.
7655   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7656   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7657   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7658
7659   // Vector-related lowering.
7660   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7661   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7662   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7663   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7664   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7665   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7666   case ISD::MUL:                return LowerMUL(Op, DAG);
7667
7668   // For counter-based loop handling.
7669   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7670
7671   // Frame & Return address.
7672   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7673   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7674   }
7675 }
7676
7677 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7678                                            SmallVectorImpl<SDValue>&Results,
7679                                            SelectionDAG &DAG) const {
7680   SDLoc dl(N);
7681   switch (N->getOpcode()) {
7682   default:
7683     llvm_unreachable("Do not know how to custom type legalize this operation!");
7684   case ISD::READCYCLECOUNTER: {
7685     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7686     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7687
7688     Results.push_back(RTB);
7689     Results.push_back(RTB.getValue(1));
7690     Results.push_back(RTB.getValue(2));
7691     break;
7692   }
7693   case ISD::INTRINSIC_W_CHAIN: {
7694     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7695         Intrinsic::ppc_is_decremented_ctr_nonzero)
7696       break;
7697
7698     assert(N->getValueType(0) == MVT::i1 &&
7699            "Unexpected result type for CTR decrement intrinsic");
7700     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7701     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7702     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7703                                  N->getOperand(1)); 
7704
7705     Results.push_back(NewInt);
7706     Results.push_back(NewInt.getValue(1));
7707     break;
7708   }
7709   case ISD::VAARG: {
7710     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7711       return;
7712
7713     EVT VT = N->getValueType(0);
7714
7715     if (VT == MVT::i64) {
7716       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7717
7718       Results.push_back(NewNode);
7719       Results.push_back(NewNode.getValue(1));
7720     }
7721     return;
7722   }
7723   case ISD::FP_ROUND_INREG: {
7724     assert(N->getValueType(0) == MVT::ppcf128);
7725     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7726     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7727                              MVT::f64, N->getOperand(0),
7728                              DAG.getIntPtrConstant(0));
7729     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7730                              MVT::f64, N->getOperand(0),
7731                              DAG.getIntPtrConstant(1));
7732
7733     // Add the two halves of the long double in round-to-zero mode.
7734     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7735
7736     // We know the low half is about to be thrown away, so just use something
7737     // convenient.
7738     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7739                                 FPreg, FPreg));
7740     return;
7741   }
7742   case ISD::FP_TO_SINT:
7743     // LowerFP_TO_INT() can only handle f32 and f64.
7744     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7745       return;
7746     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7747     return;
7748   }
7749 }
7750
7751
7752 //===----------------------------------------------------------------------===//
7753 //  Other Lowering Code
7754 //===----------------------------------------------------------------------===//
7755
7756 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7757   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7758   Function *Func = Intrinsic::getDeclaration(M, Id);
7759   return Builder.CreateCall(Func);
7760 }
7761
7762 // The mappings for emitLeading/TrailingFence is taken from
7763 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7764 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7765                                          AtomicOrdering Ord, bool IsStore,
7766                                          bool IsLoad) const {
7767   if (Ord == SequentiallyConsistent)
7768     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7769   else if (isAtLeastRelease(Ord))
7770     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7771   else
7772     return nullptr;
7773 }
7774
7775 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7776                                           AtomicOrdering Ord, bool IsStore,
7777                                           bool IsLoad) const {
7778   if (IsLoad && isAtLeastAcquire(Ord))
7779     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7780   // FIXME: this is too conservative, a dependent branch + isync is enough.
7781   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7782   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7783   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7784   else
7785     return nullptr;
7786 }
7787
7788 MachineBasicBlock *
7789 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7790                                     unsigned AtomicSize,
7791                                     unsigned BinOpcode) const {
7792   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7793   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7794
7795   auto LoadMnemonic = PPC::LDARX;
7796   auto StoreMnemonic = PPC::STDCX;
7797   switch (AtomicSize) {
7798   default:
7799     llvm_unreachable("Unexpected size of atomic entity");
7800   case 1:
7801     LoadMnemonic = PPC::LBARX;
7802     StoreMnemonic = PPC::STBCX;
7803     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7804     break;
7805   case 2:
7806     LoadMnemonic = PPC::LHARX;
7807     StoreMnemonic = PPC::STHCX;
7808     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7809     break;
7810   case 4:
7811     LoadMnemonic = PPC::LWARX;
7812     StoreMnemonic = PPC::STWCX;
7813     break;
7814   case 8:
7815     LoadMnemonic = PPC::LDARX;
7816     StoreMnemonic = PPC::STDCX;
7817     break;
7818   }
7819
7820   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7821   MachineFunction *F = BB->getParent();
7822   MachineFunction::iterator It = BB;
7823   ++It;
7824
7825   unsigned dest = MI->getOperand(0).getReg();
7826   unsigned ptrA = MI->getOperand(1).getReg();
7827   unsigned ptrB = MI->getOperand(2).getReg();
7828   unsigned incr = MI->getOperand(3).getReg();
7829   DebugLoc dl = MI->getDebugLoc();
7830
7831   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7832   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7833   F->insert(It, loopMBB);
7834   F->insert(It, exitMBB);
7835   exitMBB->splice(exitMBB->begin(), BB,
7836                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7837   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7838
7839   MachineRegisterInfo &RegInfo = F->getRegInfo();
7840   unsigned TmpReg = (!BinOpcode) ? incr :
7841     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7842                                            : &PPC::GPRCRegClass);
7843
7844   //  thisMBB:
7845   //   ...
7846   //   fallthrough --> loopMBB
7847   BB->addSuccessor(loopMBB);
7848
7849   //  loopMBB:
7850   //   l[wd]arx dest, ptr
7851   //   add r0, dest, incr
7852   //   st[wd]cx. r0, ptr
7853   //   bne- loopMBB
7854   //   fallthrough --> exitMBB
7855   BB = loopMBB;
7856   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7857     .addReg(ptrA).addReg(ptrB);
7858   if (BinOpcode)
7859     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7860   BuildMI(BB, dl, TII->get(StoreMnemonic))
7861     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7862   BuildMI(BB, dl, TII->get(PPC::BCC))
7863     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7864   BB->addSuccessor(loopMBB);
7865   BB->addSuccessor(exitMBB);
7866
7867   //  exitMBB:
7868   //   ...
7869   BB = exitMBB;
7870   return BB;
7871 }
7872
7873 MachineBasicBlock *
7874 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7875                                             MachineBasicBlock *BB,
7876                                             bool is8bit,    // operation
7877                                             unsigned BinOpcode) const {
7878   // If we support part-word atomic mnemonics, just use them
7879   if (Subtarget.hasPartwordAtomics())
7880     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7881
7882   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7883   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7884   // In 64 bit mode we have to use 64 bits for addresses, even though the
7885   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
7886   // registers without caring whether they're 32 or 64, but here we're
7887   // doing actual arithmetic on the addresses.
7888   bool is64bit = Subtarget.isPPC64();
7889   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7890
7891   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7892   MachineFunction *F = BB->getParent();
7893   MachineFunction::iterator It = BB;
7894   ++It;
7895
7896   unsigned dest = MI->getOperand(0).getReg();
7897   unsigned ptrA = MI->getOperand(1).getReg();
7898   unsigned ptrB = MI->getOperand(2).getReg();
7899   unsigned incr = MI->getOperand(3).getReg();
7900   DebugLoc dl = MI->getDebugLoc();
7901
7902   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7903   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7904   F->insert(It, loopMBB);
7905   F->insert(It, exitMBB);
7906   exitMBB->splice(exitMBB->begin(), BB,
7907                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7908   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7909
7910   MachineRegisterInfo &RegInfo = F->getRegInfo();
7911   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7912                                           : &PPC::GPRCRegClass;
7913   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7914   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7915   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7916   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7917   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7918   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7919   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7920   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7921   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7922   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7923   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7924   unsigned Ptr1Reg;
7925   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7926
7927   //  thisMBB:
7928   //   ...
7929   //   fallthrough --> loopMBB
7930   BB->addSuccessor(loopMBB);
7931
7932   // The 4-byte load must be aligned, while a char or short may be
7933   // anywhere in the word.  Hence all this nasty bookkeeping code.
7934   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7935   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7936   //   xori shift, shift1, 24 [16]
7937   //   rlwinm ptr, ptr1, 0, 0, 29
7938   //   slw incr2, incr, shift
7939   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7940   //   slw mask, mask2, shift
7941   //  loopMBB:
7942   //   lwarx tmpDest, ptr
7943   //   add tmp, tmpDest, incr2
7944   //   andc tmp2, tmpDest, mask
7945   //   and tmp3, tmp, mask
7946   //   or tmp4, tmp3, tmp2
7947   //   stwcx. tmp4, ptr
7948   //   bne- loopMBB
7949   //   fallthrough --> exitMBB
7950   //   srw dest, tmpDest, shift
7951   if (ptrA != ZeroReg) {
7952     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7953     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7954       .addReg(ptrA).addReg(ptrB);
7955   } else {
7956     Ptr1Reg = ptrB;
7957   }
7958   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7959       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7960   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7961       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7962   if (is64bit)
7963     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7964       .addReg(Ptr1Reg).addImm(0).addImm(61);
7965   else
7966     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7967       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7968   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7969       .addReg(incr).addReg(ShiftReg);
7970   if (is8bit)
7971     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7972   else {
7973     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7974     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7975   }
7976   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7977       .addReg(Mask2Reg).addReg(ShiftReg);
7978
7979   BB = loopMBB;
7980   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7981     .addReg(ZeroReg).addReg(PtrReg);
7982   if (BinOpcode)
7983     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7984       .addReg(Incr2Reg).addReg(TmpDestReg);
7985   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7986     .addReg(TmpDestReg).addReg(MaskReg);
7987   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7988     .addReg(TmpReg).addReg(MaskReg);
7989   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7990     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7991   BuildMI(BB, dl, TII->get(PPC::STWCX))
7992     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7993   BuildMI(BB, dl, TII->get(PPC::BCC))
7994     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7995   BB->addSuccessor(loopMBB);
7996   BB->addSuccessor(exitMBB);
7997
7998   //  exitMBB:
7999   //   ...
8000   BB = exitMBB;
8001   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8002     .addReg(ShiftReg);
8003   return BB;
8004 }
8005
8006 llvm::MachineBasicBlock*
8007 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8008                                     MachineBasicBlock *MBB) const {
8009   DebugLoc DL = MI->getDebugLoc();
8010   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8011
8012   MachineFunction *MF = MBB->getParent();
8013   MachineRegisterInfo &MRI = MF->getRegInfo();
8014
8015   const BasicBlock *BB = MBB->getBasicBlock();
8016   MachineFunction::iterator I = MBB;
8017   ++I;
8018
8019   // Memory Reference
8020   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8021   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8022
8023   unsigned DstReg = MI->getOperand(0).getReg();
8024   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8025   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8026   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8027   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8028
8029   MVT PVT = getPointerTy();
8030   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8031          "Invalid Pointer Size!");
8032   // For v = setjmp(buf), we generate
8033   //
8034   // thisMBB:
8035   //  SjLjSetup mainMBB
8036   //  bl mainMBB
8037   //  v_restore = 1
8038   //  b sinkMBB
8039   //
8040   // mainMBB:
8041   //  buf[LabelOffset] = LR
8042   //  v_main = 0
8043   //
8044   // sinkMBB:
8045   //  v = phi(main, restore)
8046   //
8047
8048   MachineBasicBlock *thisMBB = MBB;
8049   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8050   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8051   MF->insert(I, mainMBB);
8052   MF->insert(I, sinkMBB);
8053
8054   MachineInstrBuilder MIB;
8055
8056   // Transfer the remainder of BB and its successor edges to sinkMBB.
8057   sinkMBB->splice(sinkMBB->begin(), MBB,
8058                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8059   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8060
8061   // Note that the structure of the jmp_buf used here is not compatible
8062   // with that used by libc, and is not designed to be. Specifically, it
8063   // stores only those 'reserved' registers that LLVM does not otherwise
8064   // understand how to spill. Also, by convention, by the time this
8065   // intrinsic is called, Clang has already stored the frame address in the
8066   // first slot of the buffer and stack address in the third. Following the
8067   // X86 target code, we'll store the jump address in the second slot. We also
8068   // need to save the TOC pointer (R2) to handle jumps between shared
8069   // libraries, and that will be stored in the fourth slot. The thread
8070   // identifier (R13) is not affected.
8071
8072   // thisMBB:
8073   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8074   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8075   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8076
8077   // Prepare IP either in reg.
8078   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8079   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8080   unsigned BufReg = MI->getOperand(1).getReg();
8081
8082   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8083     setUsesTOCBasePtr(*MBB->getParent());
8084     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8085             .addReg(PPC::X2)
8086             .addImm(TOCOffset)
8087             .addReg(BufReg);
8088     MIB.setMemRefs(MMOBegin, MMOEnd);
8089   }
8090
8091   // Naked functions never have a base pointer, and so we use r1. For all
8092   // other functions, this decision must be delayed until during PEI.
8093   unsigned BaseReg;
8094   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8095     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8096   else
8097     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8098
8099   MIB = BuildMI(*thisMBB, MI, DL,
8100                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8101             .addReg(BaseReg)
8102             .addImm(BPOffset)
8103             .addReg(BufReg);
8104   MIB.setMemRefs(MMOBegin, MMOEnd);
8105
8106   // Setup
8107   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8108   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8109   MIB.addRegMask(TRI->getNoPreservedMask());
8110
8111   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8112
8113   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8114           .addMBB(mainMBB);
8115   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8116
8117   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8118   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8119
8120   // mainMBB:
8121   //  mainDstReg = 0
8122   MIB =
8123       BuildMI(mainMBB, DL,
8124               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8125
8126   // Store IP
8127   if (Subtarget.isPPC64()) {
8128     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8129             .addReg(LabelReg)
8130             .addImm(LabelOffset)
8131             .addReg(BufReg);
8132   } else {
8133     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8134             .addReg(LabelReg)
8135             .addImm(LabelOffset)
8136             .addReg(BufReg);
8137   }
8138
8139   MIB.setMemRefs(MMOBegin, MMOEnd);
8140
8141   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8142   mainMBB->addSuccessor(sinkMBB);
8143
8144   // sinkMBB:
8145   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8146           TII->get(PPC::PHI), DstReg)
8147     .addReg(mainDstReg).addMBB(mainMBB)
8148     .addReg(restoreDstReg).addMBB(thisMBB);
8149
8150   MI->eraseFromParent();
8151   return sinkMBB;
8152 }
8153
8154 MachineBasicBlock *
8155 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8156                                      MachineBasicBlock *MBB) const {
8157   DebugLoc DL = MI->getDebugLoc();
8158   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8159
8160   MachineFunction *MF = MBB->getParent();
8161   MachineRegisterInfo &MRI = MF->getRegInfo();
8162
8163   // Memory Reference
8164   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8165   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8166
8167   MVT PVT = getPointerTy();
8168   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8169          "Invalid Pointer Size!");
8170
8171   const TargetRegisterClass *RC =
8172     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8173   unsigned Tmp = MRI.createVirtualRegister(RC);
8174   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8175   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8176   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8177   unsigned BP =
8178       (PVT == MVT::i64)
8179           ? PPC::X30
8180           : (Subtarget.isSVR4ABI() &&
8181                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8182                  ? PPC::R29
8183                  : PPC::R30);
8184
8185   MachineInstrBuilder MIB;
8186
8187   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8188   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8189   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8190   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8191
8192   unsigned BufReg = MI->getOperand(0).getReg();
8193
8194   // Reload FP (the jumped-to function may not have had a
8195   // frame pointer, and if so, then its r31 will be restored
8196   // as necessary).
8197   if (PVT == MVT::i64) {
8198     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8199             .addImm(0)
8200             .addReg(BufReg);
8201   } else {
8202     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8203             .addImm(0)
8204             .addReg(BufReg);
8205   }
8206   MIB.setMemRefs(MMOBegin, MMOEnd);
8207
8208   // Reload IP
8209   if (PVT == MVT::i64) {
8210     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8211             .addImm(LabelOffset)
8212             .addReg(BufReg);
8213   } else {
8214     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8215             .addImm(LabelOffset)
8216             .addReg(BufReg);
8217   }
8218   MIB.setMemRefs(MMOBegin, MMOEnd);
8219
8220   // Reload SP
8221   if (PVT == MVT::i64) {
8222     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8223             .addImm(SPOffset)
8224             .addReg(BufReg);
8225   } else {
8226     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8227             .addImm(SPOffset)
8228             .addReg(BufReg);
8229   }
8230   MIB.setMemRefs(MMOBegin, MMOEnd);
8231
8232   // Reload BP
8233   if (PVT == MVT::i64) {
8234     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8235             .addImm(BPOffset)
8236             .addReg(BufReg);
8237   } else {
8238     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8239             .addImm(BPOffset)
8240             .addReg(BufReg);
8241   }
8242   MIB.setMemRefs(MMOBegin, MMOEnd);
8243
8244   // Reload TOC
8245   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8246     setUsesTOCBasePtr(*MBB->getParent());
8247     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8248             .addImm(TOCOffset)
8249             .addReg(BufReg);
8250
8251     MIB.setMemRefs(MMOBegin, MMOEnd);
8252   }
8253
8254   // Jump
8255   BuildMI(*MBB, MI, DL,
8256           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8257   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8258
8259   MI->eraseFromParent();
8260   return MBB;
8261 }
8262
8263 MachineBasicBlock *
8264 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8265                                                MachineBasicBlock *BB) const {
8266   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8267       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8268     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8269         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8270       // Call lowering should have added an r2 operand to indicate a dependence
8271       // on the TOC base pointer value. It can't however, because there is no
8272       // way to mark the dependence as implicit there, and so the stackmap code
8273       // will confuse it with a regular operand. Instead, add the dependence
8274       // here.
8275       setUsesTOCBasePtr(*BB->getParent());
8276       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8277     }
8278
8279     return emitPatchPoint(MI, BB);
8280   }
8281
8282   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8283       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8284     return emitEHSjLjSetJmp(MI, BB);
8285   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8286              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8287     return emitEHSjLjLongJmp(MI, BB);
8288   }
8289
8290   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8291
8292   // To "insert" these instructions we actually have to insert their
8293   // control-flow patterns.
8294   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8295   MachineFunction::iterator It = BB;
8296   ++It;
8297
8298   MachineFunction *F = BB->getParent();
8299
8300   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8301                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8302                               MI->getOpcode() == PPC::SELECT_I4 ||
8303                               MI->getOpcode() == PPC::SELECT_I8)) {
8304     SmallVector<MachineOperand, 2> Cond;
8305     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8306         MI->getOpcode() == PPC::SELECT_CC_I8)
8307       Cond.push_back(MI->getOperand(4));
8308     else
8309       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8310     Cond.push_back(MI->getOperand(1));
8311
8312     DebugLoc dl = MI->getDebugLoc();
8313     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8314                       Cond, MI->getOperand(2).getReg(),
8315                       MI->getOperand(3).getReg());
8316   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8317              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8318              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8319              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8320              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8321              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8322              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8323              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8324              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8325              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8326              MI->getOpcode() == PPC::SELECT_I4 ||
8327              MI->getOpcode() == PPC::SELECT_I8 ||
8328              MI->getOpcode() == PPC::SELECT_F4 ||
8329              MI->getOpcode() == PPC::SELECT_F8 ||
8330              MI->getOpcode() == PPC::SELECT_QFRC ||
8331              MI->getOpcode() == PPC::SELECT_QSRC ||
8332              MI->getOpcode() == PPC::SELECT_QBRC ||
8333              MI->getOpcode() == PPC::SELECT_VRRC ||
8334              MI->getOpcode() == PPC::SELECT_VSFRC ||
8335              MI->getOpcode() == PPC::SELECT_VSRC) {
8336     // The incoming instruction knows the destination vreg to set, the
8337     // condition code register to branch on, the true/false values to
8338     // select between, and a branch opcode to use.
8339
8340     //  thisMBB:
8341     //  ...
8342     //   TrueVal = ...
8343     //   cmpTY ccX, r1, r2
8344     //   bCC copy1MBB
8345     //   fallthrough --> copy0MBB
8346     MachineBasicBlock *thisMBB = BB;
8347     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8348     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8349     DebugLoc dl = MI->getDebugLoc();
8350     F->insert(It, copy0MBB);
8351     F->insert(It, sinkMBB);
8352
8353     // Transfer the remainder of BB and its successor edges to sinkMBB.
8354     sinkMBB->splice(sinkMBB->begin(), BB,
8355                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8356     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8357
8358     // Next, add the true and fallthrough blocks as its successors.
8359     BB->addSuccessor(copy0MBB);
8360     BB->addSuccessor(sinkMBB);
8361
8362     if (MI->getOpcode() == PPC::SELECT_I4 ||
8363         MI->getOpcode() == PPC::SELECT_I8 ||
8364         MI->getOpcode() == PPC::SELECT_F4 ||
8365         MI->getOpcode() == PPC::SELECT_F8 ||
8366         MI->getOpcode() == PPC::SELECT_QFRC ||
8367         MI->getOpcode() == PPC::SELECT_QSRC ||
8368         MI->getOpcode() == PPC::SELECT_QBRC ||
8369         MI->getOpcode() == PPC::SELECT_VRRC ||
8370         MI->getOpcode() == PPC::SELECT_VSFRC ||
8371         MI->getOpcode() == PPC::SELECT_VSRC) {
8372       BuildMI(BB, dl, TII->get(PPC::BC))
8373         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8374     } else {
8375       unsigned SelectPred = MI->getOperand(4).getImm();
8376       BuildMI(BB, dl, TII->get(PPC::BCC))
8377         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8378     }
8379
8380     //  copy0MBB:
8381     //   %FalseValue = ...
8382     //   # fallthrough to sinkMBB
8383     BB = copy0MBB;
8384
8385     // Update machine-CFG edges
8386     BB->addSuccessor(sinkMBB);
8387
8388     //  sinkMBB:
8389     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8390     //  ...
8391     BB = sinkMBB;
8392     BuildMI(*BB, BB->begin(), dl,
8393             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8394       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8395       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8396   } else if (MI->getOpcode() == PPC::ReadTB) {
8397     // To read the 64-bit time-base register on a 32-bit target, we read the
8398     // two halves. Should the counter have wrapped while it was being read, we
8399     // need to try again.
8400     // ...
8401     // readLoop:
8402     // mfspr Rx,TBU # load from TBU
8403     // mfspr Ry,TB  # load from TB
8404     // mfspr Rz,TBU # load from TBU
8405     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8406     // bne readLoop   # branch if they're not equal
8407     // ...
8408
8409     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8410     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8411     DebugLoc dl = MI->getDebugLoc();
8412     F->insert(It, readMBB);
8413     F->insert(It, sinkMBB);
8414
8415     // Transfer the remainder of BB and its successor edges to sinkMBB.
8416     sinkMBB->splice(sinkMBB->begin(), BB,
8417                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8418     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8419
8420     BB->addSuccessor(readMBB);
8421     BB = readMBB;
8422
8423     MachineRegisterInfo &RegInfo = F->getRegInfo();
8424     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8425     unsigned LoReg = MI->getOperand(0).getReg();
8426     unsigned HiReg = MI->getOperand(1).getReg();
8427
8428     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8429     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8430     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8431
8432     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8433
8434     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8435       .addReg(HiReg).addReg(ReadAgainReg);
8436     BuildMI(BB, dl, TII->get(PPC::BCC))
8437       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8438
8439     BB->addSuccessor(readMBB);
8440     BB->addSuccessor(sinkMBB);
8441   }
8442   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8443     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8444   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8445     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8446   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8447     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8448   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8449     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8450
8451   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8452     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8453   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8454     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8455   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8456     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8457   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8458     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8459
8460   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8461     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8462   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8463     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8464   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8465     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8466   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8467     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8468
8469   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8470     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8471   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8472     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8473   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8474     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8475   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8476     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8477
8478   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8479     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8480   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8481     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8482   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8483     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8484   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8485     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8486
8487   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8488     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8489   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8490     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8491   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8492     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8493   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8494     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8495
8496   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8497     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8498   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8499     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8500   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8501     BB = EmitAtomicBinary(MI, BB, 4, 0);
8502   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8503     BB = EmitAtomicBinary(MI, BB, 8, 0);
8504
8505   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8506            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8507            (Subtarget.hasPartwordAtomics() &&
8508             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8509            (Subtarget.hasPartwordAtomics() &&
8510             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8511     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8512
8513     auto LoadMnemonic = PPC::LDARX;
8514     auto StoreMnemonic = PPC::STDCX;
8515     switch(MI->getOpcode()) {
8516     default:
8517       llvm_unreachable("Compare and swap of unknown size");
8518     case PPC::ATOMIC_CMP_SWAP_I8:
8519       LoadMnemonic = PPC::LBARX;
8520       StoreMnemonic = PPC::STBCX;
8521       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8522       break;
8523     case PPC::ATOMIC_CMP_SWAP_I16:
8524       LoadMnemonic = PPC::LHARX;
8525       StoreMnemonic = PPC::STHCX;
8526       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8527       break;
8528     case PPC::ATOMIC_CMP_SWAP_I32:
8529       LoadMnemonic = PPC::LWARX;
8530       StoreMnemonic = PPC::STWCX;
8531       break;
8532     case PPC::ATOMIC_CMP_SWAP_I64:
8533       LoadMnemonic = PPC::LDARX;
8534       StoreMnemonic = PPC::STDCX;
8535       break;
8536     }
8537     unsigned dest   = MI->getOperand(0).getReg();
8538     unsigned ptrA   = MI->getOperand(1).getReg();
8539     unsigned ptrB   = MI->getOperand(2).getReg();
8540     unsigned oldval = MI->getOperand(3).getReg();
8541     unsigned newval = MI->getOperand(4).getReg();
8542     DebugLoc dl     = MI->getDebugLoc();
8543
8544     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8545     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8546     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8547     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8548     F->insert(It, loop1MBB);
8549     F->insert(It, loop2MBB);
8550     F->insert(It, midMBB);
8551     F->insert(It, exitMBB);
8552     exitMBB->splice(exitMBB->begin(), BB,
8553                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8554     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8555
8556     //  thisMBB:
8557     //   ...
8558     //   fallthrough --> loopMBB
8559     BB->addSuccessor(loop1MBB);
8560
8561     // loop1MBB:
8562     //   l[bhwd]arx dest, ptr
8563     //   cmp[wd] dest, oldval
8564     //   bne- midMBB
8565     // loop2MBB:
8566     //   st[bhwd]cx. newval, ptr
8567     //   bne- loopMBB
8568     //   b exitBB
8569     // midMBB:
8570     //   st[bhwd]cx. dest, ptr
8571     // exitBB:
8572     BB = loop1MBB;
8573     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8574       .addReg(ptrA).addReg(ptrB);
8575     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8576       .addReg(oldval).addReg(dest);
8577     BuildMI(BB, dl, TII->get(PPC::BCC))
8578       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8579     BB->addSuccessor(loop2MBB);
8580     BB->addSuccessor(midMBB);
8581
8582     BB = loop2MBB;
8583     BuildMI(BB, dl, TII->get(StoreMnemonic))
8584       .addReg(newval).addReg(ptrA).addReg(ptrB);
8585     BuildMI(BB, dl, TII->get(PPC::BCC))
8586       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8587     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8588     BB->addSuccessor(loop1MBB);
8589     BB->addSuccessor(exitMBB);
8590
8591     BB = midMBB;
8592     BuildMI(BB, dl, TII->get(StoreMnemonic))
8593       .addReg(dest).addReg(ptrA).addReg(ptrB);
8594     BB->addSuccessor(exitMBB);
8595
8596     //  exitMBB:
8597     //   ...
8598     BB = exitMBB;
8599   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8600              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8601     // We must use 64-bit registers for addresses when targeting 64-bit,
8602     // since we're actually doing arithmetic on them.  Other registers
8603     // can be 32-bit.
8604     bool is64bit = Subtarget.isPPC64();
8605     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8606
8607     unsigned dest   = MI->getOperand(0).getReg();
8608     unsigned ptrA   = MI->getOperand(1).getReg();
8609     unsigned ptrB   = MI->getOperand(2).getReg();
8610     unsigned oldval = MI->getOperand(3).getReg();
8611     unsigned newval = MI->getOperand(4).getReg();
8612     DebugLoc dl     = MI->getDebugLoc();
8613
8614     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8615     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8616     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8617     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8618     F->insert(It, loop1MBB);
8619     F->insert(It, loop2MBB);
8620     F->insert(It, midMBB);
8621     F->insert(It, exitMBB);
8622     exitMBB->splice(exitMBB->begin(), BB,
8623                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8624     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8625
8626     MachineRegisterInfo &RegInfo = F->getRegInfo();
8627     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8628                                             : &PPC::GPRCRegClass;
8629     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8630     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8631     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8632     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8633     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8634     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8635     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8636     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8637     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8638     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8639     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8640     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8641     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8642     unsigned Ptr1Reg;
8643     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8644     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8645     //  thisMBB:
8646     //   ...
8647     //   fallthrough --> loopMBB
8648     BB->addSuccessor(loop1MBB);
8649
8650     // The 4-byte load must be aligned, while a char or short may be
8651     // anywhere in the word.  Hence all this nasty bookkeeping code.
8652     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8653     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8654     //   xori shift, shift1, 24 [16]
8655     //   rlwinm ptr, ptr1, 0, 0, 29
8656     //   slw newval2, newval, shift
8657     //   slw oldval2, oldval,shift
8658     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8659     //   slw mask, mask2, shift
8660     //   and newval3, newval2, mask
8661     //   and oldval3, oldval2, mask
8662     // loop1MBB:
8663     //   lwarx tmpDest, ptr
8664     //   and tmp, tmpDest, mask
8665     //   cmpw tmp, oldval3
8666     //   bne- midMBB
8667     // loop2MBB:
8668     //   andc tmp2, tmpDest, mask
8669     //   or tmp4, tmp2, newval3
8670     //   stwcx. tmp4, ptr
8671     //   bne- loop1MBB
8672     //   b exitBB
8673     // midMBB:
8674     //   stwcx. tmpDest, ptr
8675     // exitBB:
8676     //   srw dest, tmpDest, shift
8677     if (ptrA != ZeroReg) {
8678       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8679       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8680         .addReg(ptrA).addReg(ptrB);
8681     } else {
8682       Ptr1Reg = ptrB;
8683     }
8684     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8685         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8686     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8687         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8688     if (is64bit)
8689       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8690         .addReg(Ptr1Reg).addImm(0).addImm(61);
8691     else
8692       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8693         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8694     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8695         .addReg(newval).addReg(ShiftReg);
8696     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8697         .addReg(oldval).addReg(ShiftReg);
8698     if (is8bit)
8699       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8700     else {
8701       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8702       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8703         .addReg(Mask3Reg).addImm(65535);
8704     }
8705     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8706         .addReg(Mask2Reg).addReg(ShiftReg);
8707     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8708         .addReg(NewVal2Reg).addReg(MaskReg);
8709     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8710         .addReg(OldVal2Reg).addReg(MaskReg);
8711
8712     BB = loop1MBB;
8713     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8714         .addReg(ZeroReg).addReg(PtrReg);
8715     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8716         .addReg(TmpDestReg).addReg(MaskReg);
8717     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8718         .addReg(TmpReg).addReg(OldVal3Reg);
8719     BuildMI(BB, dl, TII->get(PPC::BCC))
8720         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8721     BB->addSuccessor(loop2MBB);
8722     BB->addSuccessor(midMBB);
8723
8724     BB = loop2MBB;
8725     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8726         .addReg(TmpDestReg).addReg(MaskReg);
8727     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8728         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8729     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8730         .addReg(ZeroReg).addReg(PtrReg);
8731     BuildMI(BB, dl, TII->get(PPC::BCC))
8732       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8733     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8734     BB->addSuccessor(loop1MBB);
8735     BB->addSuccessor(exitMBB);
8736
8737     BB = midMBB;
8738     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8739       .addReg(ZeroReg).addReg(PtrReg);
8740     BB->addSuccessor(exitMBB);
8741
8742     //  exitMBB:
8743     //   ...
8744     BB = exitMBB;
8745     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8746       .addReg(ShiftReg);
8747   } else if (MI->getOpcode() == PPC::FADDrtz) {
8748     // This pseudo performs an FADD with rounding mode temporarily forced
8749     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8750     // is not modeled at the SelectionDAG level.
8751     unsigned Dest = MI->getOperand(0).getReg();
8752     unsigned Src1 = MI->getOperand(1).getReg();
8753     unsigned Src2 = MI->getOperand(2).getReg();
8754     DebugLoc dl   = MI->getDebugLoc();
8755
8756     MachineRegisterInfo &RegInfo = F->getRegInfo();
8757     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8758
8759     // Save FPSCR value.
8760     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8761
8762     // Set rounding mode to round-to-zero.
8763     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8764     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8765
8766     // Perform addition.
8767     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8768
8769     // Restore FPSCR value.
8770     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8771   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8772              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8773              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8774              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8775     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8776                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8777                       PPC::ANDIo8 : PPC::ANDIo;
8778     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8779                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8780
8781     MachineRegisterInfo &RegInfo = F->getRegInfo();
8782     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8783                                                   &PPC::GPRCRegClass :
8784                                                   &PPC::G8RCRegClass);
8785
8786     DebugLoc dl   = MI->getDebugLoc();
8787     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8788       .addReg(MI->getOperand(1).getReg()).addImm(1);
8789     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8790             MI->getOperand(0).getReg())
8791       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8792   } else {
8793     llvm_unreachable("Unexpected instr type to insert");
8794   }
8795
8796   MI->eraseFromParent();   // The pseudo instruction is gone now.
8797   return BB;
8798 }
8799
8800 //===----------------------------------------------------------------------===//
8801 // Target Optimization Hooks
8802 //===----------------------------------------------------------------------===//
8803
8804 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8805                                             DAGCombinerInfo &DCI,
8806                                             unsigned &RefinementSteps,
8807                                             bool &UseOneConstNR) const {
8808   EVT VT = Operand.getValueType();
8809   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8810       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8811       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8812       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8813       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8814       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8815     // Convergence is quadratic, so we essentially double the number of digits
8816     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8817     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8818     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8819     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8820     if (VT.getScalarType() == MVT::f64)
8821       ++RefinementSteps;
8822     UseOneConstNR = true;
8823     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8824   }
8825   return SDValue();
8826 }
8827
8828 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8829                                             DAGCombinerInfo &DCI,
8830                                             unsigned &RefinementSteps) const {
8831   EVT VT = Operand.getValueType();
8832   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8833       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8834       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8835       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8836       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8837       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8838     // Convergence is quadratic, so we essentially double the number of digits
8839     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8840     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8841     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8842     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8843     if (VT.getScalarType() == MVT::f64)
8844       ++RefinementSteps;
8845     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8846   }
8847   return SDValue();
8848 }
8849
8850 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8851   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8852   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8853   // enabled for division), this functionality is redundant with the default
8854   // combiner logic (once the division -> reciprocal/multiply transformation
8855   // has taken place). As a result, this matters more for older cores than for
8856   // newer ones.
8857
8858   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8859   // reciprocal if there are two or more FDIVs (for embedded cores with only
8860   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8861   switch (Subtarget.getDarwinDirective()) {
8862   default:
8863     return NumUsers > 2;
8864   case PPC::DIR_440:
8865   case PPC::DIR_A2:
8866   case PPC::DIR_E500mc:
8867   case PPC::DIR_E5500:
8868     return NumUsers > 1;
8869   }
8870 }
8871
8872 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8873                             unsigned Bytes, int Dist,
8874                             SelectionDAG &DAG) {
8875   if (VT.getSizeInBits() / 8 != Bytes)
8876     return false;
8877
8878   SDValue BaseLoc = Base->getBasePtr();
8879   if (Loc.getOpcode() == ISD::FrameIndex) {
8880     if (BaseLoc.getOpcode() != ISD::FrameIndex)
8881       return false;
8882     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8883     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
8884     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8885     int FS  = MFI->getObjectSize(FI);
8886     int BFS = MFI->getObjectSize(BFI);
8887     if (FS != BFS || FS != (int)Bytes) return false;
8888     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8889   }
8890
8891   // Handle X+C
8892   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8893       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8894     return true;
8895
8896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8897   const GlobalValue *GV1 = nullptr;
8898   const GlobalValue *GV2 = nullptr;
8899   int64_t Offset1 = 0;
8900   int64_t Offset2 = 0;
8901   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8902   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8903   if (isGA1 && isGA2 && GV1 == GV2)
8904     return Offset1 == (Offset2 + Dist*Bytes);
8905   return false;
8906 }
8907
8908 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8909 // not enforce equality of the chain operands.
8910 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8911                             unsigned Bytes, int Dist,
8912                             SelectionDAG &DAG) {
8913   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8914     EVT VT = LS->getMemoryVT();
8915     SDValue Loc = LS->getBasePtr();
8916     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8917   }
8918
8919   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8920     EVT VT;
8921     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8922     default: return false;
8923     case Intrinsic::ppc_qpx_qvlfd:
8924     case Intrinsic::ppc_qpx_qvlfda:
8925       VT = MVT::v4f64;
8926       break;
8927     case Intrinsic::ppc_qpx_qvlfs:
8928     case Intrinsic::ppc_qpx_qvlfsa:
8929       VT = MVT::v4f32;
8930       break;
8931     case Intrinsic::ppc_qpx_qvlfcd:
8932     case Intrinsic::ppc_qpx_qvlfcda:
8933       VT = MVT::v2f64;
8934       break;
8935     case Intrinsic::ppc_qpx_qvlfcs:
8936     case Intrinsic::ppc_qpx_qvlfcsa:
8937       VT = MVT::v2f32;
8938       break;
8939     case Intrinsic::ppc_qpx_qvlfiwa:
8940     case Intrinsic::ppc_qpx_qvlfiwz:
8941     case Intrinsic::ppc_altivec_lvx:
8942     case Intrinsic::ppc_altivec_lvxl:
8943     case Intrinsic::ppc_vsx_lxvw4x:
8944       VT = MVT::v4i32;
8945       break;
8946     case Intrinsic::ppc_vsx_lxvd2x:
8947       VT = MVT::v2f64;
8948       break;
8949     case Intrinsic::ppc_altivec_lvebx:
8950       VT = MVT::i8;
8951       break;
8952     case Intrinsic::ppc_altivec_lvehx:
8953       VT = MVT::i16;
8954       break;
8955     case Intrinsic::ppc_altivec_lvewx:
8956       VT = MVT::i32;
8957       break;
8958     }
8959
8960     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8961   }
8962
8963   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8964     EVT VT;
8965     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8966     default: return false;
8967     case Intrinsic::ppc_qpx_qvstfd:
8968     case Intrinsic::ppc_qpx_qvstfda:
8969       VT = MVT::v4f64;
8970       break;
8971     case Intrinsic::ppc_qpx_qvstfs:
8972     case Intrinsic::ppc_qpx_qvstfsa:
8973       VT = MVT::v4f32;
8974       break;
8975     case Intrinsic::ppc_qpx_qvstfcd:
8976     case Intrinsic::ppc_qpx_qvstfcda:
8977       VT = MVT::v2f64;
8978       break;
8979     case Intrinsic::ppc_qpx_qvstfcs:
8980     case Intrinsic::ppc_qpx_qvstfcsa:
8981       VT = MVT::v2f32;
8982       break;
8983     case Intrinsic::ppc_qpx_qvstfiw:
8984     case Intrinsic::ppc_qpx_qvstfiwa:
8985     case Intrinsic::ppc_altivec_stvx:
8986     case Intrinsic::ppc_altivec_stvxl:
8987     case Intrinsic::ppc_vsx_stxvw4x:
8988       VT = MVT::v4i32;
8989       break;
8990     case Intrinsic::ppc_vsx_stxvd2x:
8991       VT = MVT::v2f64;
8992       break;
8993     case Intrinsic::ppc_altivec_stvebx:
8994       VT = MVT::i8;
8995       break;
8996     case Intrinsic::ppc_altivec_stvehx:
8997       VT = MVT::i16;
8998       break;
8999     case Intrinsic::ppc_altivec_stvewx:
9000       VT = MVT::i32;
9001       break;
9002     }
9003
9004     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9005   }
9006
9007   return false;
9008 }
9009
9010 // Return true is there is a nearyby consecutive load to the one provided
9011 // (regardless of alignment). We search up and down the chain, looking though
9012 // token factors and other loads (but nothing else). As a result, a true result
9013 // indicates that it is safe to create a new consecutive load adjacent to the
9014 // load provided.
9015 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9016   SDValue Chain = LD->getChain();
9017   EVT VT = LD->getMemoryVT();
9018
9019   SmallSet<SDNode *, 16> LoadRoots;
9020   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9021   SmallSet<SDNode *, 16> Visited;
9022
9023   // First, search up the chain, branching to follow all token-factor operands.
9024   // If we find a consecutive load, then we're done, otherwise, record all
9025   // nodes just above the top-level loads and token factors.
9026   while (!Queue.empty()) {
9027     SDNode *ChainNext = Queue.pop_back_val();
9028     if (!Visited.insert(ChainNext).second)
9029       continue;
9030
9031     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9032       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9033         return true;
9034
9035       if (!Visited.count(ChainLD->getChain().getNode()))
9036         Queue.push_back(ChainLD->getChain().getNode());
9037     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9038       for (const SDUse &O : ChainNext->ops())
9039         if (!Visited.count(O.getNode()))
9040           Queue.push_back(O.getNode());
9041     } else
9042       LoadRoots.insert(ChainNext);
9043   }
9044
9045   // Second, search down the chain, starting from the top-level nodes recorded
9046   // in the first phase. These top-level nodes are the nodes just above all
9047   // loads and token factors. Starting with their uses, recursively look though
9048   // all loads (just the chain uses) and token factors to find a consecutive
9049   // load.
9050   Visited.clear();
9051   Queue.clear();
9052
9053   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9054        IE = LoadRoots.end(); I != IE; ++I) {
9055     Queue.push_back(*I);
9056        
9057     while (!Queue.empty()) {
9058       SDNode *LoadRoot = Queue.pop_back_val();
9059       if (!Visited.insert(LoadRoot).second)
9060         continue;
9061
9062       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9063         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9064           return true;
9065
9066       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9067            UE = LoadRoot->use_end(); UI != UE; ++UI)
9068         if (((isa<MemSDNode>(*UI) &&
9069             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9070             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9071           Queue.push_back(*UI);
9072     }
9073   }
9074
9075   return false;
9076 }
9077
9078 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9079                                                   DAGCombinerInfo &DCI) const {
9080   SelectionDAG &DAG = DCI.DAG;
9081   SDLoc dl(N);
9082
9083   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9084   // If we're tracking CR bits, we need to be careful that we don't have:
9085   //   trunc(binary-ops(zext(x), zext(y)))
9086   // or
9087   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9088   // such that we're unnecessarily moving things into GPRs when it would be
9089   // better to keep them in CR bits.
9090
9091   // Note that trunc here can be an actual i1 trunc, or can be the effective
9092   // truncation that comes from a setcc or select_cc.
9093   if (N->getOpcode() == ISD::TRUNCATE &&
9094       N->getValueType(0) != MVT::i1)
9095     return SDValue();
9096
9097   if (N->getOperand(0).getValueType() != MVT::i32 &&
9098       N->getOperand(0).getValueType() != MVT::i64)
9099     return SDValue();
9100
9101   if (N->getOpcode() == ISD::SETCC ||
9102       N->getOpcode() == ISD::SELECT_CC) {
9103     // If we're looking at a comparison, then we need to make sure that the
9104     // high bits (all except for the first) don't matter the result.
9105     ISD::CondCode CC =
9106       cast<CondCodeSDNode>(N->getOperand(
9107         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9108     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9109
9110     if (ISD::isSignedIntSetCC(CC)) {
9111       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9112           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9113         return SDValue();
9114     } else if (ISD::isUnsignedIntSetCC(CC)) {
9115       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9116                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9117           !DAG.MaskedValueIsZero(N->getOperand(1),
9118                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9119         return SDValue();
9120     } else {
9121       // This is neither a signed nor an unsigned comparison, just make sure
9122       // that the high bits are equal.
9123       APInt Op1Zero, Op1One;
9124       APInt Op2Zero, Op2One;
9125       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9126       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9127
9128       // We don't really care about what is known about the first bit (if
9129       // anything), so clear it in all masks prior to comparing them.
9130       Op1Zero.clearBit(0); Op1One.clearBit(0);
9131       Op2Zero.clearBit(0); Op2One.clearBit(0);
9132
9133       if (Op1Zero != Op2Zero || Op1One != Op2One)
9134         return SDValue();
9135     }
9136   }
9137
9138   // We now know that the higher-order bits are irrelevant, we just need to
9139   // make sure that all of the intermediate operations are bit operations, and
9140   // all inputs are extensions.
9141   if (N->getOperand(0).getOpcode() != ISD::AND &&
9142       N->getOperand(0).getOpcode() != ISD::OR  &&
9143       N->getOperand(0).getOpcode() != ISD::XOR &&
9144       N->getOperand(0).getOpcode() != ISD::SELECT &&
9145       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9146       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9147       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9148       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9149       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9150     return SDValue();
9151
9152   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9153       N->getOperand(1).getOpcode() != ISD::AND &&
9154       N->getOperand(1).getOpcode() != ISD::OR  &&
9155       N->getOperand(1).getOpcode() != ISD::XOR &&
9156       N->getOperand(1).getOpcode() != ISD::SELECT &&
9157       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9158       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9159       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9160       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9161       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9162     return SDValue();
9163
9164   SmallVector<SDValue, 4> Inputs;
9165   SmallVector<SDValue, 8> BinOps, PromOps;
9166   SmallPtrSet<SDNode *, 16> Visited;
9167
9168   for (unsigned i = 0; i < 2; ++i) {
9169     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9170           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9171           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9172           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9173         isa<ConstantSDNode>(N->getOperand(i)))
9174       Inputs.push_back(N->getOperand(i));
9175     else
9176       BinOps.push_back(N->getOperand(i));
9177
9178     if (N->getOpcode() == ISD::TRUNCATE)
9179       break;
9180   }
9181
9182   // Visit all inputs, collect all binary operations (and, or, xor and
9183   // select) that are all fed by extensions. 
9184   while (!BinOps.empty()) {
9185     SDValue BinOp = BinOps.back();
9186     BinOps.pop_back();
9187
9188     if (!Visited.insert(BinOp.getNode()).second)
9189       continue;
9190
9191     PromOps.push_back(BinOp);
9192
9193     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9194       // The condition of the select is not promoted.
9195       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9196         continue;
9197       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9198         continue;
9199
9200       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9201             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9202             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9203            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9204           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9205         Inputs.push_back(BinOp.getOperand(i)); 
9206       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9207                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9208                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9209                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9210                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9211                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9212                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9213                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9214                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9215         BinOps.push_back(BinOp.getOperand(i));
9216       } else {
9217         // We have an input that is not an extension or another binary
9218         // operation; we'll abort this transformation.
9219         return SDValue();
9220       }
9221     }
9222   }
9223
9224   // Make sure that this is a self-contained cluster of operations (which
9225   // is not quite the same thing as saying that everything has only one
9226   // use).
9227   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9228     if (isa<ConstantSDNode>(Inputs[i]))
9229       continue;
9230
9231     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9232                               UE = Inputs[i].getNode()->use_end();
9233          UI != UE; ++UI) {
9234       SDNode *User = *UI;
9235       if (User != N && !Visited.count(User))
9236         return SDValue();
9237
9238       // Make sure that we're not going to promote the non-output-value
9239       // operand(s) or SELECT or SELECT_CC.
9240       // FIXME: Although we could sometimes handle this, and it does occur in
9241       // practice that one of the condition inputs to the select is also one of
9242       // the outputs, we currently can't deal with this.
9243       if (User->getOpcode() == ISD::SELECT) {
9244         if (User->getOperand(0) == Inputs[i])
9245           return SDValue();
9246       } else if (User->getOpcode() == ISD::SELECT_CC) {
9247         if (User->getOperand(0) == Inputs[i] ||
9248             User->getOperand(1) == Inputs[i])
9249           return SDValue();
9250       }
9251     }
9252   }
9253
9254   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9255     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9256                               UE = PromOps[i].getNode()->use_end();
9257          UI != UE; ++UI) {
9258       SDNode *User = *UI;
9259       if (User != N && !Visited.count(User))
9260         return SDValue();
9261
9262       // Make sure that we're not going to promote the non-output-value
9263       // operand(s) or SELECT or SELECT_CC.
9264       // FIXME: Although we could sometimes handle this, and it does occur in
9265       // practice that one of the condition inputs to the select is also one of
9266       // the outputs, we currently can't deal with this.
9267       if (User->getOpcode() == ISD::SELECT) {
9268         if (User->getOperand(0) == PromOps[i])
9269           return SDValue();
9270       } else if (User->getOpcode() == ISD::SELECT_CC) {
9271         if (User->getOperand(0) == PromOps[i] ||
9272             User->getOperand(1) == PromOps[i])
9273           return SDValue();
9274       }
9275     }
9276   }
9277
9278   // Replace all inputs with the extension operand.
9279   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9280     // Constants may have users outside the cluster of to-be-promoted nodes,
9281     // and so we need to replace those as we do the promotions.
9282     if (isa<ConstantSDNode>(Inputs[i]))
9283       continue;
9284     else
9285       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9286   }
9287
9288   // Replace all operations (these are all the same, but have a different
9289   // (i1) return type). DAG.getNode will validate that the types of
9290   // a binary operator match, so go through the list in reverse so that
9291   // we've likely promoted both operands first. Any intermediate truncations or
9292   // extensions disappear.
9293   while (!PromOps.empty()) {
9294     SDValue PromOp = PromOps.back();
9295     PromOps.pop_back();
9296
9297     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9298         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9299         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9300         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9301       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9302           PromOp.getOperand(0).getValueType() != MVT::i1) {
9303         // The operand is not yet ready (see comment below).
9304         PromOps.insert(PromOps.begin(), PromOp);
9305         continue;
9306       }
9307
9308       SDValue RepValue = PromOp.getOperand(0);
9309       if (isa<ConstantSDNode>(RepValue))
9310         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9311
9312       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9313       continue;
9314     }
9315
9316     unsigned C;
9317     switch (PromOp.getOpcode()) {
9318     default:             C = 0; break;
9319     case ISD::SELECT:    C = 1; break;
9320     case ISD::SELECT_CC: C = 2; break;
9321     }
9322
9323     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9324          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9325         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9326          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9327       // The to-be-promoted operands of this node have not yet been
9328       // promoted (this should be rare because we're going through the
9329       // list backward, but if one of the operands has several users in
9330       // this cluster of to-be-promoted nodes, it is possible).
9331       PromOps.insert(PromOps.begin(), PromOp);
9332       continue;
9333     }
9334
9335     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9336                                 PromOp.getNode()->op_end());
9337
9338     // If there are any constant inputs, make sure they're replaced now.
9339     for (unsigned i = 0; i < 2; ++i)
9340       if (isa<ConstantSDNode>(Ops[C+i]))
9341         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9342
9343     DAG.ReplaceAllUsesOfValueWith(PromOp,
9344       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9345   }
9346
9347   // Now we're left with the initial truncation itself.
9348   if (N->getOpcode() == ISD::TRUNCATE)
9349     return N->getOperand(0);
9350
9351   // Otherwise, this is a comparison. The operands to be compared have just
9352   // changed type (to i1), but everything else is the same.
9353   return SDValue(N, 0);
9354 }
9355
9356 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9357                                                   DAGCombinerInfo &DCI) const {
9358   SelectionDAG &DAG = DCI.DAG;
9359   SDLoc dl(N);
9360
9361   // If we're tracking CR bits, we need to be careful that we don't have:
9362   //   zext(binary-ops(trunc(x), trunc(y)))
9363   // or
9364   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9365   // such that we're unnecessarily moving things into CR bits that can more
9366   // efficiently stay in GPRs. Note that if we're not certain that the high
9367   // bits are set as required by the final extension, we still may need to do
9368   // some masking to get the proper behavior.
9369
9370   // This same functionality is important on PPC64 when dealing with
9371   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9372   // the return values of functions. Because it is so similar, it is handled
9373   // here as well.
9374
9375   if (N->getValueType(0) != MVT::i32 &&
9376       N->getValueType(0) != MVT::i64)
9377     return SDValue();
9378
9379   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9380         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9381     return SDValue();
9382
9383   if (N->getOperand(0).getOpcode() != ISD::AND &&
9384       N->getOperand(0).getOpcode() != ISD::OR  &&
9385       N->getOperand(0).getOpcode() != ISD::XOR &&
9386       N->getOperand(0).getOpcode() != ISD::SELECT &&
9387       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9388     return SDValue();
9389
9390   SmallVector<SDValue, 4> Inputs;
9391   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9392   SmallPtrSet<SDNode *, 16> Visited;
9393
9394   // Visit all inputs, collect all binary operations (and, or, xor and
9395   // select) that are all fed by truncations. 
9396   while (!BinOps.empty()) {
9397     SDValue BinOp = BinOps.back();
9398     BinOps.pop_back();
9399
9400     if (!Visited.insert(BinOp.getNode()).second)
9401       continue;
9402
9403     PromOps.push_back(BinOp);
9404
9405     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9406       // The condition of the select is not promoted.
9407       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9408         continue;
9409       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9410         continue;
9411
9412       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9413           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9414         Inputs.push_back(BinOp.getOperand(i)); 
9415       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9416                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9417                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9418                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9419                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9420         BinOps.push_back(BinOp.getOperand(i));
9421       } else {
9422         // We have an input that is not a truncation or another binary
9423         // operation; we'll abort this transformation.
9424         return SDValue();
9425       }
9426     }
9427   }
9428
9429   // The operands of a select that must be truncated when the select is
9430   // promoted because the operand is actually part of the to-be-promoted set.
9431   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9432
9433   // Make sure that this is a self-contained cluster of operations (which
9434   // is not quite the same thing as saying that everything has only one
9435   // use).
9436   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9437     if (isa<ConstantSDNode>(Inputs[i]))
9438       continue;
9439
9440     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9441                               UE = Inputs[i].getNode()->use_end();
9442          UI != UE; ++UI) {
9443       SDNode *User = *UI;
9444       if (User != N && !Visited.count(User))
9445         return SDValue();
9446
9447       // If we're going to promote the non-output-value operand(s) or SELECT or
9448       // SELECT_CC, record them for truncation.
9449       if (User->getOpcode() == ISD::SELECT) {
9450         if (User->getOperand(0) == Inputs[i])
9451           SelectTruncOp[0].insert(std::make_pair(User,
9452                                     User->getOperand(0).getValueType()));
9453       } else if (User->getOpcode() == ISD::SELECT_CC) {
9454         if (User->getOperand(0) == Inputs[i])
9455           SelectTruncOp[0].insert(std::make_pair(User,
9456                                     User->getOperand(0).getValueType()));
9457         if (User->getOperand(1) == Inputs[i])
9458           SelectTruncOp[1].insert(std::make_pair(User,
9459                                     User->getOperand(1).getValueType()));
9460       }
9461     }
9462   }
9463
9464   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9465     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9466                               UE = PromOps[i].getNode()->use_end();
9467          UI != UE; ++UI) {
9468       SDNode *User = *UI;
9469       if (User != N && !Visited.count(User))
9470         return SDValue();
9471
9472       // If we're going to promote the non-output-value operand(s) or SELECT or
9473       // SELECT_CC, record them for truncation.
9474       if (User->getOpcode() == ISD::SELECT) {
9475         if (User->getOperand(0) == PromOps[i])
9476           SelectTruncOp[0].insert(std::make_pair(User,
9477                                     User->getOperand(0).getValueType()));
9478       } else if (User->getOpcode() == ISD::SELECT_CC) {
9479         if (User->getOperand(0) == PromOps[i])
9480           SelectTruncOp[0].insert(std::make_pair(User,
9481                                     User->getOperand(0).getValueType()));
9482         if (User->getOperand(1) == PromOps[i])
9483           SelectTruncOp[1].insert(std::make_pair(User,
9484                                     User->getOperand(1).getValueType()));
9485       }
9486     }
9487   }
9488
9489   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9490   bool ReallyNeedsExt = false;
9491   if (N->getOpcode() != ISD::ANY_EXTEND) {
9492     // If all of the inputs are not already sign/zero extended, then
9493     // we'll still need to do that at the end.
9494     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9495       if (isa<ConstantSDNode>(Inputs[i]))
9496         continue;
9497
9498       unsigned OpBits =
9499         Inputs[i].getOperand(0).getValueSizeInBits();
9500       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9501
9502       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9503            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9504                                   APInt::getHighBitsSet(OpBits,
9505                                                         OpBits-PromBits))) ||
9506           (N->getOpcode() == ISD::SIGN_EXTEND &&
9507            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9508              (OpBits-(PromBits-1)))) {
9509         ReallyNeedsExt = true;
9510         break;
9511       }
9512     }
9513   }
9514
9515   // Replace all inputs, either with the truncation operand, or a
9516   // truncation or extension to the final output type.
9517   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9518     // Constant inputs need to be replaced with the to-be-promoted nodes that
9519     // use them because they might have users outside of the cluster of
9520     // promoted nodes.
9521     if (isa<ConstantSDNode>(Inputs[i]))
9522       continue;
9523
9524     SDValue InSrc = Inputs[i].getOperand(0);
9525     if (Inputs[i].getValueType() == N->getValueType(0))
9526       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9527     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9528       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9529         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9530     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9531       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9532         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9533     else
9534       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9535         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9536   }
9537
9538   // Replace all operations (these are all the same, but have a different
9539   // (promoted) return type). DAG.getNode will validate that the types of
9540   // a binary operator match, so go through the list in reverse so that
9541   // we've likely promoted both operands first.
9542   while (!PromOps.empty()) {
9543     SDValue PromOp = PromOps.back();
9544     PromOps.pop_back();
9545
9546     unsigned C;
9547     switch (PromOp.getOpcode()) {
9548     default:             C = 0; break;
9549     case ISD::SELECT:    C = 1; break;
9550     case ISD::SELECT_CC: C = 2; break;
9551     }
9552
9553     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9554          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9555         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9556          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9557       // The to-be-promoted operands of this node have not yet been
9558       // promoted (this should be rare because we're going through the
9559       // list backward, but if one of the operands has several users in
9560       // this cluster of to-be-promoted nodes, it is possible).
9561       PromOps.insert(PromOps.begin(), PromOp);
9562       continue;
9563     }
9564
9565     // For SELECT and SELECT_CC nodes, we do a similar check for any
9566     // to-be-promoted comparison inputs.
9567     if (PromOp.getOpcode() == ISD::SELECT ||
9568         PromOp.getOpcode() == ISD::SELECT_CC) {
9569       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9570            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9571           (SelectTruncOp[1].count(PromOp.getNode()) &&
9572            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9573         PromOps.insert(PromOps.begin(), PromOp);
9574         continue;
9575       }
9576     }
9577
9578     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9579                                 PromOp.getNode()->op_end());
9580
9581     // If this node has constant inputs, then they'll need to be promoted here.
9582     for (unsigned i = 0; i < 2; ++i) {
9583       if (!isa<ConstantSDNode>(Ops[C+i]))
9584         continue;
9585       if (Ops[C+i].getValueType() == N->getValueType(0))
9586         continue;
9587
9588       if (N->getOpcode() == ISD::SIGN_EXTEND)
9589         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9590       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9591         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9592       else
9593         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9594     }
9595
9596     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9597     // truncate them again to the original value type.
9598     if (PromOp.getOpcode() == ISD::SELECT ||
9599         PromOp.getOpcode() == ISD::SELECT_CC) {
9600       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9601       if (SI0 != SelectTruncOp[0].end())
9602         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9603       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9604       if (SI1 != SelectTruncOp[1].end())
9605         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9606     }
9607
9608     DAG.ReplaceAllUsesOfValueWith(PromOp,
9609       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9610   }
9611
9612   // Now we're left with the initial extension itself.
9613   if (!ReallyNeedsExt)
9614     return N->getOperand(0);
9615
9616   // To zero extend, just mask off everything except for the first bit (in the
9617   // i1 case).
9618   if (N->getOpcode() == ISD::ZERO_EXTEND)
9619     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9620                        DAG.getConstant(APInt::getLowBitsSet(
9621                                          N->getValueSizeInBits(0), PromBits),
9622                                        N->getValueType(0)));
9623
9624   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9625          "Invalid extension type");
9626   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9627   SDValue ShiftCst =
9628     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9629   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9630                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9631                                  N->getOperand(0), ShiftCst), ShiftCst);
9632 }
9633
9634 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9635                                               DAGCombinerInfo &DCI) const {
9636   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9637           N->getOpcode() == ISD::UINT_TO_FP) &&
9638          "Need an int -> FP conversion node here");
9639
9640   if (!Subtarget.has64BitSupport())
9641     return SDValue();
9642
9643   SelectionDAG &DAG = DCI.DAG;
9644   SDLoc dl(N);
9645   SDValue Op(N, 0);
9646
9647   // Don't handle ppc_fp128 here or i1 conversions.
9648   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9649     return SDValue();
9650   if (Op.getOperand(0).getValueType() == MVT::i1)
9651     return SDValue();
9652
9653   // For i32 intermediate values, unfortunately, the conversion functions
9654   // leave the upper 32 bits of the value are undefined. Within the set of
9655   // scalar instructions, we have no method for zero- or sign-extending the
9656   // value. Thus, we cannot handle i32 intermediate values here.
9657   if (Op.getOperand(0).getValueType() == MVT::i32)
9658     return SDValue();
9659
9660   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9661          "UINT_TO_FP is supported only with FPCVT");
9662
9663   // If we have FCFIDS, then use it when converting to single-precision.
9664   // Otherwise, convert to double-precision and then round.
9665   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9666                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9667                                                             : PPCISD::FCFIDS)
9668                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9669                                                             : PPCISD::FCFID);
9670   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9671                   ? MVT::f32
9672                   : MVT::f64;
9673
9674   // If we're converting from a float, to an int, and back to a float again,
9675   // then we don't need the store/load pair at all.
9676   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9677        Subtarget.hasFPCVT()) ||
9678       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9679     SDValue Src = Op.getOperand(0).getOperand(0);
9680     if (Src.getValueType() == MVT::f32) {
9681       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9682       DCI.AddToWorklist(Src.getNode());
9683     }
9684
9685     unsigned FCTOp =
9686       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9687                                                         PPCISD::FCTIDUZ;
9688
9689     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9690     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9691
9692     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9693       FP = DAG.getNode(ISD::FP_ROUND, dl,
9694                        MVT::f32, FP, DAG.getIntPtrConstant(0));
9695       DCI.AddToWorklist(FP.getNode());
9696     }
9697
9698     return FP;
9699   }
9700
9701   return SDValue();
9702 }
9703
9704 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9705 // builtins) into loads with swaps.
9706 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9707                                               DAGCombinerInfo &DCI) const {
9708   SelectionDAG &DAG = DCI.DAG;
9709   SDLoc dl(N);
9710   SDValue Chain;
9711   SDValue Base;
9712   MachineMemOperand *MMO;
9713
9714   switch (N->getOpcode()) {
9715   default:
9716     llvm_unreachable("Unexpected opcode for little endian VSX load");
9717   case ISD::LOAD: {
9718     LoadSDNode *LD = cast<LoadSDNode>(N);
9719     Chain = LD->getChain();
9720     Base = LD->getBasePtr();
9721     MMO = LD->getMemOperand();
9722     // If the MMO suggests this isn't a load of a full vector, leave
9723     // things alone.  For a built-in, we have to make the change for
9724     // correctness, so if there is a size problem that will be a bug.
9725     if (MMO->getSize() < 16)
9726       return SDValue();
9727     break;
9728   }
9729   case ISD::INTRINSIC_W_CHAIN: {
9730     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9731     Chain = Intrin->getChain();
9732     Base = Intrin->getBasePtr();
9733     MMO = Intrin->getMemOperand();
9734     break;
9735   }
9736   }
9737
9738   MVT VecTy = N->getValueType(0).getSimpleVT();
9739   SDValue LoadOps[] = { Chain, Base };
9740   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9741                                          DAG.getVTList(VecTy, MVT::Other),
9742                                          LoadOps, VecTy, MMO);
9743   DCI.AddToWorklist(Load.getNode());
9744   Chain = Load.getValue(1);
9745   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9746                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9747   DCI.AddToWorklist(Swap.getNode());
9748   return Swap;
9749 }
9750
9751 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9752 // builtins) into stores with swaps.
9753 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9754                                                DAGCombinerInfo &DCI) const {
9755   SelectionDAG &DAG = DCI.DAG;
9756   SDLoc dl(N);
9757   SDValue Chain;
9758   SDValue Base;
9759   unsigned SrcOpnd;
9760   MachineMemOperand *MMO;
9761
9762   switch (N->getOpcode()) {
9763   default:
9764     llvm_unreachable("Unexpected opcode for little endian VSX store");
9765   case ISD::STORE: {
9766     StoreSDNode *ST = cast<StoreSDNode>(N);
9767     Chain = ST->getChain();
9768     Base = ST->getBasePtr();
9769     MMO = ST->getMemOperand();
9770     SrcOpnd = 1;
9771     // If the MMO suggests this isn't a store of a full vector, leave
9772     // things alone.  For a built-in, we have to make the change for
9773     // correctness, so if there is a size problem that will be a bug.
9774     if (MMO->getSize() < 16)
9775       return SDValue();
9776     break;
9777   }
9778   case ISD::INTRINSIC_VOID: {
9779     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9780     Chain = Intrin->getChain();
9781     // Intrin->getBasePtr() oddly does not get what we want.
9782     Base = Intrin->getOperand(3);
9783     MMO = Intrin->getMemOperand();
9784     SrcOpnd = 2;
9785     break;
9786   }
9787   }
9788
9789   SDValue Src = N->getOperand(SrcOpnd);
9790   MVT VecTy = Src.getValueType().getSimpleVT();
9791   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9792                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9793   DCI.AddToWorklist(Swap.getNode());
9794   Chain = Swap.getValue(1);
9795   SDValue StoreOps[] = { Chain, Swap, Base };
9796   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9797                                           DAG.getVTList(MVT::Other),
9798                                           StoreOps, VecTy, MMO);
9799   DCI.AddToWorklist(Store.getNode());
9800   return Store;
9801 }
9802
9803 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9804                                              DAGCombinerInfo &DCI) const {
9805   SelectionDAG &DAG = DCI.DAG;
9806   SDLoc dl(N);
9807   switch (N->getOpcode()) {
9808   default: break;
9809   case PPCISD::SHL:
9810     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9811       if (C->isNullValue())   // 0 << V -> 0.
9812         return N->getOperand(0);
9813     }
9814     break;
9815   case PPCISD::SRL:
9816     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9817       if (C->isNullValue())   // 0 >>u V -> 0.
9818         return N->getOperand(0);
9819     }
9820     break;
9821   case PPCISD::SRA:
9822     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9823       if (C->isNullValue() ||   //  0 >>s V -> 0.
9824           C->isAllOnesValue())    // -1 >>s V -> -1.
9825         return N->getOperand(0);
9826     }
9827     break;
9828   case ISD::SIGN_EXTEND:
9829   case ISD::ZERO_EXTEND:
9830   case ISD::ANY_EXTEND: 
9831     return DAGCombineExtBoolTrunc(N, DCI);
9832   case ISD::TRUNCATE:
9833   case ISD::SETCC:
9834   case ISD::SELECT_CC:
9835     return DAGCombineTruncBoolExt(N, DCI);
9836   case ISD::SINT_TO_FP:
9837   case ISD::UINT_TO_FP:
9838     return combineFPToIntToFP(N, DCI);
9839   case ISD::STORE: {
9840     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9841     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9842         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9843         N->getOperand(1).getValueType() == MVT::i32 &&
9844         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9845       SDValue Val = N->getOperand(1).getOperand(0);
9846       if (Val.getValueType() == MVT::f32) {
9847         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9848         DCI.AddToWorklist(Val.getNode());
9849       }
9850       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9851       DCI.AddToWorklist(Val.getNode());
9852
9853       SDValue Ops[] = {
9854         N->getOperand(0), Val, N->getOperand(2),
9855         DAG.getValueType(N->getOperand(1).getValueType())
9856       };
9857
9858       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9859               DAG.getVTList(MVT::Other), Ops,
9860               cast<StoreSDNode>(N)->getMemoryVT(),
9861               cast<StoreSDNode>(N)->getMemOperand());
9862       DCI.AddToWorklist(Val.getNode());
9863       return Val;
9864     }
9865
9866     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9867     if (cast<StoreSDNode>(N)->isUnindexed() &&
9868         N->getOperand(1).getOpcode() == ISD::BSWAP &&
9869         N->getOperand(1).getNode()->hasOneUse() &&
9870         (N->getOperand(1).getValueType() == MVT::i32 ||
9871          N->getOperand(1).getValueType() == MVT::i16 ||
9872          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9873           N->getOperand(1).getValueType() == MVT::i64))) {
9874       SDValue BSwapOp = N->getOperand(1).getOperand(0);
9875       // Do an any-extend to 32-bits if this is a half-word input.
9876       if (BSwapOp.getValueType() == MVT::i16)
9877         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9878
9879       SDValue Ops[] = {
9880         N->getOperand(0), BSwapOp, N->getOperand(2),
9881         DAG.getValueType(N->getOperand(1).getValueType())
9882       };
9883       return
9884         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9885                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9886                                 cast<StoreSDNode>(N)->getMemOperand());
9887     }
9888
9889     // For little endian, VSX stores require generating xxswapd/lxvd2x.
9890     EVT VT = N->getOperand(1).getValueType();
9891     if (VT.isSimple()) {
9892       MVT StoreVT = VT.getSimpleVT();
9893       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9894           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9895            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9896         return expandVSXStoreForLE(N, DCI);
9897     }
9898     break;
9899   }
9900   case ISD::LOAD: {
9901     LoadSDNode *LD = cast<LoadSDNode>(N);
9902     EVT VT = LD->getValueType(0);
9903
9904     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9905     if (VT.isSimple()) {
9906       MVT LoadVT = VT.getSimpleVT();
9907       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9908           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9909            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9910         return expandVSXLoadForLE(N, DCI);
9911     }
9912
9913     EVT MemVT = LD->getMemoryVT();
9914     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9915     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9916     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9917     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9918     if (LD->isUnindexed() && VT.isVector() &&
9919         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9920           // P8 and later hardware should just use LOAD.
9921           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9922                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9923          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9924           LD->getAlignment() >= ScalarABIAlignment)) &&
9925         LD->getAlignment() < ABIAlignment) {
9926       // This is a type-legal unaligned Altivec or QPX load.
9927       SDValue Chain = LD->getChain();
9928       SDValue Ptr = LD->getBasePtr();
9929       bool isLittleEndian = Subtarget.isLittleEndian();
9930
9931       // This implements the loading of unaligned vectors as described in
9932       // the venerable Apple Velocity Engine overview. Specifically:
9933       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9934       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9935       //
9936       // The general idea is to expand a sequence of one or more unaligned
9937       // loads into an alignment-based permutation-control instruction (lvsl
9938       // or lvsr), a series of regular vector loads (which always truncate
9939       // their input address to an aligned address), and a series of
9940       // permutations.  The results of these permutations are the requested
9941       // loaded values.  The trick is that the last "extra" load is not taken
9942       // from the address you might suspect (sizeof(vector) bytes after the
9943       // last requested load), but rather sizeof(vector) - 1 bytes after the
9944       // last requested vector. The point of this is to avoid a page fault if
9945       // the base address happened to be aligned. This works because if the
9946       // base address is aligned, then adding less than a full vector length
9947       // will cause the last vector in the sequence to be (re)loaded.
9948       // Otherwise, the next vector will be fetched as you might suspect was
9949       // necessary.
9950
9951       // We might be able to reuse the permutation generation from
9952       // a different base address offset from this one by an aligned amount.
9953       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9954       // optimization later.
9955       Intrinsic::ID Intr, IntrLD, IntrPerm;
9956       MVT PermCntlTy, PermTy, LDTy;
9957       if (Subtarget.hasAltivec()) {
9958         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
9959                                  Intrinsic::ppc_altivec_lvsl;
9960         IntrLD = Intrinsic::ppc_altivec_lvx;
9961         IntrPerm = Intrinsic::ppc_altivec_vperm;
9962         PermCntlTy = MVT::v16i8;
9963         PermTy = MVT::v4i32;
9964         LDTy = MVT::v4i32;
9965       } else {
9966         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9967                                        Intrinsic::ppc_qpx_qvlpcls;
9968         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9969                                        Intrinsic::ppc_qpx_qvlfs;
9970         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9971         PermCntlTy = MVT::v4f64;
9972         PermTy = MVT::v4f64;
9973         LDTy = MemVT.getSimpleVT();
9974       }
9975
9976       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9977
9978       // Create the new MMO for the new base load. It is like the original MMO,
9979       // but represents an area in memory almost twice the vector size centered
9980       // on the original address. If the address is unaligned, we might start
9981       // reading up to (sizeof(vector)-1) bytes below the address of the
9982       // original unaligned load.
9983       MachineFunction &MF = DAG.getMachineFunction();
9984       MachineMemOperand *BaseMMO =
9985         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9986                                 2*MemVT.getStoreSize()-1);
9987
9988       // Create the new base load.
9989       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9990       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9991       SDValue BaseLoad =
9992         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9993                                 DAG.getVTList(PermTy, MVT::Other),
9994                                 BaseLoadOps, LDTy, BaseMMO);
9995
9996       // Note that the value of IncOffset (which is provided to the next
9997       // load's pointer info offset value, and thus used to calculate the
9998       // alignment), and the value of IncValue (which is actually used to
9999       // increment the pointer value) are different! This is because we
10000       // require the next load to appear to be aligned, even though it
10001       // is actually offset from the base pointer by a lesser amount.
10002       int IncOffset = VT.getSizeInBits() / 8;
10003       int IncValue = IncOffset;
10004
10005       // Walk (both up and down) the chain looking for another load at the real
10006       // (aligned) offset (the alignment of the other load does not matter in
10007       // this case). If found, then do not use the offset reduction trick, as
10008       // that will prevent the loads from being later combined (as they would
10009       // otherwise be duplicates).
10010       if (!findConsecutiveLoad(LD, DAG))
10011         --IncValue;
10012
10013       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
10014       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10015
10016       MachineMemOperand *ExtraMMO =
10017         MF.getMachineMemOperand(LD->getMemOperand(),
10018                                 1, 2*MemVT.getStoreSize()-1);
10019       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10020       SDValue ExtraLoad =
10021         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10022                                 DAG.getVTList(PermTy, MVT::Other),
10023                                 ExtraLoadOps, LDTy, ExtraMMO);
10024
10025       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10026         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10027
10028       // Because vperm has a big-endian bias, we must reverse the order
10029       // of the input vectors and complement the permute control vector
10030       // when generating little endian code.  We have already handled the
10031       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10032       // and ExtraLoad here.
10033       SDValue Perm;
10034       if (isLittleEndian)
10035         Perm = BuildIntrinsicOp(IntrPerm,
10036                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10037       else
10038         Perm = BuildIntrinsicOp(IntrPerm,
10039                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10040
10041       if (VT != PermTy)
10042         Perm = Subtarget.hasAltivec() ?
10043                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10044                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10045                                DAG.getTargetConstant(1, MVT::i64));
10046                                // second argument is 1 because this rounding
10047                                // is always exact.
10048
10049       // The output of the permutation is our loaded result, the TokenFactor is
10050       // our new chain.
10051       DCI.CombineTo(N, Perm, TF);
10052       return SDValue(N, 0);
10053     }
10054     }
10055     break;
10056     case ISD::INTRINSIC_WO_CHAIN: {
10057       bool isLittleEndian = Subtarget.isLittleEndian();
10058       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10059       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10060                                            : Intrinsic::ppc_altivec_lvsl);
10061       if ((IID == Intr ||
10062            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10063            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10064         N->getOperand(1)->getOpcode() == ISD::ADD) {
10065         SDValue Add = N->getOperand(1);
10066
10067         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10068                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10069
10070         if (DAG.MaskedValueIsZero(
10071                 Add->getOperand(1),
10072                 APInt::getAllOnesValue(Bits /* alignment */)
10073                     .zext(
10074                         Add.getValueType().getScalarType().getSizeInBits()))) {
10075           SDNode *BasePtr = Add->getOperand(0).getNode();
10076           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10077                                     UE = BasePtr->use_end();
10078                UI != UE; ++UI) {
10079             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10080                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10081               // We've found another LVSL/LVSR, and this address is an aligned
10082               // multiple of that one. The results will be the same, so use the
10083               // one we've just found instead.
10084
10085               return SDValue(*UI, 0);
10086             }
10087           }
10088         }
10089
10090         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10091           SDNode *BasePtr = Add->getOperand(0).getNode();
10092           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10093                UE = BasePtr->use_end(); UI != UE; ++UI) {
10094             if (UI->getOpcode() == ISD::ADD &&
10095                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10096                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10097                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10098                 (1ULL << Bits) == 0) {
10099               SDNode *OtherAdd = *UI;
10100               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10101                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10102                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10103                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10104                   return SDValue(*VI, 0);
10105                 }
10106               }
10107             }
10108           }
10109         }
10110       }
10111     }
10112
10113     break;
10114   case ISD::INTRINSIC_W_CHAIN: {
10115     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10116     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10117       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10118       default:
10119         break;
10120       case Intrinsic::ppc_vsx_lxvw4x:
10121       case Intrinsic::ppc_vsx_lxvd2x:
10122         return expandVSXLoadForLE(N, DCI);
10123       }
10124     }
10125     break;
10126   }
10127   case ISD::INTRINSIC_VOID: {
10128     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10129     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10130       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10131       default:
10132         break;
10133       case Intrinsic::ppc_vsx_stxvw4x:
10134       case Intrinsic::ppc_vsx_stxvd2x:
10135         return expandVSXStoreForLE(N, DCI);
10136       }
10137     }
10138     break;
10139   }
10140   case ISD::BSWAP:
10141     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10142     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10143         N->getOperand(0).hasOneUse() &&
10144         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10145          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10146           N->getValueType(0) == MVT::i64))) {
10147       SDValue Load = N->getOperand(0);
10148       LoadSDNode *LD = cast<LoadSDNode>(Load);
10149       // Create the byte-swapping load.
10150       SDValue Ops[] = {
10151         LD->getChain(),    // Chain
10152         LD->getBasePtr(),  // Ptr
10153         DAG.getValueType(N->getValueType(0)) // VT
10154       };
10155       SDValue BSLoad =
10156         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10157                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10158                                               MVT::i64 : MVT::i32, MVT::Other),
10159                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10160
10161       // If this is an i16 load, insert the truncate.
10162       SDValue ResVal = BSLoad;
10163       if (N->getValueType(0) == MVT::i16)
10164         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10165
10166       // First, combine the bswap away.  This makes the value produced by the
10167       // load dead.
10168       DCI.CombineTo(N, ResVal);
10169
10170       // Next, combine the load away, we give it a bogus result value but a real
10171       // chain result.  The result value is dead because the bswap is dead.
10172       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10173
10174       // Return N so it doesn't get rechecked!
10175       return SDValue(N, 0);
10176     }
10177
10178     break;
10179   case PPCISD::VCMP: {
10180     // If a VCMPo node already exists with exactly the same operands as this
10181     // node, use its result instead of this node (VCMPo computes both a CR6 and
10182     // a normal output).
10183     //
10184     if (!N->getOperand(0).hasOneUse() &&
10185         !N->getOperand(1).hasOneUse() &&
10186         !N->getOperand(2).hasOneUse()) {
10187
10188       // Scan all of the users of the LHS, looking for VCMPo's that match.
10189       SDNode *VCMPoNode = nullptr;
10190
10191       SDNode *LHSN = N->getOperand(0).getNode();
10192       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10193            UI != E; ++UI)
10194         if (UI->getOpcode() == PPCISD::VCMPo &&
10195             UI->getOperand(1) == N->getOperand(1) &&
10196             UI->getOperand(2) == N->getOperand(2) &&
10197             UI->getOperand(0) == N->getOperand(0)) {
10198           VCMPoNode = *UI;
10199           break;
10200         }
10201
10202       // If there is no VCMPo node, or if the flag value has a single use, don't
10203       // transform this.
10204       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10205         break;
10206
10207       // Look at the (necessarily single) use of the flag value.  If it has a
10208       // chain, this transformation is more complex.  Note that multiple things
10209       // could use the value result, which we should ignore.
10210       SDNode *FlagUser = nullptr;
10211       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10212            FlagUser == nullptr; ++UI) {
10213         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10214         SDNode *User = *UI;
10215         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10216           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10217             FlagUser = User;
10218             break;
10219           }
10220         }
10221       }
10222
10223       // If the user is a MFOCRF instruction, we know this is safe.
10224       // Otherwise we give up for right now.
10225       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10226         return SDValue(VCMPoNode, 0);
10227     }
10228     break;
10229   }
10230   case ISD::BRCOND: {
10231     SDValue Cond = N->getOperand(1);
10232     SDValue Target = N->getOperand(2);
10233  
10234     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10235         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10236           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10237
10238       // We now need to make the intrinsic dead (it cannot be instruction
10239       // selected).
10240       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10241       assert(Cond.getNode()->hasOneUse() &&
10242              "Counter decrement has more than one use");
10243
10244       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10245                          N->getOperand(0), Target);
10246     }
10247   }
10248   break;
10249   case ISD::BR_CC: {
10250     // If this is a branch on an altivec predicate comparison, lower this so
10251     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10252     // lowering is done pre-legalize, because the legalizer lowers the predicate
10253     // compare down to code that is difficult to reassemble.
10254     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10255     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10256
10257     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10258     // value. If so, pass-through the AND to get to the intrinsic.
10259     if (LHS.getOpcode() == ISD::AND &&
10260         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10261         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10262           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10263         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10264         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10265           isZero())
10266       LHS = LHS.getOperand(0);
10267
10268     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10269         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10270           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10271         isa<ConstantSDNode>(RHS)) {
10272       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10273              "Counter decrement comparison is not EQ or NE");
10274
10275       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10276       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10277                     (CC == ISD::SETNE && !Val);
10278
10279       // We now need to make the intrinsic dead (it cannot be instruction
10280       // selected).
10281       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10282       assert(LHS.getNode()->hasOneUse() &&
10283              "Counter decrement has more than one use");
10284
10285       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10286                          N->getOperand(0), N->getOperand(4));
10287     }
10288
10289     int CompareOpc;
10290     bool isDot;
10291
10292     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10293         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10294         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10295       assert(isDot && "Can't compare against a vector result!");
10296
10297       // If this is a comparison against something other than 0/1, then we know
10298       // that the condition is never/always true.
10299       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10300       if (Val != 0 && Val != 1) {
10301         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10302           return N->getOperand(0);
10303         // Always !=, turn it into an unconditional branch.
10304         return DAG.getNode(ISD::BR, dl, MVT::Other,
10305                            N->getOperand(0), N->getOperand(4));
10306       }
10307
10308       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10309
10310       // Create the PPCISD altivec 'dot' comparison node.
10311       SDValue Ops[] = {
10312         LHS.getOperand(2),  // LHS of compare
10313         LHS.getOperand(3),  // RHS of compare
10314         DAG.getConstant(CompareOpc, MVT::i32)
10315       };
10316       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10317       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10318
10319       // Unpack the result based on how the target uses it.
10320       PPC::Predicate CompOpc;
10321       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10322       default:  // Can't happen, don't crash on invalid number though.
10323       case 0:   // Branch on the value of the EQ bit of CR6.
10324         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10325         break;
10326       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10327         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10328         break;
10329       case 2:   // Branch on the value of the LT bit of CR6.
10330         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10331         break;
10332       case 3:   // Branch on the inverted value of the LT bit of CR6.
10333         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10334         break;
10335       }
10336
10337       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10338                          DAG.getConstant(CompOpc, MVT::i32),
10339                          DAG.getRegister(PPC::CR6, MVT::i32),
10340                          N->getOperand(4), CompNode.getValue(1));
10341     }
10342     break;
10343   }
10344   }
10345
10346   return SDValue();
10347 }
10348
10349 SDValue
10350 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10351                                   SelectionDAG &DAG,
10352                                   std::vector<SDNode *> *Created) const {
10353   // fold (sdiv X, pow2)
10354   EVT VT = N->getValueType(0);
10355   if (VT == MVT::i64 && !Subtarget.isPPC64())
10356     return SDValue();
10357   if ((VT != MVT::i32 && VT != MVT::i64) ||
10358       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10359     return SDValue();
10360
10361   SDLoc DL(N);
10362   SDValue N0 = N->getOperand(0);
10363
10364   bool IsNegPow2 = (-Divisor).isPowerOf2();
10365   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10366   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10367
10368   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10369   if (Created)
10370     Created->push_back(Op.getNode());
10371
10372   if (IsNegPow2) {
10373     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10374     if (Created)
10375       Created->push_back(Op.getNode());
10376   }
10377
10378   return Op;
10379 }
10380
10381 //===----------------------------------------------------------------------===//
10382 // Inline Assembly Support
10383 //===----------------------------------------------------------------------===//
10384
10385 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10386                                                       APInt &KnownZero,
10387                                                       APInt &KnownOne,
10388                                                       const SelectionDAG &DAG,
10389                                                       unsigned Depth) const {
10390   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10391   switch (Op.getOpcode()) {
10392   default: break;
10393   case PPCISD::LBRX: {
10394     // lhbrx is known to have the top bits cleared out.
10395     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10396       KnownZero = 0xFFFF0000;
10397     break;
10398   }
10399   case ISD::INTRINSIC_WO_CHAIN: {
10400     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10401     default: break;
10402     case Intrinsic::ppc_altivec_vcmpbfp_p:
10403     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10404     case Intrinsic::ppc_altivec_vcmpequb_p:
10405     case Intrinsic::ppc_altivec_vcmpequh_p:
10406     case Intrinsic::ppc_altivec_vcmpequw_p:
10407     case Intrinsic::ppc_altivec_vcmpequd_p:
10408     case Intrinsic::ppc_altivec_vcmpgefp_p:
10409     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10410     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10411     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10412     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10413     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10414     case Intrinsic::ppc_altivec_vcmpgtub_p:
10415     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10416     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10417     case Intrinsic::ppc_altivec_vcmpgtud_p:
10418       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10419       break;
10420     }
10421   }
10422   }
10423 }
10424
10425 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10426   switch (Subtarget.getDarwinDirective()) {
10427   default: break;
10428   case PPC::DIR_970:
10429   case PPC::DIR_PWR4:
10430   case PPC::DIR_PWR5:
10431   case PPC::DIR_PWR5X:
10432   case PPC::DIR_PWR6:
10433   case PPC::DIR_PWR6X:
10434   case PPC::DIR_PWR7:
10435   case PPC::DIR_PWR8: {
10436     if (!ML)
10437       break;
10438
10439     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10440
10441     // For small loops (between 5 and 8 instructions), align to a 32-byte
10442     // boundary so that the entire loop fits in one instruction-cache line.
10443     uint64_t LoopSize = 0;
10444     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10445       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10446         LoopSize += TII->GetInstSizeInBytes(J);
10447
10448     if (LoopSize > 16 && LoopSize <= 32)
10449       return 5;
10450
10451     break;
10452   }
10453   }
10454
10455   return TargetLowering::getPrefLoopAlignment(ML);
10456 }
10457
10458 /// getConstraintType - Given a constraint, return the type of
10459 /// constraint it is for this target.
10460 PPCTargetLowering::ConstraintType
10461 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10462   if (Constraint.size() == 1) {
10463     switch (Constraint[0]) {
10464     default: break;
10465     case 'b':
10466     case 'r':
10467     case 'f':
10468     case 'v':
10469     case 'y':
10470       return C_RegisterClass;
10471     case 'Z':
10472       // FIXME: While Z does indicate a memory constraint, it specifically
10473       // indicates an r+r address (used in conjunction with the 'y' modifier
10474       // in the replacement string). Currently, we're forcing the base
10475       // register to be r0 in the asm printer (which is interpreted as zero)
10476       // and forming the complete address in the second register. This is
10477       // suboptimal.
10478       return C_Memory;
10479     }
10480   } else if (Constraint == "wc") { // individual CR bits.
10481     return C_RegisterClass;
10482   } else if (Constraint == "wa" || Constraint == "wd" ||
10483              Constraint == "wf" || Constraint == "ws") {
10484     return C_RegisterClass; // VSX registers.
10485   }
10486   return TargetLowering::getConstraintType(Constraint);
10487 }
10488
10489 /// Examine constraint type and operand type and determine a weight value.
10490 /// This object must already have been set up with the operand type
10491 /// and the current alternative constraint selected.
10492 TargetLowering::ConstraintWeight
10493 PPCTargetLowering::getSingleConstraintMatchWeight(
10494     AsmOperandInfo &info, const char *constraint) const {
10495   ConstraintWeight weight = CW_Invalid;
10496   Value *CallOperandVal = info.CallOperandVal;
10497     // If we don't have a value, we can't do a match,
10498     // but allow it at the lowest weight.
10499   if (!CallOperandVal)
10500     return CW_Default;
10501   Type *type = CallOperandVal->getType();
10502
10503   // Look at the constraint type.
10504   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10505     return CW_Register; // an individual CR bit.
10506   else if ((StringRef(constraint) == "wa" ||
10507             StringRef(constraint) == "wd" ||
10508             StringRef(constraint) == "wf") &&
10509            type->isVectorTy())
10510     return CW_Register;
10511   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10512     return CW_Register;
10513
10514   switch (*constraint) {
10515   default:
10516     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10517     break;
10518   case 'b':
10519     if (type->isIntegerTy())
10520       weight = CW_Register;
10521     break;
10522   case 'f':
10523     if (type->isFloatTy())
10524       weight = CW_Register;
10525     break;
10526   case 'd':
10527     if (type->isDoubleTy())
10528       weight = CW_Register;
10529     break;
10530   case 'v':
10531     if (type->isVectorTy())
10532       weight = CW_Register;
10533     break;
10534   case 'y':
10535     weight = CW_Register;
10536     break;
10537   case 'Z':
10538     weight = CW_Memory;
10539     break;
10540   }
10541   return weight;
10542 }
10543
10544 std::pair<unsigned, const TargetRegisterClass *>
10545 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10546                                                 const std::string &Constraint,
10547                                                 MVT VT) const {
10548   if (Constraint.size() == 1) {
10549     // GCC RS6000 Constraint Letters
10550     switch (Constraint[0]) {
10551     case 'b':   // R1-R31
10552       if (VT == MVT::i64 && Subtarget.isPPC64())
10553         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10554       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10555     case 'r':   // R0-R31
10556       if (VT == MVT::i64 && Subtarget.isPPC64())
10557         return std::make_pair(0U, &PPC::G8RCRegClass);
10558       return std::make_pair(0U, &PPC::GPRCRegClass);
10559     case 'f':
10560       if (VT == MVT::f32 || VT == MVT::i32)
10561         return std::make_pair(0U, &PPC::F4RCRegClass);
10562       if (VT == MVT::f64 || VT == MVT::i64)
10563         return std::make_pair(0U, &PPC::F8RCRegClass);
10564       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10565         return std::make_pair(0U, &PPC::QFRCRegClass);
10566       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10567         return std::make_pair(0U, &PPC::QSRCRegClass);
10568       break;
10569     case 'v':
10570       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10571         return std::make_pair(0U, &PPC::QFRCRegClass);
10572       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10573         return std::make_pair(0U, &PPC::QSRCRegClass);
10574       return std::make_pair(0U, &PPC::VRRCRegClass);
10575     case 'y':   // crrc
10576       return std::make_pair(0U, &PPC::CRRCRegClass);
10577     }
10578   } else if (Constraint == "wc") { // an individual CR bit.
10579     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10580   } else if (Constraint == "wa" || Constraint == "wd" ||
10581              Constraint == "wf") {
10582     return std::make_pair(0U, &PPC::VSRCRegClass);
10583   } else if (Constraint == "ws") {
10584     return std::make_pair(0U, &PPC::VSFRCRegClass);
10585   }
10586
10587   std::pair<unsigned, const TargetRegisterClass *> R =
10588       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10589
10590   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10591   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10592   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10593   // register.
10594   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10595   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10596   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10597       PPC::GPRCRegClass.contains(R.first))
10598     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10599                             PPC::sub_32, &PPC::G8RCRegClass),
10600                           &PPC::G8RCRegClass);
10601
10602   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10603   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10604     R.first = PPC::CR0;
10605     R.second = &PPC::CRRCRegClass;
10606   }
10607
10608   return R;
10609 }
10610
10611
10612 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10613 /// vector.  If it is invalid, don't add anything to Ops.
10614 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10615                                                      std::string &Constraint,
10616                                                      std::vector<SDValue>&Ops,
10617                                                      SelectionDAG &DAG) const {
10618   SDValue Result;
10619
10620   // Only support length 1 constraints.
10621   if (Constraint.length() > 1) return;
10622
10623   char Letter = Constraint[0];
10624   switch (Letter) {
10625   default: break;
10626   case 'I':
10627   case 'J':
10628   case 'K':
10629   case 'L':
10630   case 'M':
10631   case 'N':
10632   case 'O':
10633   case 'P': {
10634     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10635     if (!CST) return; // Must be an immediate to match.
10636     int64_t Value = CST->getSExtValue();
10637     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10638                          // numbers are printed as such.
10639     switch (Letter) {
10640     default: llvm_unreachable("Unknown constraint letter!");
10641     case 'I':  // "I" is a signed 16-bit constant.
10642       if (isInt<16>(Value))
10643         Result = DAG.getTargetConstant(Value, TCVT);
10644       break;
10645     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10646       if (isShiftedUInt<16, 16>(Value))
10647         Result = DAG.getTargetConstant(Value, TCVT);
10648       break;
10649     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10650       if (isShiftedInt<16, 16>(Value))
10651         Result = DAG.getTargetConstant(Value, TCVT);
10652       break;
10653     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10654       if (isUInt<16>(Value))
10655         Result = DAG.getTargetConstant(Value, TCVT);
10656       break;
10657     case 'M':  // "M" is a constant that is greater than 31.
10658       if (Value > 31)
10659         Result = DAG.getTargetConstant(Value, TCVT);
10660       break;
10661     case 'N':  // "N" is a positive constant that is an exact power of two.
10662       if (Value > 0 && isPowerOf2_64(Value))
10663         Result = DAG.getTargetConstant(Value, TCVT);
10664       break;
10665     case 'O':  // "O" is the constant zero.
10666       if (Value == 0)
10667         Result = DAG.getTargetConstant(Value, TCVT);
10668       break;
10669     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10670       if (isInt<16>(-Value))
10671         Result = DAG.getTargetConstant(Value, TCVT);
10672       break;
10673     }
10674     break;
10675   }
10676   }
10677
10678   if (Result.getNode()) {
10679     Ops.push_back(Result);
10680     return;
10681   }
10682
10683   // Handle standard constraint letters.
10684   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10685 }
10686
10687 // isLegalAddressingMode - Return true if the addressing mode represented
10688 // by AM is legal for this target, for a load/store of the specified type.
10689 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10690                                               Type *Ty) const {
10691   // PPC does not allow r+i addressing modes for vectors!
10692   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10693     return false;
10694
10695   // PPC allows a sign-extended 16-bit immediate field.
10696   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10697     return false;
10698
10699   // No global is ever allowed as a base.
10700   if (AM.BaseGV)
10701     return false;
10702
10703   // PPC only support r+r,
10704   switch (AM.Scale) {
10705   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10706     break;
10707   case 1:
10708     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10709       return false;
10710     // Otherwise we have r+r or r+i.
10711     break;
10712   case 2:
10713     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10714       return false;
10715     // Allow 2*r as r+r.
10716     break;
10717   default:
10718     // No other scales are supported.
10719     return false;
10720   }
10721
10722   return true;
10723 }
10724
10725 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10726                                            SelectionDAG &DAG) const {
10727   MachineFunction &MF = DAG.getMachineFunction();
10728   MachineFrameInfo *MFI = MF.getFrameInfo();
10729   MFI->setReturnAddressIsTaken(true);
10730
10731   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10732     return SDValue();
10733
10734   SDLoc dl(Op);
10735   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10736
10737   // Make sure the function does not optimize away the store of the RA to
10738   // the stack.
10739   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10740   FuncInfo->setLRStoreRequired();
10741   bool isPPC64 = Subtarget.isPPC64();
10742
10743   if (Depth > 0) {
10744     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10745     SDValue Offset =
10746         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10747                         isPPC64 ? MVT::i64 : MVT::i32);
10748     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10749                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10750                                    FrameAddr, Offset),
10751                        MachinePointerInfo(), false, false, false, 0);
10752   }
10753
10754   // Just load the return address off the stack.
10755   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10756   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10757                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10758 }
10759
10760 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10761                                           SelectionDAG &DAG) const {
10762   SDLoc dl(Op);
10763   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10764
10765   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10766   bool isPPC64 = PtrVT == MVT::i64;
10767
10768   MachineFunction &MF = DAG.getMachineFunction();
10769   MachineFrameInfo *MFI = MF.getFrameInfo();
10770   MFI->setFrameAddressIsTaken(true);
10771
10772   // Naked functions never have a frame pointer, and so we use r1. For all
10773   // other functions, this decision must be delayed until during PEI.
10774   unsigned FrameReg;
10775   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10776     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10777   else
10778     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10779
10780   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10781                                          PtrVT);
10782   while (Depth--)
10783     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10784                             FrameAddr, MachinePointerInfo(), false, false,
10785                             false, 0);
10786   return FrameAddr;
10787 }
10788
10789 // FIXME? Maybe this could be a TableGen attribute on some registers and
10790 // this table could be generated automatically from RegInfo.
10791 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10792                                               EVT VT) const {
10793   bool isPPC64 = Subtarget.isPPC64();
10794   bool isDarwinABI = Subtarget.isDarwinABI();
10795
10796   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10797       (!isPPC64 && VT != MVT::i32))
10798     report_fatal_error("Invalid register global variable type");
10799
10800   bool is64Bit = isPPC64 && VT == MVT::i64;
10801   unsigned Reg = StringSwitch<unsigned>(RegName)
10802                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10803                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10804                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10805                                   (is64Bit ? PPC::X13 : PPC::R13))
10806                    .Default(0);
10807
10808   if (Reg)
10809     return Reg;
10810   report_fatal_error("Invalid register name global variable");
10811 }
10812
10813 bool
10814 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10815   // The PowerPC target isn't yet aware of offsets.
10816   return false;
10817 }
10818
10819 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10820                                            const CallInst &I,
10821                                            unsigned Intrinsic) const {
10822
10823   switch (Intrinsic) {
10824   case Intrinsic::ppc_qpx_qvlfd:
10825   case Intrinsic::ppc_qpx_qvlfs:
10826   case Intrinsic::ppc_qpx_qvlfcd:
10827   case Intrinsic::ppc_qpx_qvlfcs:
10828   case Intrinsic::ppc_qpx_qvlfiwa:
10829   case Intrinsic::ppc_qpx_qvlfiwz:
10830   case Intrinsic::ppc_altivec_lvx:
10831   case Intrinsic::ppc_altivec_lvxl:
10832   case Intrinsic::ppc_altivec_lvebx:
10833   case Intrinsic::ppc_altivec_lvehx:
10834   case Intrinsic::ppc_altivec_lvewx:
10835   case Intrinsic::ppc_vsx_lxvd2x:
10836   case Intrinsic::ppc_vsx_lxvw4x: {
10837     EVT VT;
10838     switch (Intrinsic) {
10839     case Intrinsic::ppc_altivec_lvebx:
10840       VT = MVT::i8;
10841       break;
10842     case Intrinsic::ppc_altivec_lvehx:
10843       VT = MVT::i16;
10844       break;
10845     case Intrinsic::ppc_altivec_lvewx:
10846       VT = MVT::i32;
10847       break;
10848     case Intrinsic::ppc_vsx_lxvd2x:
10849       VT = MVT::v2f64;
10850       break;
10851     case Intrinsic::ppc_qpx_qvlfd:
10852       VT = MVT::v4f64;
10853       break;
10854     case Intrinsic::ppc_qpx_qvlfs:
10855       VT = MVT::v4f32;
10856       break;
10857     case Intrinsic::ppc_qpx_qvlfcd:
10858       VT = MVT::v2f64;
10859       break;
10860     case Intrinsic::ppc_qpx_qvlfcs:
10861       VT = MVT::v2f32;
10862       break;
10863     default:
10864       VT = MVT::v4i32;
10865       break;
10866     }
10867
10868     Info.opc = ISD::INTRINSIC_W_CHAIN;
10869     Info.memVT = VT;
10870     Info.ptrVal = I.getArgOperand(0);
10871     Info.offset = -VT.getStoreSize()+1;
10872     Info.size = 2*VT.getStoreSize()-1;
10873     Info.align = 1;
10874     Info.vol = false;
10875     Info.readMem = true;
10876     Info.writeMem = false;
10877     return true;
10878   }
10879   case Intrinsic::ppc_qpx_qvlfda:
10880   case Intrinsic::ppc_qpx_qvlfsa:
10881   case Intrinsic::ppc_qpx_qvlfcda:
10882   case Intrinsic::ppc_qpx_qvlfcsa:
10883   case Intrinsic::ppc_qpx_qvlfiwaa:
10884   case Intrinsic::ppc_qpx_qvlfiwza: {
10885     EVT VT;
10886     switch (Intrinsic) {
10887     case Intrinsic::ppc_qpx_qvlfda:
10888       VT = MVT::v4f64;
10889       break;
10890     case Intrinsic::ppc_qpx_qvlfsa:
10891       VT = MVT::v4f32;
10892       break;
10893     case Intrinsic::ppc_qpx_qvlfcda:
10894       VT = MVT::v2f64;
10895       break;
10896     case Intrinsic::ppc_qpx_qvlfcsa:
10897       VT = MVT::v2f32;
10898       break;
10899     default:
10900       VT = MVT::v4i32;
10901       break;
10902     }
10903
10904     Info.opc = ISD::INTRINSIC_W_CHAIN;
10905     Info.memVT = VT;
10906     Info.ptrVal = I.getArgOperand(0);
10907     Info.offset = 0;
10908     Info.size = VT.getStoreSize();
10909     Info.align = 1;
10910     Info.vol = false;
10911     Info.readMem = true;
10912     Info.writeMem = false;
10913     return true;
10914   }
10915   case Intrinsic::ppc_qpx_qvstfd:
10916   case Intrinsic::ppc_qpx_qvstfs:
10917   case Intrinsic::ppc_qpx_qvstfcd:
10918   case Intrinsic::ppc_qpx_qvstfcs:
10919   case Intrinsic::ppc_qpx_qvstfiw:
10920   case Intrinsic::ppc_altivec_stvx:
10921   case Intrinsic::ppc_altivec_stvxl:
10922   case Intrinsic::ppc_altivec_stvebx:
10923   case Intrinsic::ppc_altivec_stvehx:
10924   case Intrinsic::ppc_altivec_stvewx:
10925   case Intrinsic::ppc_vsx_stxvd2x:
10926   case Intrinsic::ppc_vsx_stxvw4x: {
10927     EVT VT;
10928     switch (Intrinsic) {
10929     case Intrinsic::ppc_altivec_stvebx:
10930       VT = MVT::i8;
10931       break;
10932     case Intrinsic::ppc_altivec_stvehx:
10933       VT = MVT::i16;
10934       break;
10935     case Intrinsic::ppc_altivec_stvewx:
10936       VT = MVT::i32;
10937       break;
10938     case Intrinsic::ppc_vsx_stxvd2x:
10939       VT = MVT::v2f64;
10940       break;
10941     case Intrinsic::ppc_qpx_qvstfd:
10942       VT = MVT::v4f64;
10943       break;
10944     case Intrinsic::ppc_qpx_qvstfs:
10945       VT = MVT::v4f32;
10946       break;
10947     case Intrinsic::ppc_qpx_qvstfcd:
10948       VT = MVT::v2f64;
10949       break;
10950     case Intrinsic::ppc_qpx_qvstfcs:
10951       VT = MVT::v2f32;
10952       break;
10953     default:
10954       VT = MVT::v4i32;
10955       break;
10956     }
10957
10958     Info.opc = ISD::INTRINSIC_VOID;
10959     Info.memVT = VT;
10960     Info.ptrVal = I.getArgOperand(1);
10961     Info.offset = -VT.getStoreSize()+1;
10962     Info.size = 2*VT.getStoreSize()-1;
10963     Info.align = 1;
10964     Info.vol = false;
10965     Info.readMem = false;
10966     Info.writeMem = true;
10967     return true;
10968   }
10969   case Intrinsic::ppc_qpx_qvstfda:
10970   case Intrinsic::ppc_qpx_qvstfsa:
10971   case Intrinsic::ppc_qpx_qvstfcda:
10972   case Intrinsic::ppc_qpx_qvstfcsa:
10973   case Intrinsic::ppc_qpx_qvstfiwa: {
10974     EVT VT;
10975     switch (Intrinsic) {
10976     case Intrinsic::ppc_qpx_qvstfda:
10977       VT = MVT::v4f64;
10978       break;
10979     case Intrinsic::ppc_qpx_qvstfsa:
10980       VT = MVT::v4f32;
10981       break;
10982     case Intrinsic::ppc_qpx_qvstfcda:
10983       VT = MVT::v2f64;
10984       break;
10985     case Intrinsic::ppc_qpx_qvstfcsa:
10986       VT = MVT::v2f32;
10987       break;
10988     default:
10989       VT = MVT::v4i32;
10990       break;
10991     }
10992
10993     Info.opc = ISD::INTRINSIC_VOID;
10994     Info.memVT = VT;
10995     Info.ptrVal = I.getArgOperand(1);
10996     Info.offset = 0;
10997     Info.size = VT.getStoreSize();
10998     Info.align = 1;
10999     Info.vol = false;
11000     Info.readMem = false;
11001     Info.writeMem = true;
11002     return true;
11003   }
11004   default:
11005     break;
11006   }
11007
11008   return false;
11009 }
11010
11011 /// getOptimalMemOpType - Returns the target specific optimal type for load
11012 /// and store operations as a result of memset, memcpy, and memmove
11013 /// lowering. If DstAlign is zero that means it's safe to destination
11014 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11015 /// means there isn't a need to check it against alignment requirement,
11016 /// probably because the source does not need to be loaded. If 'IsMemset' is
11017 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11018 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11019 /// source is constant so it does not need to be loaded.
11020 /// It returns EVT::Other if the type should be determined using generic
11021 /// target-independent logic.
11022 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11023                                            unsigned DstAlign, unsigned SrcAlign,
11024                                            bool IsMemset, bool ZeroMemset,
11025                                            bool MemcpyStrSrc,
11026                                            MachineFunction &MF) const {
11027   const Function *F = MF.getFunction();
11028   // When expanding a memset, require at least two QPX instructions to cover
11029   // the cost of loading the value to be stored from the constant pool.
11030   if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11031      (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11032       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11033     return MVT::v4f64;
11034   }
11035
11036   // We should use Altivec/VSX loads and stores when available. For unaligned
11037   // addresses, unaligned VSX loads are only fast starting with the P8.
11038   if (Subtarget.hasAltivec() && Size >= 16 &&
11039       (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11040        ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11041     return MVT::v4i32;
11042
11043   if (Subtarget.isPPC64()) {
11044     return MVT::i64;
11045   }
11046
11047   return MVT::i32;
11048 }
11049
11050 /// \brief Returns true if it is beneficial to convert a load of a constant
11051 /// to just the constant itself.
11052 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11053                                                           Type *Ty) const {
11054   assert(Ty->isIntegerTy());
11055
11056   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11057   if (BitSize == 0 || BitSize > 64)
11058     return false;
11059   return true;
11060 }
11061
11062 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11063   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11064     return false;
11065   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11066   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11067   return NumBits1 == 64 && NumBits2 == 32;
11068 }
11069
11070 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11071   if (!VT1.isInteger() || !VT2.isInteger())
11072     return false;
11073   unsigned NumBits1 = VT1.getSizeInBits();
11074   unsigned NumBits2 = VT2.getSizeInBits();
11075   return NumBits1 == 64 && NumBits2 == 32;
11076 }
11077
11078 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11079   // Generally speaking, zexts are not free, but they are free when they can be
11080   // folded with other operations.
11081   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11082     EVT MemVT = LD->getMemoryVT();
11083     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11084          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11085         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11086          LD->getExtensionType() == ISD::ZEXTLOAD))
11087       return true;
11088   }
11089
11090   // FIXME: Add other cases...
11091   //  - 32-bit shifts with a zext to i64
11092   //  - zext after ctlz, bswap, etc.
11093   //  - zext after and by a constant mask
11094
11095   return TargetLowering::isZExtFree(Val, VT2);
11096 }
11097
11098 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11099   assert(VT.isFloatingPoint());
11100   return true;
11101 }
11102
11103 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11104   return isInt<16>(Imm) || isUInt<16>(Imm);
11105 }
11106
11107 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11108   return isInt<16>(Imm) || isUInt<16>(Imm);
11109 }
11110
11111 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11112                                                        unsigned,
11113                                                        unsigned,
11114                                                        bool *Fast) const {
11115   if (DisablePPCUnaligned)
11116     return false;
11117
11118   // PowerPC supports unaligned memory access for simple non-vector types.
11119   // Although accessing unaligned addresses is not as efficient as accessing
11120   // aligned addresses, it is generally more efficient than manual expansion,
11121   // and generally only traps for software emulation when crossing page
11122   // boundaries.
11123
11124   if (!VT.isSimple())
11125     return false;
11126
11127   if (VT.getSimpleVT().isVector()) {
11128     if (Subtarget.hasVSX()) {
11129       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11130           VT != MVT::v4f32 && VT != MVT::v4i32)
11131         return false;
11132     } else {
11133       return false;
11134     }
11135   }
11136
11137   if (VT == MVT::ppcf128)
11138     return false;
11139
11140   if (Fast)
11141     *Fast = true;
11142
11143   return true;
11144 }
11145
11146 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11147   VT = VT.getScalarType();
11148
11149   if (!VT.isSimple())
11150     return false;
11151
11152   switch (VT.getSimpleVT().SimpleTy) {
11153   case MVT::f32:
11154   case MVT::f64:
11155     return true;
11156   default:
11157     break;
11158   }
11159
11160   return false;
11161 }
11162
11163 const MCPhysReg *
11164 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11165   // LR is a callee-save register, but we must treat it as clobbered by any call
11166   // site. Hence we include LR in the scratch registers, which are in turn added
11167   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11168   // to CTR, which is used by any indirect call.
11169   static const MCPhysReg ScratchRegs[] = {
11170     PPC::X12, PPC::LR8, PPC::CTR8, 0
11171   };
11172
11173   return ScratchRegs;
11174 }
11175
11176 bool
11177 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11178                      EVT VT , unsigned DefinedValues) const {
11179   if (VT == MVT::v2i64)
11180     return false;
11181
11182   if (Subtarget.hasQPX()) {
11183     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11184       return true;
11185   }
11186
11187   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11188 }
11189
11190 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11191   if (DisableILPPref || Subtarget.enableMachineScheduler())
11192     return TargetLowering::getSchedulingPreference(N);
11193
11194   return Sched::ILP;
11195 }
11196
11197 // Create a fast isel object.
11198 FastISel *
11199 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11200                                   const TargetLibraryInfo *LibInfo) const {
11201   return PPC::createFastISel(FuncInfo, LibInfo);
11202 }