[APInt] Add an isSplat helper and use it in some places.
[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, check if it consists
1407   // of a repeated bit pattern of size ByteSize.
1408   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1409     return SDValue();
1410
1411   // Properly sign extend the value.
1412   int MaskVal = SignExtend32(Value, ByteSize * 8);
1413
1414   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1415   if (MaskVal == 0) return SDValue();
1416
1417   // Finally, if this value fits in a 5 bit sext field, return it
1418   if (SignExtend32<5>(MaskVal) == MaskVal)
1419     return DAG.getTargetConstant(MaskVal, MVT::i32);
1420   return SDValue();
1421 }
1422
1423 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1424 /// amount, otherwise return -1.
1425 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1426   EVT VT = N->getValueType(0);
1427   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1428     return -1;
1429
1430   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1431
1432   // Find the first non-undef value in the shuffle mask.
1433   unsigned i;
1434   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1435     /*search*/;
1436
1437   if (i == 4) return -1;  // all undef.
1438
1439   // Otherwise, check to see if the rest of the elements are consecutively
1440   // numbered from this value.
1441   unsigned ShiftAmt = SVOp->getMaskElt(i);
1442   if (ShiftAmt < i) return -1;
1443   ShiftAmt -= i;
1444
1445   // Check the rest of the elements to see if they are consecutive.
1446   for (++i; i != 4; ++i)
1447     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1448       return -1;
1449
1450   return ShiftAmt;
1451 }
1452
1453 //===----------------------------------------------------------------------===//
1454 //  Addressing Mode Selection
1455 //===----------------------------------------------------------------------===//
1456
1457 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1458 /// or 64-bit immediate, and if the value can be accurately represented as a
1459 /// sign extension from a 16-bit value.  If so, this returns true and the
1460 /// immediate.
1461 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1462   if (!isa<ConstantSDNode>(N))
1463     return false;
1464
1465   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1466   if (N->getValueType(0) == MVT::i32)
1467     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1468   else
1469     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1470 }
1471 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1472   return isIntS16Immediate(Op.getNode(), Imm);
1473 }
1474
1475
1476 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1477 /// can be represented as an indexed [r+r] operation.  Returns false if it
1478 /// can be more efficiently represented with [r+imm].
1479 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1480                                             SDValue &Index,
1481                                             SelectionDAG &DAG) const {
1482   short imm = 0;
1483   if (N.getOpcode() == ISD::ADD) {
1484     if (isIntS16Immediate(N.getOperand(1), imm))
1485       return false;    // r+i
1486     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1487       return false;    // r+i
1488
1489     Base = N.getOperand(0);
1490     Index = N.getOperand(1);
1491     return true;
1492   } else if (N.getOpcode() == ISD::OR) {
1493     if (isIntS16Immediate(N.getOperand(1), imm))
1494       return false;    // r+i can fold it if we can.
1495
1496     // If this is an or of disjoint bitfields, we can codegen this as an add
1497     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1498     // disjoint.
1499     APInt LHSKnownZero, LHSKnownOne;
1500     APInt RHSKnownZero, RHSKnownOne;
1501     DAG.computeKnownBits(N.getOperand(0),
1502                          LHSKnownZero, LHSKnownOne);
1503
1504     if (LHSKnownZero.getBoolValue()) {
1505       DAG.computeKnownBits(N.getOperand(1),
1506                            RHSKnownZero, RHSKnownOne);
1507       // If all of the bits are known zero on the LHS or RHS, the add won't
1508       // carry.
1509       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1510         Base = N.getOperand(0);
1511         Index = N.getOperand(1);
1512         return true;
1513       }
1514     }
1515   }
1516
1517   return false;
1518 }
1519
1520 // If we happen to be doing an i64 load or store into a stack slot that has
1521 // less than a 4-byte alignment, then the frame-index elimination may need to
1522 // use an indexed load or store instruction (because the offset may not be a
1523 // multiple of 4). The extra register needed to hold the offset comes from the
1524 // register scavenger, and it is possible that the scavenger will need to use
1525 // an emergency spill slot. As a result, we need to make sure that a spill slot
1526 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1527 // stack slot.
1528 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1529   // FIXME: This does not handle the LWA case.
1530   if (VT != MVT::i64)
1531     return;
1532
1533   // NOTE: We'll exclude negative FIs here, which come from argument
1534   // lowering, because there are no known test cases triggering this problem
1535   // using packed structures (or similar). We can remove this exclusion if
1536   // we find such a test case. The reason why this is so test-case driven is
1537   // because this entire 'fixup' is only to prevent crashes (from the
1538   // register scavenger) on not-really-valid inputs. For example, if we have:
1539   //   %a = alloca i1
1540   //   %b = bitcast i1* %a to i64*
1541   //   store i64* a, i64 b
1542   // then the store should really be marked as 'align 1', but is not. If it
1543   // were marked as 'align 1' then the indexed form would have been
1544   // instruction-selected initially, and the problem this 'fixup' is preventing
1545   // won't happen regardless.
1546   if (FrameIdx < 0)
1547     return;
1548
1549   MachineFunction &MF = DAG.getMachineFunction();
1550   MachineFrameInfo *MFI = MF.getFrameInfo();
1551
1552   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1553   if (Align >= 4)
1554     return;
1555
1556   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1557   FuncInfo->setHasNonRISpills();
1558 }
1559
1560 /// Returns true if the address N can be represented by a base register plus
1561 /// a signed 16-bit displacement [r+imm], and if it is not better
1562 /// represented as reg+reg.  If Aligned is true, only accept displacements
1563 /// suitable for STD and friends, i.e. multiples of 4.
1564 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1565                                             SDValue &Base,
1566                                             SelectionDAG &DAG,
1567                                             bool Aligned) const {
1568   // FIXME dl should come from parent load or store, not from address
1569   SDLoc dl(N);
1570   // If this can be more profitably realized as r+r, fail.
1571   if (SelectAddressRegReg(N, Disp, Base, DAG))
1572     return false;
1573
1574   if (N.getOpcode() == ISD::ADD) {
1575     short imm = 0;
1576     if (isIntS16Immediate(N.getOperand(1), imm) &&
1577         (!Aligned || (imm & 3) == 0)) {
1578       Disp = DAG.getTargetConstant(imm, N.getValueType());
1579       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1580         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1581         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1582       } else {
1583         Base = N.getOperand(0);
1584       }
1585       return true; // [r+i]
1586     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1587       // Match LOAD (ADD (X, Lo(G))).
1588       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1589              && "Cannot handle constant offsets yet!");
1590       Disp = N.getOperand(1).getOperand(0);  // The global address.
1591       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1592              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1593              Disp.getOpcode() == ISD::TargetConstantPool ||
1594              Disp.getOpcode() == ISD::TargetJumpTable);
1595       Base = N.getOperand(0);
1596       return true;  // [&g+r]
1597     }
1598   } else if (N.getOpcode() == ISD::OR) {
1599     short imm = 0;
1600     if (isIntS16Immediate(N.getOperand(1), imm) &&
1601         (!Aligned || (imm & 3) == 0)) {
1602       // If this is an or of disjoint bitfields, we can codegen this as an add
1603       // (for better address arithmetic) if the LHS and RHS of the OR are
1604       // provably disjoint.
1605       APInt LHSKnownZero, LHSKnownOne;
1606       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1607
1608       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1609         // If all of the bits are known zero on the LHS or RHS, the add won't
1610         // carry.
1611         if (FrameIndexSDNode *FI =
1612               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1613           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1614           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1615         } else {
1616           Base = N.getOperand(0);
1617         }
1618         Disp = DAG.getTargetConstant(imm, N.getValueType());
1619         return true;
1620       }
1621     }
1622   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1623     // Loading from a constant address.
1624
1625     // If this address fits entirely in a 16-bit sext immediate field, codegen
1626     // this as "d, 0"
1627     short Imm;
1628     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1629       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1630       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1631                              CN->getValueType(0));
1632       return true;
1633     }
1634
1635     // Handle 32-bit sext immediates with LIS + addr mode.
1636     if ((CN->getValueType(0) == MVT::i32 ||
1637          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1638         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1639       int Addr = (int)CN->getZExtValue();
1640
1641       // Otherwise, break this down into an LIS + disp.
1642       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1643
1644       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1645       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1646       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1647       return true;
1648     }
1649   }
1650
1651   Disp = DAG.getTargetConstant(0, getPointerTy());
1652   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1653     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1654     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1655   } else
1656     Base = N;
1657   return true;      // [r+0]
1658 }
1659
1660 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1661 /// represented as an indexed [r+r] operation.
1662 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1663                                                 SDValue &Index,
1664                                                 SelectionDAG &DAG) const {
1665   // Check to see if we can easily represent this as an [r+r] address.  This
1666   // will fail if it thinks that the address is more profitably represented as
1667   // reg+imm, e.g. where imm = 0.
1668   if (SelectAddressRegReg(N, Base, Index, DAG))
1669     return true;
1670
1671   // If the operand is an addition, always emit this as [r+r], since this is
1672   // better (for code size, and execution, as the memop does the add for free)
1673   // than emitting an explicit add.
1674   if (N.getOpcode() == ISD::ADD) {
1675     Base = N.getOperand(0);
1676     Index = N.getOperand(1);
1677     return true;
1678   }
1679
1680   // Otherwise, do it the hard way, using R0 as the base register.
1681   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1682                          N.getValueType());
1683   Index = N;
1684   return true;
1685 }
1686
1687 /// getPreIndexedAddressParts - returns true by value, base pointer and
1688 /// offset pointer and addressing mode by reference if the node's address
1689 /// can be legally represented as pre-indexed load / store address.
1690 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1691                                                   SDValue &Offset,
1692                                                   ISD::MemIndexedMode &AM,
1693                                                   SelectionDAG &DAG) const {
1694   if (DisablePPCPreinc) return false;
1695
1696   bool isLoad = true;
1697   SDValue Ptr;
1698   EVT VT;
1699   unsigned Alignment;
1700   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1701     Ptr = LD->getBasePtr();
1702     VT = LD->getMemoryVT();
1703     Alignment = LD->getAlignment();
1704   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1705     Ptr = ST->getBasePtr();
1706     VT  = ST->getMemoryVT();
1707     Alignment = ST->getAlignment();
1708     isLoad = false;
1709   } else
1710     return false;
1711
1712   // PowerPC doesn't have preinc load/store instructions for vectors (except
1713   // for QPX, which does have preinc r+r forms).
1714   if (VT.isVector()) {
1715     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1716       return false;
1717     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1718       AM = ISD::PRE_INC;
1719       return true;
1720     }
1721   }
1722
1723   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1724
1725     // Common code will reject creating a pre-inc form if the base pointer
1726     // is a frame index, or if N is a store and the base pointer is either
1727     // the same as or a predecessor of the value being stored.  Check for
1728     // those situations here, and try with swapped Base/Offset instead.
1729     bool Swap = false;
1730
1731     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1732       Swap = true;
1733     else if (!isLoad) {
1734       SDValue Val = cast<StoreSDNode>(N)->getValue();
1735       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1736         Swap = true;
1737     }
1738
1739     if (Swap)
1740       std::swap(Base, Offset);
1741
1742     AM = ISD::PRE_INC;
1743     return true;
1744   }
1745
1746   // LDU/STU can only handle immediates that are a multiple of 4.
1747   if (VT != MVT::i64) {
1748     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1749       return false;
1750   } else {
1751     // LDU/STU need an address with at least 4-byte alignment.
1752     if (Alignment < 4)
1753       return false;
1754
1755     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1756       return false;
1757   }
1758
1759   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1760     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1761     // sext i32 to i64 when addr mode is r+i.
1762     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1763         LD->getExtensionType() == ISD::SEXTLOAD &&
1764         isa<ConstantSDNode>(Offset))
1765       return false;
1766   }
1767
1768   AM = ISD::PRE_INC;
1769   return true;
1770 }
1771
1772 //===----------------------------------------------------------------------===//
1773 //  LowerOperation implementation
1774 //===----------------------------------------------------------------------===//
1775
1776 /// GetLabelAccessInfo - Return true if we should reference labels using a
1777 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1778 static bool GetLabelAccessInfo(const TargetMachine &TM,
1779                                const PPCSubtarget &Subtarget,
1780                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1781                                const GlobalValue *GV = nullptr) {
1782   HiOpFlags = PPCII::MO_HA;
1783   LoOpFlags = PPCII::MO_LO;
1784
1785   // Don't use the pic base if not in PIC relocation model.
1786   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1787
1788   if (isPIC) {
1789     HiOpFlags |= PPCII::MO_PIC_FLAG;
1790     LoOpFlags |= PPCII::MO_PIC_FLAG;
1791   }
1792
1793   // If this is a reference to a global value that requires a non-lazy-ptr, make
1794   // sure that instruction lowering adds it.
1795   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1796     HiOpFlags |= PPCII::MO_NLP_FLAG;
1797     LoOpFlags |= PPCII::MO_NLP_FLAG;
1798
1799     if (GV->hasHiddenVisibility()) {
1800       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1801       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1802     }
1803   }
1804
1805   return isPIC;
1806 }
1807
1808 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1809                              SelectionDAG &DAG) {
1810   EVT PtrVT = HiPart.getValueType();
1811   SDValue Zero = DAG.getConstant(0, PtrVT);
1812   SDLoc DL(HiPart);
1813
1814   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1815   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1816
1817   // With PIC, the first instruction is actually "GR+hi(&G)".
1818   if (isPIC)
1819     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1820                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1821
1822   // Generate non-pic code that has direct accesses to the constant pool.
1823   // The address of the global is just (hi(&g)+lo(&g)).
1824   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1825 }
1826
1827 static void setUsesTOCBasePtr(MachineFunction &MF) {
1828   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1829   FuncInfo->setUsesTOCBasePtr();
1830 }
1831
1832 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1833   setUsesTOCBasePtr(DAG.getMachineFunction());
1834 }
1835
1836 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1837                            SDValue GA) {
1838   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1839   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1840                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1841
1842   SDValue Ops[] = { GA, Reg };
1843   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1844                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1845                                  MachinePointerInfo::getGOT(), 0, false, true,
1846                                  false, 0);
1847 }
1848
1849 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1850                                              SelectionDAG &DAG) const {
1851   EVT PtrVT = Op.getValueType();
1852   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1853   const Constant *C = CP->getConstVal();
1854
1855   // 64-bit SVR4 ABI code is always position-independent.
1856   // The actual address of the GlobalValue is stored in the TOC.
1857   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1858     setUsesTOCBasePtr(DAG);
1859     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1860     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1861   }
1862
1863   unsigned MOHiFlag, MOLoFlag;
1864   bool isPIC =
1865       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1866
1867   if (isPIC && Subtarget.isSVR4ABI()) {
1868     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1869                                            PPCII::MO_PIC_FLAG);
1870     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1871   }
1872
1873   SDValue CPIHi =
1874     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1875   SDValue CPILo =
1876     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1877   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1878 }
1879
1880 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1881   EVT PtrVT = Op.getValueType();
1882   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1883
1884   // 64-bit SVR4 ABI code is always position-independent.
1885   // The actual address of the GlobalValue is stored in the TOC.
1886   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1887     setUsesTOCBasePtr(DAG);
1888     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1889     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1890   }
1891
1892   unsigned MOHiFlag, MOLoFlag;
1893   bool isPIC =
1894       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1895
1896   if (isPIC && Subtarget.isSVR4ABI()) {
1897     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1898                                         PPCII::MO_PIC_FLAG);
1899     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1900   }
1901
1902   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1903   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1904   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1905 }
1906
1907 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1908                                              SelectionDAG &DAG) const {
1909   EVT PtrVT = Op.getValueType();
1910   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1911   const BlockAddress *BA = BASDN->getBlockAddress();
1912
1913   // 64-bit SVR4 ABI code is always position-independent.
1914   // The actual BlockAddress is stored in the TOC.
1915   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1916     setUsesTOCBasePtr(DAG);
1917     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1918     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1919   }
1920
1921   unsigned MOHiFlag, MOLoFlag;
1922   bool isPIC =
1923       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1924   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1925   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1926   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1927 }
1928
1929 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1930                                               SelectionDAG &DAG) const {
1931
1932   // FIXME: TLS addresses currently use medium model code sequences,
1933   // which is the most useful form.  Eventually support for small and
1934   // large models could be added if users need it, at the cost of
1935   // additional complexity.
1936   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1937   SDLoc dl(GA);
1938   const GlobalValue *GV = GA->getGlobal();
1939   EVT PtrVT = getPointerTy();
1940   bool is64bit = Subtarget.isPPC64();
1941   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1942   PICLevel::Level picLevel = M->getPICLevel();
1943
1944   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1945
1946   if (Model == TLSModel::LocalExec) {
1947     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1948                                                PPCII::MO_TPREL_HA);
1949     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1950                                                PPCII::MO_TPREL_LO);
1951     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1952                                      is64bit ? MVT::i64 : MVT::i32);
1953     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1954     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1955   }
1956
1957   if (Model == TLSModel::InitialExec) {
1958     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1959     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1960                                                 PPCII::MO_TLS);
1961     SDValue GOTPtr;
1962     if (is64bit) {
1963       setUsesTOCBasePtr(DAG);
1964       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1965       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1966                            PtrVT, GOTReg, TGA);
1967     } else
1968       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1969     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1970                                    PtrVT, TGA, GOTPtr);
1971     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1972   }
1973
1974   if (Model == TLSModel::GeneralDynamic) {
1975     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1976     SDValue GOTPtr;
1977     if (is64bit) {
1978       setUsesTOCBasePtr(DAG);
1979       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1980       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1981                                    GOTReg, TGA);
1982     } else {
1983       if (picLevel == PICLevel::Small)
1984         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1985       else
1986         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1987     }
1988     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
1989                        GOTPtr, TGA, TGA);
1990   }
1991
1992   if (Model == TLSModel::LocalDynamic) {
1993     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1994     SDValue GOTPtr;
1995     if (is64bit) {
1996       setUsesTOCBasePtr(DAG);
1997       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1998       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1999                            GOTReg, TGA);
2000     } else {
2001       if (picLevel == PICLevel::Small)
2002         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2003       else
2004         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2005     }
2006     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2007                                   PtrVT, GOTPtr, TGA, TGA);
2008     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2009                                       PtrVT, TLSAddr, TGA);
2010     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2011   }
2012
2013   llvm_unreachable("Unknown TLS model!");
2014 }
2015
2016 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2017                                               SelectionDAG &DAG) const {
2018   EVT PtrVT = Op.getValueType();
2019   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2020   SDLoc DL(GSDN);
2021   const GlobalValue *GV = GSDN->getGlobal();
2022
2023   // 64-bit SVR4 ABI code is always position-independent.
2024   // The actual address of the GlobalValue is stored in the TOC.
2025   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2026     setUsesTOCBasePtr(DAG);
2027     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2028     return getTOCEntry(DAG, DL, true, GA);
2029   }
2030
2031   unsigned MOHiFlag, MOLoFlag;
2032   bool isPIC =
2033       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2034
2035   if (isPIC && Subtarget.isSVR4ABI()) {
2036     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2037                                             GSDN->getOffset(),
2038                                             PPCII::MO_PIC_FLAG);
2039     return getTOCEntry(DAG, DL, false, GA);
2040   }
2041
2042   SDValue GAHi =
2043     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2044   SDValue GALo =
2045     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2046
2047   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2048
2049   // If the global reference is actually to a non-lazy-pointer, we have to do an
2050   // extra load to get the address of the global.
2051   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2052     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2053                       false, false, false, 0);
2054   return Ptr;
2055 }
2056
2057 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2058   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2059   SDLoc dl(Op);
2060
2061   if (Op.getValueType() == MVT::v2i64) {
2062     // When the operands themselves are v2i64 values, we need to do something
2063     // special because VSX has no underlying comparison operations for these.
2064     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2065       // Equality can be handled by casting to the legal type for Altivec
2066       // comparisons, everything else needs to be expanded.
2067       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2068         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2069                  DAG.getSetCC(dl, MVT::v4i32,
2070                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2071                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2072                    CC));
2073       }
2074
2075       return SDValue();
2076     }
2077
2078     // We handle most of these in the usual way.
2079     return Op;
2080   }
2081
2082   // If we're comparing for equality to zero, expose the fact that this is
2083   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2084   // fold the new nodes.
2085   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2086     if (C->isNullValue() && CC == ISD::SETEQ) {
2087       EVT VT = Op.getOperand(0).getValueType();
2088       SDValue Zext = Op.getOperand(0);
2089       if (VT.bitsLT(MVT::i32)) {
2090         VT = MVT::i32;
2091         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2092       }
2093       unsigned Log2b = Log2_32(VT.getSizeInBits());
2094       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2095       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2096                                 DAG.getConstant(Log2b, MVT::i32));
2097       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2098     }
2099     // Leave comparisons against 0 and -1 alone for now, since they're usually
2100     // optimized.  FIXME: revisit this when we can custom lower all setcc
2101     // optimizations.
2102     if (C->isAllOnesValue() || C->isNullValue())
2103       return SDValue();
2104   }
2105
2106   // If we have an integer seteq/setne, turn it into a compare against zero
2107   // by xor'ing the rhs with the lhs, which is faster than setting a
2108   // condition register, reading it back out, and masking the correct bit.  The
2109   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2110   // the result to other bit-twiddling opportunities.
2111   EVT LHSVT = Op.getOperand(0).getValueType();
2112   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2113     EVT VT = Op.getValueType();
2114     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2115                                 Op.getOperand(1));
2116     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
2117   }
2118   return SDValue();
2119 }
2120
2121 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2122                                       const PPCSubtarget &Subtarget) const {
2123   SDNode *Node = Op.getNode();
2124   EVT VT = Node->getValueType(0);
2125   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2126   SDValue InChain = Node->getOperand(0);
2127   SDValue VAListPtr = Node->getOperand(1);
2128   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2129   SDLoc dl(Node);
2130
2131   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2132
2133   // gpr_index
2134   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2135                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2136                                     false, false, false, 0);
2137   InChain = GprIndex.getValue(1);
2138
2139   if (VT == MVT::i64) {
2140     // Check if GprIndex is even
2141     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2142                                  DAG.getConstant(1, MVT::i32));
2143     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2144                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
2145     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2146                                           DAG.getConstant(1, MVT::i32));
2147     // Align GprIndex to be even if it isn't
2148     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2149                            GprIndex);
2150   }
2151
2152   // fpr index is 1 byte after gpr
2153   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2154                                DAG.getConstant(1, MVT::i32));
2155
2156   // fpr
2157   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2158                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2159                                     false, false, false, 0);
2160   InChain = FprIndex.getValue(1);
2161
2162   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2163                                        DAG.getConstant(8, MVT::i32));
2164
2165   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2166                                         DAG.getConstant(4, MVT::i32));
2167
2168   // areas
2169   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2170                                      MachinePointerInfo(), false, false,
2171                                      false, 0);
2172   InChain = OverflowArea.getValue(1);
2173
2174   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2175                                     MachinePointerInfo(), false, false,
2176                                     false, 0);
2177   InChain = RegSaveArea.getValue(1);
2178
2179   // select overflow_area if index > 8
2180   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2181                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
2182
2183   // adjustment constant gpr_index * 4/8
2184   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2185                                     VT.isInteger() ? GprIndex : FprIndex,
2186                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
2187                                                     MVT::i32));
2188
2189   // OurReg = RegSaveArea + RegConstant
2190   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2191                                RegConstant);
2192
2193   // Floating types are 32 bytes into RegSaveArea
2194   if (VT.isFloatingPoint())
2195     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2196                          DAG.getConstant(32, MVT::i32));
2197
2198   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2199   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2200                                    VT.isInteger() ? GprIndex : FprIndex,
2201                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
2202                                                    MVT::i32));
2203
2204   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2205                               VT.isInteger() ? VAListPtr : FprPtr,
2206                               MachinePointerInfo(SV),
2207                               MVT::i8, false, false, 0);
2208
2209   // determine if we should load from reg_save_area or overflow_area
2210   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2211
2212   // increase overflow_area by 4/8 if gpr/fpr > 8
2213   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2214                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2215                                           MVT::i32));
2216
2217   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2218                              OverflowAreaPlusN);
2219
2220   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2221                               OverflowAreaPtr,
2222                               MachinePointerInfo(),
2223                               MVT::i32, false, false, 0);
2224
2225   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2226                      false, false, false, 0);
2227 }
2228
2229 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2230                                        const PPCSubtarget &Subtarget) const {
2231   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2232
2233   // We have to copy the entire va_list struct:
2234   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2235   return DAG.getMemcpy(Op.getOperand(0), Op,
2236                        Op.getOperand(1), Op.getOperand(2),
2237                        DAG.getConstant(12, MVT::i32), 8, false, true,
2238                        MachinePointerInfo(), MachinePointerInfo());
2239 }
2240
2241 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2242                                                   SelectionDAG &DAG) const {
2243   return Op.getOperand(0);
2244 }
2245
2246 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2247                                                 SelectionDAG &DAG) const {
2248   SDValue Chain = Op.getOperand(0);
2249   SDValue Trmp = Op.getOperand(1); // trampoline
2250   SDValue FPtr = Op.getOperand(2); // nested function
2251   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2252   SDLoc dl(Op);
2253
2254   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2255   bool isPPC64 = (PtrVT == MVT::i64);
2256   Type *IntPtrTy =
2257     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2258                                                              *DAG.getContext());
2259
2260   TargetLowering::ArgListTy Args;
2261   TargetLowering::ArgListEntry Entry;
2262
2263   Entry.Ty = IntPtrTy;
2264   Entry.Node = Trmp; Args.push_back(Entry);
2265
2266   // TrampSize == (isPPC64 ? 48 : 40);
2267   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2268                                isPPC64 ? MVT::i64 : MVT::i32);
2269   Args.push_back(Entry);
2270
2271   Entry.Node = FPtr; Args.push_back(Entry);
2272   Entry.Node = Nest; Args.push_back(Entry);
2273
2274   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2275   TargetLowering::CallLoweringInfo CLI(DAG);
2276   CLI.setDebugLoc(dl).setChain(Chain)
2277     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2278                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2279                std::move(Args), 0);
2280
2281   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2282   return CallResult.second;
2283 }
2284
2285 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2286                                         const PPCSubtarget &Subtarget) const {
2287   MachineFunction &MF = DAG.getMachineFunction();
2288   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2289
2290   SDLoc dl(Op);
2291
2292   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2293     // vastart just stores the address of the VarArgsFrameIndex slot into the
2294     // memory location argument.
2295     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2296     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2297     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2298     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2299                         MachinePointerInfo(SV),
2300                         false, false, 0);
2301   }
2302
2303   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2304   // We suppose the given va_list is already allocated.
2305   //
2306   // typedef struct {
2307   //  char gpr;     /* index into the array of 8 GPRs
2308   //                 * stored in the register save area
2309   //                 * gpr=0 corresponds to r3,
2310   //                 * gpr=1 to r4, etc.
2311   //                 */
2312   //  char fpr;     /* index into the array of 8 FPRs
2313   //                 * stored in the register save area
2314   //                 * fpr=0 corresponds to f1,
2315   //                 * fpr=1 to f2, etc.
2316   //                 */
2317   //  char *overflow_arg_area;
2318   //                /* location on stack that holds
2319   //                 * the next overflow argument
2320   //                 */
2321   //  char *reg_save_area;
2322   //               /* where r3:r10 and f1:f8 (if saved)
2323   //                * are stored
2324   //                */
2325   // } va_list[1];
2326
2327
2328   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2329   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2330
2331
2332   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2333
2334   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2335                                             PtrVT);
2336   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2337                                  PtrVT);
2338
2339   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2340   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2341
2342   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2343   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2344
2345   uint64_t FPROffset = 1;
2346   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2347
2348   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2349
2350   // Store first byte : number of int regs
2351   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2352                                          Op.getOperand(1),
2353                                          MachinePointerInfo(SV),
2354                                          MVT::i8, false, false, 0);
2355   uint64_t nextOffset = FPROffset;
2356   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2357                                   ConstFPROffset);
2358
2359   // Store second byte : number of float regs
2360   SDValue secondStore =
2361     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2362                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2363                       false, false, 0);
2364   nextOffset += StackOffset;
2365   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2366
2367   // Store second word : arguments given on stack
2368   SDValue thirdStore =
2369     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2370                  MachinePointerInfo(SV, nextOffset),
2371                  false, false, 0);
2372   nextOffset += FrameOffset;
2373   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2374
2375   // Store third word : arguments given in registers
2376   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2377                       MachinePointerInfo(SV, nextOffset),
2378                       false, false, 0);
2379
2380 }
2381
2382 #include "PPCGenCallingConv.inc"
2383
2384 // Function whose sole purpose is to kill compiler warnings 
2385 // stemming from unused functions included from PPCGenCallingConv.inc.
2386 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2387   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2388 }
2389
2390 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2391                                       CCValAssign::LocInfo &LocInfo,
2392                                       ISD::ArgFlagsTy &ArgFlags,
2393                                       CCState &State) {
2394   return true;
2395 }
2396
2397 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2398                                              MVT &LocVT,
2399                                              CCValAssign::LocInfo &LocInfo,
2400                                              ISD::ArgFlagsTy &ArgFlags,
2401                                              CCState &State) {
2402   static const MCPhysReg ArgRegs[] = {
2403     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2404     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2405   };
2406   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2407
2408   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2409
2410   // Skip one register if the first unallocated register has an even register
2411   // number and there are still argument registers available which have not been
2412   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2413   // need to skip a register if RegNum is odd.
2414   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2415     State.AllocateReg(ArgRegs[RegNum]);
2416   }
2417
2418   // Always return false here, as this function only makes sure that the first
2419   // unallocated register has an odd register number and does not actually
2420   // allocate a register for the current argument.
2421   return false;
2422 }
2423
2424 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2425                                                MVT &LocVT,
2426                                                CCValAssign::LocInfo &LocInfo,
2427                                                ISD::ArgFlagsTy &ArgFlags,
2428                                                CCState &State) {
2429   static const MCPhysReg ArgRegs[] = {
2430     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2431     PPC::F8
2432   };
2433
2434   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2435
2436   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2437
2438   // If there is only one Floating-point register left we need to put both f64
2439   // values of a split ppc_fp128 value on the stack.
2440   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2441     State.AllocateReg(ArgRegs[RegNum]);
2442   }
2443
2444   // Always return false here, as this function only makes sure that the two f64
2445   // values a ppc_fp128 value is split into are both passed in registers or both
2446   // passed on the stack and does not actually allocate a register for the
2447   // current argument.
2448   return false;
2449 }
2450
2451 /// FPR - The set of FP registers that should be allocated for arguments,
2452 /// on Darwin.
2453 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2454                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2455                                 PPC::F11, PPC::F12, PPC::F13};
2456
2457 /// QFPR - The set of QPX registers that should be allocated for arguments.
2458 static const MCPhysReg QFPR[] = {
2459     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2460     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2461
2462 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2463 /// the stack.
2464 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2465                                        unsigned PtrByteSize) {
2466   unsigned ArgSize = ArgVT.getStoreSize();
2467   if (Flags.isByVal())
2468     ArgSize = Flags.getByValSize();
2469
2470   // Round up to multiples of the pointer size, except for array members,
2471   // which are always packed.
2472   if (!Flags.isInConsecutiveRegs())
2473     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2474
2475   return ArgSize;
2476 }
2477
2478 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2479 /// on the stack.
2480 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2481                                             ISD::ArgFlagsTy Flags,
2482                                             unsigned PtrByteSize) {
2483   unsigned Align = PtrByteSize;
2484
2485   // Altivec parameters are padded to a 16 byte boundary.
2486   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2487       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2488       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2489     Align = 16;
2490   // QPX vector types stored in double-precision are padded to a 32 byte
2491   // boundary.
2492   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2493     Align = 32;
2494
2495   // ByVal parameters are aligned as requested.
2496   if (Flags.isByVal()) {
2497     unsigned BVAlign = Flags.getByValAlign();
2498     if (BVAlign > PtrByteSize) {
2499       if (BVAlign % PtrByteSize != 0)
2500           llvm_unreachable(
2501             "ByVal alignment is not a multiple of the pointer size");
2502
2503       Align = BVAlign;
2504     }
2505   }
2506
2507   // Array members are always packed to their original alignment.
2508   if (Flags.isInConsecutiveRegs()) {
2509     // If the array member was split into multiple registers, the first
2510     // needs to be aligned to the size of the full type.  (Except for
2511     // ppcf128, which is only aligned as its f64 components.)
2512     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2513       Align = OrigVT.getStoreSize();
2514     else
2515       Align = ArgVT.getStoreSize();
2516   }
2517
2518   return Align;
2519 }
2520
2521 /// CalculateStackSlotUsed - Return whether this argument will use its
2522 /// stack slot (instead of being passed in registers).  ArgOffset,
2523 /// AvailableFPRs, and AvailableVRs must hold the current argument
2524 /// position, and will be updated to account for this argument.
2525 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2526                                    ISD::ArgFlagsTy Flags,
2527                                    unsigned PtrByteSize,
2528                                    unsigned LinkageSize,
2529                                    unsigned ParamAreaSize,
2530                                    unsigned &ArgOffset,
2531                                    unsigned &AvailableFPRs,
2532                                    unsigned &AvailableVRs, bool HasQPX) {
2533   bool UseMemory = false;
2534
2535   // Respect alignment of argument on the stack.
2536   unsigned Align =
2537     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2538   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2539   // If there's no space left in the argument save area, we must
2540   // use memory (this check also catches zero-sized arguments).
2541   if (ArgOffset >= LinkageSize + ParamAreaSize)
2542     UseMemory = true;
2543
2544   // Allocate argument on the stack.
2545   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2546   if (Flags.isInConsecutiveRegsLast())
2547     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2548   // If we overran the argument save area, we must use memory
2549   // (this check catches arguments passed partially in memory)
2550   if (ArgOffset > LinkageSize + ParamAreaSize)
2551     UseMemory = true;
2552
2553   // However, if the argument is actually passed in an FPR or a VR,
2554   // we don't use memory after all.
2555   if (!Flags.isByVal()) {
2556     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2557         // QPX registers overlap with the scalar FP registers.
2558         (HasQPX && (ArgVT == MVT::v4f32 ||
2559                     ArgVT == MVT::v4f64 ||
2560                     ArgVT == MVT::v4i1)))
2561       if (AvailableFPRs > 0) {
2562         --AvailableFPRs;
2563         return false;
2564       }
2565     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2566         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2567         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2568       if (AvailableVRs > 0) {
2569         --AvailableVRs;
2570         return false;
2571       }
2572   }
2573
2574   return UseMemory;
2575 }
2576
2577 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2578 /// ensure minimum alignment required for target.
2579 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2580                                      unsigned NumBytes) {
2581   unsigned TargetAlign = Lowering->getStackAlignment();
2582   unsigned AlignMask = TargetAlign - 1;
2583   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2584   return NumBytes;
2585 }
2586
2587 SDValue
2588 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2589                                         CallingConv::ID CallConv, bool isVarArg,
2590                                         const SmallVectorImpl<ISD::InputArg>
2591                                           &Ins,
2592                                         SDLoc dl, SelectionDAG &DAG,
2593                                         SmallVectorImpl<SDValue> &InVals)
2594                                           const {
2595   if (Subtarget.isSVR4ABI()) {
2596     if (Subtarget.isPPC64())
2597       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2598                                          dl, DAG, InVals);
2599     else
2600       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2601                                          dl, DAG, InVals);
2602   } else {
2603     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2604                                        dl, DAG, InVals);
2605   }
2606 }
2607
2608 SDValue
2609 PPCTargetLowering::LowerFormalArguments_32SVR4(
2610                                       SDValue Chain,
2611                                       CallingConv::ID CallConv, bool isVarArg,
2612                                       const SmallVectorImpl<ISD::InputArg>
2613                                         &Ins,
2614                                       SDLoc dl, SelectionDAG &DAG,
2615                                       SmallVectorImpl<SDValue> &InVals) const {
2616
2617   // 32-bit SVR4 ABI Stack Frame Layout:
2618   //              +-----------------------------------+
2619   //        +-->  |            Back chain             |
2620   //        |     +-----------------------------------+
2621   //        |     | Floating-point register save area |
2622   //        |     +-----------------------------------+
2623   //        |     |    General register save area     |
2624   //        |     +-----------------------------------+
2625   //        |     |          CR save word             |
2626   //        |     +-----------------------------------+
2627   //        |     |         VRSAVE save word          |
2628   //        |     +-----------------------------------+
2629   //        |     |         Alignment padding         |
2630   //        |     +-----------------------------------+
2631   //        |     |     Vector register save area     |
2632   //        |     +-----------------------------------+
2633   //        |     |       Local variable space        |
2634   //        |     +-----------------------------------+
2635   //        |     |        Parameter list area        |
2636   //        |     +-----------------------------------+
2637   //        |     |           LR save word            |
2638   //        |     +-----------------------------------+
2639   // SP-->  +---  |            Back chain             |
2640   //              +-----------------------------------+
2641   //
2642   // Specifications:
2643   //   System V Application Binary Interface PowerPC Processor Supplement
2644   //   AltiVec Technology Programming Interface Manual
2645
2646   MachineFunction &MF = DAG.getMachineFunction();
2647   MachineFrameInfo *MFI = MF.getFrameInfo();
2648   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2649
2650   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2651   // Potential tail calls could cause overwriting of argument stack slots.
2652   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2653                        (CallConv == CallingConv::Fast));
2654   unsigned PtrByteSize = 4;
2655
2656   // Assign locations to all of the incoming arguments.
2657   SmallVector<CCValAssign, 16> ArgLocs;
2658   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2659                  *DAG.getContext());
2660
2661   // Reserve space for the linkage area on the stack.
2662   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2663   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2664
2665   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2666
2667   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2668     CCValAssign &VA = ArgLocs[i];
2669
2670     // Arguments stored in registers.
2671     if (VA.isRegLoc()) {
2672       const TargetRegisterClass *RC;
2673       EVT ValVT = VA.getValVT();
2674
2675       switch (ValVT.getSimpleVT().SimpleTy) {
2676         default:
2677           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2678         case MVT::i1:
2679         case MVT::i32:
2680           RC = &PPC::GPRCRegClass;
2681           break;
2682         case MVT::f32:
2683           RC = &PPC::F4RCRegClass;
2684           break;
2685         case MVT::f64:
2686           if (Subtarget.hasVSX())
2687             RC = &PPC::VSFRCRegClass;
2688           else
2689             RC = &PPC::F8RCRegClass;
2690           break;
2691         case MVT::v16i8:
2692         case MVT::v8i16:
2693         case MVT::v4i32:
2694           RC = &PPC::VRRCRegClass;
2695           break;
2696         case MVT::v4f32:
2697           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2698           break;
2699         case MVT::v2f64:
2700         case MVT::v2i64:
2701           RC = &PPC::VSHRCRegClass;
2702           break;
2703         case MVT::v4f64:
2704           RC = &PPC::QFRCRegClass;
2705           break;
2706         case MVT::v4i1:
2707           RC = &PPC::QBRCRegClass;
2708           break;
2709       }
2710
2711       // Transform the arguments stored in physical registers into virtual ones.
2712       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2713       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2714                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2715
2716       if (ValVT == MVT::i1)
2717         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2718
2719       InVals.push_back(ArgValue);
2720     } else {
2721       // Argument stored in memory.
2722       assert(VA.isMemLoc());
2723
2724       unsigned ArgSize = VA.getLocVT().getStoreSize();
2725       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2726                                       isImmutable);
2727
2728       // Create load nodes to retrieve arguments from the stack.
2729       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2730       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2731                                    MachinePointerInfo(),
2732                                    false, false, false, 0));
2733     }
2734   }
2735
2736   // Assign locations to all of the incoming aggregate by value arguments.
2737   // Aggregates passed by value are stored in the local variable space of the
2738   // caller's stack frame, right above the parameter list area.
2739   SmallVector<CCValAssign, 16> ByValArgLocs;
2740   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2741                       ByValArgLocs, *DAG.getContext());
2742
2743   // Reserve stack space for the allocations in CCInfo.
2744   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2745
2746   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2747
2748   // Area that is at least reserved in the caller of this function.
2749   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2750   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2751
2752   // Set the size that is at least reserved in caller of this function.  Tail
2753   // call optimized function's reserved stack space needs to be aligned so that
2754   // taking the difference between two stack areas will result in an aligned
2755   // stack.
2756   MinReservedArea =
2757       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2758   FuncInfo->setMinReservedArea(MinReservedArea);
2759
2760   SmallVector<SDValue, 8> MemOps;
2761
2762   // If the function takes variable number of arguments, make a frame index for
2763   // the start of the first vararg value... for expansion of llvm.va_start.
2764   if (isVarArg) {
2765     static const MCPhysReg GPArgRegs[] = {
2766       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2767       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2768     };
2769     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2770
2771     static const MCPhysReg FPArgRegs[] = {
2772       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2773       PPC::F8
2774     };
2775     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2776     if (DisablePPCFloatInVariadic)
2777       NumFPArgRegs = 0;
2778
2779     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2780     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2781
2782     // Make room for NumGPArgRegs and NumFPArgRegs.
2783     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2784                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2785
2786     FuncInfo->setVarArgsStackOffset(
2787       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2788                              CCInfo.getNextStackOffset(), true));
2789
2790     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2791     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2792
2793     // The fixed integer arguments of a variadic function are stored to the
2794     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2795     // the result of va_next.
2796     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2797       // Get an existing live-in vreg, or add a new one.
2798       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2799       if (!VReg)
2800         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2801
2802       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2803       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2804                                    MachinePointerInfo(), false, false, 0);
2805       MemOps.push_back(Store);
2806       // Increment the address by four for the next argument to store
2807       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2808       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2809     }
2810
2811     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2812     // is set.
2813     // The double arguments are stored to the VarArgsFrameIndex
2814     // on the stack.
2815     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2816       // Get an existing live-in vreg, or add a new one.
2817       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2818       if (!VReg)
2819         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2820
2821       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2822       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2823                                    MachinePointerInfo(), false, false, 0);
2824       MemOps.push_back(Store);
2825       // Increment the address by eight for the next argument to store
2826       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2827                                          PtrVT);
2828       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2829     }
2830   }
2831
2832   if (!MemOps.empty())
2833     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2834
2835   return Chain;
2836 }
2837
2838 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2839 // value to MVT::i64 and then truncate to the correct register size.
2840 SDValue
2841 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2842                                      SelectionDAG &DAG, SDValue ArgVal,
2843                                      SDLoc dl) const {
2844   if (Flags.isSExt())
2845     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2846                          DAG.getValueType(ObjectVT));
2847   else if (Flags.isZExt())
2848     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2849                          DAG.getValueType(ObjectVT));
2850
2851   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2852 }
2853
2854 SDValue
2855 PPCTargetLowering::LowerFormalArguments_64SVR4(
2856                                       SDValue Chain,
2857                                       CallingConv::ID CallConv, bool isVarArg,
2858                                       const SmallVectorImpl<ISD::InputArg>
2859                                         &Ins,
2860                                       SDLoc dl, SelectionDAG &DAG,
2861                                       SmallVectorImpl<SDValue> &InVals) const {
2862   // TODO: add description of PPC stack frame format, or at least some docs.
2863   //
2864   bool isELFv2ABI = Subtarget.isELFv2ABI();
2865   bool isLittleEndian = Subtarget.isLittleEndian();
2866   MachineFunction &MF = DAG.getMachineFunction();
2867   MachineFrameInfo *MFI = MF.getFrameInfo();
2868   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2869
2870   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2871          "fastcc not supported on varargs functions");
2872
2873   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2874   // Potential tail calls could cause overwriting of argument stack slots.
2875   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2876                        (CallConv == CallingConv::Fast));
2877   unsigned PtrByteSize = 8;
2878   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2879
2880   static const MCPhysReg GPR[] = {
2881     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2882     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2883   };
2884   static const MCPhysReg VR[] = {
2885     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2886     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2887   };
2888   static const MCPhysReg VSRH[] = {
2889     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2890     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2891   };
2892
2893   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2894   const unsigned Num_FPR_Regs = 13;
2895   const unsigned Num_VR_Regs  = array_lengthof(VR);
2896   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2897
2898   // Do a first pass over the arguments to determine whether the ABI
2899   // guarantees that our caller has allocated the parameter save area
2900   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2901   // in the ELFv2 ABI, it is true if this is a vararg function or if
2902   // any parameter is located in a stack slot.
2903
2904   bool HasParameterArea = !isELFv2ABI || isVarArg;
2905   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2906   unsigned NumBytes = LinkageSize;
2907   unsigned AvailableFPRs = Num_FPR_Regs;
2908   unsigned AvailableVRs = Num_VR_Regs;
2909   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2910     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2911                                PtrByteSize, LinkageSize, ParamAreaSize,
2912                                NumBytes, AvailableFPRs, AvailableVRs,
2913                                Subtarget.hasQPX()))
2914       HasParameterArea = true;
2915
2916   // Add DAG nodes to load the arguments or copy them out of registers.  On
2917   // entry to a function on PPC, the arguments start after the linkage area,
2918   // although the first ones are often in registers.
2919
2920   unsigned ArgOffset = LinkageSize;
2921   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2922   unsigned &QFPR_idx = FPR_idx;
2923   SmallVector<SDValue, 8> MemOps;
2924   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2925   unsigned CurArgIdx = 0;
2926   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2927     SDValue ArgVal;
2928     bool needsLoad = false;
2929     EVT ObjectVT = Ins[ArgNo].VT;
2930     EVT OrigVT = Ins[ArgNo].ArgVT;
2931     unsigned ObjSize = ObjectVT.getStoreSize();
2932     unsigned ArgSize = ObjSize;
2933     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2934     if (Ins[ArgNo].isOrigArg()) {
2935       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2936       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2937     }
2938     // We re-align the argument offset for each argument, except when using the
2939     // fast calling convention, when we need to make sure we do that only when
2940     // we'll actually use a stack slot.
2941     unsigned CurArgOffset, Align;
2942     auto ComputeArgOffset = [&]() {
2943       /* Respect alignment of argument on the stack.  */
2944       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2945       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2946       CurArgOffset = ArgOffset;
2947     };
2948
2949     if (CallConv != CallingConv::Fast) {
2950       ComputeArgOffset();
2951
2952       /* Compute GPR index associated with argument offset.  */
2953       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2954       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2955     }
2956
2957     // FIXME the codegen can be much improved in some cases.
2958     // We do not have to keep everything in memory.
2959     if (Flags.isByVal()) {
2960       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
2961
2962       if (CallConv == CallingConv::Fast)
2963         ComputeArgOffset();
2964
2965       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2966       ObjSize = Flags.getByValSize();
2967       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2968       // Empty aggregate parameters do not take up registers.  Examples:
2969       //   struct { } a;
2970       //   union  { } b;
2971       //   int c[0];
2972       // etc.  However, we have to provide a place-holder in InVals, so
2973       // pretend we have an 8-byte item at the current address for that
2974       // purpose.
2975       if (!ObjSize) {
2976         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2977         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2978         InVals.push_back(FIN);
2979         continue;
2980       }
2981
2982       // Create a stack object covering all stack doublewords occupied
2983       // by the argument.  If the argument is (fully or partially) on
2984       // the stack, or if the argument is fully in registers but the
2985       // caller has allocated the parameter save anyway, we can refer
2986       // directly to the caller's stack frame.  Otherwise, create a
2987       // local copy in our own frame.
2988       int FI;
2989       if (HasParameterArea ||
2990           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2991         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2992       else
2993         FI = MFI->CreateStackObject(ArgSize, Align, false);
2994       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2995
2996       // Handle aggregates smaller than 8 bytes.
2997       if (ObjSize < PtrByteSize) {
2998         // The value of the object is its address, which differs from the
2999         // address of the enclosing doubleword on big-endian systems.
3000         SDValue Arg = FIN;
3001         if (!isLittleEndian) {
3002           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
3003           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3004         }
3005         InVals.push_back(Arg);
3006
3007         if (GPR_idx != Num_GPR_Regs) {
3008           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3009           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3010           SDValue Store;
3011
3012           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3013             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3014                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3015             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3016                                       MachinePointerInfo(FuncArg),
3017                                       ObjType, false, false, 0);
3018           } else {
3019             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3020             // store the whole register as-is to the parameter save area
3021             // slot.
3022             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3023                                  MachinePointerInfo(FuncArg),
3024                                  false, false, 0);
3025           }
3026
3027           MemOps.push_back(Store);
3028         }
3029         // Whether we copied from a register or not, advance the offset
3030         // into the parameter save area by a full doubleword.
3031         ArgOffset += PtrByteSize;
3032         continue;
3033       }
3034
3035       // The value of the object is its address, which is the address of
3036       // its first stack doubleword.
3037       InVals.push_back(FIN);
3038
3039       // Store whatever pieces of the object are in registers to memory.
3040       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3041         if (GPR_idx == Num_GPR_Regs)
3042           break;
3043
3044         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3045         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3046         SDValue Addr = FIN;
3047         if (j) {
3048           SDValue Off = DAG.getConstant(j, PtrVT);
3049           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3050         }
3051         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3052                                      MachinePointerInfo(FuncArg, j),
3053                                      false, false, 0);
3054         MemOps.push_back(Store);
3055         ++GPR_idx;
3056       }
3057       ArgOffset += ArgSize;
3058       continue;
3059     }
3060
3061     switch (ObjectVT.getSimpleVT().SimpleTy) {
3062     default: llvm_unreachable("Unhandled argument type!");
3063     case MVT::i1:
3064     case MVT::i32:
3065     case MVT::i64:
3066       // These can be scalar arguments or elements of an integer array type
3067       // passed directly.  Clang may use those instead of "byval" aggregate
3068       // types to avoid forcing arguments to memory unnecessarily.
3069       if (GPR_idx != Num_GPR_Regs) {
3070         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3071         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3072
3073         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3074           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3075           // value to MVT::i64 and then truncate to the correct register size.
3076           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3077       } else {
3078         if (CallConv == CallingConv::Fast)
3079           ComputeArgOffset();
3080
3081         needsLoad = true;
3082         ArgSize = PtrByteSize;
3083       }
3084       if (CallConv != CallingConv::Fast || needsLoad)
3085         ArgOffset += 8;
3086       break;
3087
3088     case MVT::f32:
3089     case MVT::f64:
3090       // These can be scalar arguments or elements of a float array type
3091       // passed directly.  The latter are used to implement ELFv2 homogenous
3092       // float aggregates.
3093       if (FPR_idx != Num_FPR_Regs) {
3094         unsigned VReg;
3095
3096         if (ObjectVT == MVT::f32)
3097           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3098         else
3099           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3100                                                 ? &PPC::VSFRCRegClass
3101                                                 : &PPC::F8RCRegClass);
3102
3103         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3104         ++FPR_idx;
3105       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3106         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3107         // once we support fp <-> gpr moves.
3108
3109         // This can only ever happen in the presence of f32 array types,
3110         // since otherwise we never run out of FPRs before running out
3111         // of GPRs.
3112         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3113         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3114
3115         if (ObjectVT == MVT::f32) {
3116           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3117             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3118                                  DAG.getConstant(32, MVT::i32));
3119           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3120         }
3121
3122         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3123       } else {
3124         if (CallConv == CallingConv::Fast)
3125           ComputeArgOffset();
3126
3127         needsLoad = true;
3128       }
3129
3130       // When passing an array of floats, the array occupies consecutive
3131       // space in the argument area; only round up to the next doubleword
3132       // at the end of the array.  Otherwise, each float takes 8 bytes.
3133       if (CallConv != CallingConv::Fast || needsLoad) {
3134         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3135         ArgOffset += ArgSize;
3136         if (Flags.isInConsecutiveRegsLast())
3137           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3138       }
3139       break;
3140     case MVT::v4f32:
3141     case MVT::v4i32:
3142     case MVT::v8i16:
3143     case MVT::v16i8:
3144     case MVT::v2f64:
3145     case MVT::v2i64:
3146       if (!Subtarget.hasQPX()) {
3147       // These can be scalar arguments or elements of a vector array type
3148       // passed directly.  The latter are used to implement ELFv2 homogenous
3149       // vector aggregates.
3150       if (VR_idx != Num_VR_Regs) {
3151         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3152                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3153                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3154         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3155         ++VR_idx;
3156       } else {
3157         if (CallConv == CallingConv::Fast)
3158           ComputeArgOffset();
3159
3160         needsLoad = true;
3161       }
3162       if (CallConv != CallingConv::Fast || needsLoad)
3163         ArgOffset += 16;
3164       break;
3165       } // not QPX
3166
3167       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3168              "Invalid QPX parameter type");
3169       /* fall through */
3170
3171     case MVT::v4f64:
3172     case MVT::v4i1:
3173       // QPX vectors are treated like their scalar floating-point subregisters
3174       // (except that they're larger).
3175       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3176       if (QFPR_idx != Num_QFPR_Regs) {
3177         const TargetRegisterClass *RC;
3178         switch (ObjectVT.getSimpleVT().SimpleTy) {
3179         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3180         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3181         default:         RC = &PPC::QBRCRegClass; break;
3182         }
3183
3184         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3185         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3186         ++QFPR_idx;
3187       } else {
3188         if (CallConv == CallingConv::Fast)
3189           ComputeArgOffset();
3190         needsLoad = true;
3191       }
3192       if (CallConv != CallingConv::Fast || needsLoad)
3193         ArgOffset += Sz;
3194       break;
3195     }
3196
3197     // We need to load the argument to a virtual register if we determined
3198     // above that we ran out of physical registers of the appropriate type.
3199     if (needsLoad) {
3200       if (ObjSize < ArgSize && !isLittleEndian)
3201         CurArgOffset += ArgSize - ObjSize;
3202       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3203       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3204       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3205                            false, false, false, 0);
3206     }
3207
3208     InVals.push_back(ArgVal);
3209   }
3210
3211   // Area that is at least reserved in the caller of this function.
3212   unsigned MinReservedArea;
3213   if (HasParameterArea)
3214     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3215   else
3216     MinReservedArea = LinkageSize;
3217
3218   // Set the size that is at least reserved in caller of this function.  Tail
3219   // call optimized functions' reserved stack space needs to be aligned so that
3220   // taking the difference between two stack areas will result in an aligned
3221   // stack.
3222   MinReservedArea =
3223       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3224   FuncInfo->setMinReservedArea(MinReservedArea);
3225
3226   // If the function takes variable number of arguments, make a frame index for
3227   // the start of the first vararg value... for expansion of llvm.va_start.
3228   if (isVarArg) {
3229     int Depth = ArgOffset;
3230
3231     FuncInfo->setVarArgsFrameIndex(
3232       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3233     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3234
3235     // If this function is vararg, store any remaining integer argument regs
3236     // to their spots on the stack so that they may be loaded by deferencing the
3237     // result of va_next.
3238     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3239          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3240       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3241       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3242       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3243                                    MachinePointerInfo(), false, false, 0);
3244       MemOps.push_back(Store);
3245       // Increment the address by four for the next argument to store
3246       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
3247       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3248     }
3249   }
3250
3251   if (!MemOps.empty())
3252     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3253
3254   return Chain;
3255 }
3256
3257 SDValue
3258 PPCTargetLowering::LowerFormalArguments_Darwin(
3259                                       SDValue Chain,
3260                                       CallingConv::ID CallConv, bool isVarArg,
3261                                       const SmallVectorImpl<ISD::InputArg>
3262                                         &Ins,
3263                                       SDLoc dl, SelectionDAG &DAG,
3264                                       SmallVectorImpl<SDValue> &InVals) const {
3265   // TODO: add description of PPC stack frame format, or at least some docs.
3266   //
3267   MachineFunction &MF = DAG.getMachineFunction();
3268   MachineFrameInfo *MFI = MF.getFrameInfo();
3269   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3270
3271   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3272   bool isPPC64 = PtrVT == MVT::i64;
3273   // Potential tail calls could cause overwriting of argument stack slots.
3274   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3275                        (CallConv == CallingConv::Fast));
3276   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3277   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3278   unsigned ArgOffset = LinkageSize;
3279   // Area that is at least reserved in caller of this function.
3280   unsigned MinReservedArea = ArgOffset;
3281
3282   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3283     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3284     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3285   };
3286   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3287     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3288     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3289   };
3290   static const MCPhysReg VR[] = {
3291     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3292     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3293   };
3294
3295   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3296   const unsigned Num_FPR_Regs = 13;
3297   const unsigned Num_VR_Regs  = array_lengthof( VR);
3298
3299   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3300
3301   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3302
3303   // In 32-bit non-varargs functions, the stack space for vectors is after the
3304   // stack space for non-vectors.  We do not use this space unless we have
3305   // too many vectors to fit in registers, something that only occurs in
3306   // constructed examples:), but we have to walk the arglist to figure
3307   // that out...for the pathological case, compute VecArgOffset as the
3308   // start of the vector parameter area.  Computing VecArgOffset is the
3309   // entire point of the following loop.
3310   unsigned VecArgOffset = ArgOffset;
3311   if (!isVarArg && !isPPC64) {
3312     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3313          ++ArgNo) {
3314       EVT ObjectVT = Ins[ArgNo].VT;
3315       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3316
3317       if (Flags.isByVal()) {
3318         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3319         unsigned ObjSize = Flags.getByValSize();
3320         unsigned ArgSize =
3321                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3322         VecArgOffset += ArgSize;
3323         continue;
3324       }
3325
3326       switch(ObjectVT.getSimpleVT().SimpleTy) {
3327       default: llvm_unreachable("Unhandled argument type!");
3328       case MVT::i1:
3329       case MVT::i32:
3330       case MVT::f32:
3331         VecArgOffset += 4;
3332         break;
3333       case MVT::i64:  // PPC64
3334       case MVT::f64:
3335         // FIXME: We are guaranteed to be !isPPC64 at this point.
3336         // Does MVT::i64 apply?
3337         VecArgOffset += 8;
3338         break;
3339       case MVT::v4f32:
3340       case MVT::v4i32:
3341       case MVT::v8i16:
3342       case MVT::v16i8:
3343         // Nothing to do, we're only looking at Nonvector args here.
3344         break;
3345       }
3346     }
3347   }
3348   // We've found where the vector parameter area in memory is.  Skip the
3349   // first 12 parameters; these don't use that memory.
3350   VecArgOffset = ((VecArgOffset+15)/16)*16;
3351   VecArgOffset += 12*16;
3352
3353   // Add DAG nodes to load the arguments or copy them out of registers.  On
3354   // entry to a function on PPC, the arguments start after the linkage area,
3355   // although the first ones are often in registers.
3356
3357   SmallVector<SDValue, 8> MemOps;
3358   unsigned nAltivecParamsAtEnd = 0;
3359   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3360   unsigned CurArgIdx = 0;
3361   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3362     SDValue ArgVal;
3363     bool needsLoad = false;
3364     EVT ObjectVT = Ins[ArgNo].VT;
3365     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3366     unsigned ArgSize = ObjSize;
3367     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3368     if (Ins[ArgNo].isOrigArg()) {
3369       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3370       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3371     }
3372     unsigned CurArgOffset = ArgOffset;
3373
3374     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3375     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3376         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3377       if (isVarArg || isPPC64) {
3378         MinReservedArea = ((MinReservedArea+15)/16)*16;
3379         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3380                                                   Flags,
3381                                                   PtrByteSize);
3382       } else  nAltivecParamsAtEnd++;
3383     } else
3384       // Calculate min reserved area.
3385       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3386                                                 Flags,
3387                                                 PtrByteSize);
3388
3389     // FIXME the codegen can be much improved in some cases.
3390     // We do not have to keep everything in memory.
3391     if (Flags.isByVal()) {
3392       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3393
3394       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3395       ObjSize = Flags.getByValSize();
3396       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3397       // Objects of size 1 and 2 are right justified, everything else is
3398       // left justified.  This means the memory address is adjusted forwards.
3399       if (ObjSize==1 || ObjSize==2) {
3400         CurArgOffset = CurArgOffset + (4 - ObjSize);
3401       }
3402       // The value of the object is its address.
3403       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3404       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3405       InVals.push_back(FIN);
3406       if (ObjSize==1 || ObjSize==2) {
3407         if (GPR_idx != Num_GPR_Regs) {
3408           unsigned VReg;
3409           if (isPPC64)
3410             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3411           else
3412             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3413           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3414           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3415           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3416                                             MachinePointerInfo(FuncArg),
3417                                             ObjType, false, false, 0);
3418           MemOps.push_back(Store);
3419           ++GPR_idx;
3420         }
3421
3422         ArgOffset += PtrByteSize;
3423
3424         continue;
3425       }
3426       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3427         // Store whatever pieces of the object are in registers
3428         // to memory.  ArgOffset will be the address of the beginning
3429         // of the object.
3430         if (GPR_idx != Num_GPR_Regs) {
3431           unsigned VReg;
3432           if (isPPC64)
3433             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3434           else
3435             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3436           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3437           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3438           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3439           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3440                                        MachinePointerInfo(FuncArg, j),
3441                                        false, false, 0);
3442           MemOps.push_back(Store);
3443           ++GPR_idx;
3444           ArgOffset += PtrByteSize;
3445         } else {
3446           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3447           break;
3448         }
3449       }
3450       continue;
3451     }
3452
3453     switch (ObjectVT.getSimpleVT().SimpleTy) {
3454     default: llvm_unreachable("Unhandled argument type!");
3455     case MVT::i1:
3456     case MVT::i32:
3457       if (!isPPC64) {
3458         if (GPR_idx != Num_GPR_Regs) {
3459           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3460           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3461
3462           if (ObjectVT == MVT::i1)
3463             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3464
3465           ++GPR_idx;
3466         } else {
3467           needsLoad = true;
3468           ArgSize = PtrByteSize;
3469         }
3470         // All int arguments reserve stack space in the Darwin ABI.
3471         ArgOffset += PtrByteSize;
3472         break;
3473       }
3474       // FALLTHROUGH
3475     case MVT::i64:  // PPC64
3476       if (GPR_idx != Num_GPR_Regs) {
3477         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3478         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3479
3480         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3481           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3482           // value to MVT::i64 and then truncate to the correct register size.
3483           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3484
3485         ++GPR_idx;
3486       } else {
3487         needsLoad = true;
3488         ArgSize = PtrByteSize;
3489       }
3490       // All int arguments reserve stack space in the Darwin ABI.
3491       ArgOffset += 8;
3492       break;
3493
3494     case MVT::f32:
3495     case MVT::f64:
3496       // Every 4 bytes of argument space consumes one of the GPRs available for
3497       // argument passing.
3498       if (GPR_idx != Num_GPR_Regs) {
3499         ++GPR_idx;
3500         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3501           ++GPR_idx;
3502       }
3503       if (FPR_idx != Num_FPR_Regs) {
3504         unsigned VReg;
3505
3506         if (ObjectVT == MVT::f32)
3507           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3508         else
3509           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3510
3511         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3512         ++FPR_idx;
3513       } else {
3514         needsLoad = true;
3515       }
3516
3517       // All FP arguments reserve stack space in the Darwin ABI.
3518       ArgOffset += isPPC64 ? 8 : ObjSize;
3519       break;
3520     case MVT::v4f32:
3521     case MVT::v4i32:
3522     case MVT::v8i16:
3523     case MVT::v16i8:
3524       // Note that vector arguments in registers don't reserve stack space,
3525       // except in varargs functions.
3526       if (VR_idx != Num_VR_Regs) {
3527         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3528         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3529         if (isVarArg) {
3530           while ((ArgOffset % 16) != 0) {
3531             ArgOffset += PtrByteSize;
3532             if (GPR_idx != Num_GPR_Regs)
3533               GPR_idx++;
3534           }
3535           ArgOffset += 16;
3536           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3537         }
3538         ++VR_idx;
3539       } else {
3540         if (!isVarArg && !isPPC64) {
3541           // Vectors go after all the nonvectors.
3542           CurArgOffset = VecArgOffset;
3543           VecArgOffset += 16;
3544         } else {
3545           // Vectors are aligned.
3546           ArgOffset = ((ArgOffset+15)/16)*16;
3547           CurArgOffset = ArgOffset;
3548           ArgOffset += 16;
3549         }
3550         needsLoad = true;
3551       }
3552       break;
3553     }
3554
3555     // We need to load the argument to a virtual register if we determined above
3556     // that we ran out of physical registers of the appropriate type.
3557     if (needsLoad) {
3558       int FI = MFI->CreateFixedObject(ObjSize,
3559                                       CurArgOffset + (ArgSize - ObjSize),
3560                                       isImmutable);
3561       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3562       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3563                            false, false, false, 0);
3564     }
3565
3566     InVals.push_back(ArgVal);
3567   }
3568
3569   // Allow for Altivec parameters at the end, if needed.
3570   if (nAltivecParamsAtEnd) {
3571     MinReservedArea = ((MinReservedArea+15)/16)*16;
3572     MinReservedArea += 16*nAltivecParamsAtEnd;
3573   }
3574
3575   // Area that is at least reserved in the caller of this function.
3576   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3577
3578   // Set the size that is at least reserved in caller of this function.  Tail
3579   // call optimized functions' reserved stack space needs to be aligned so that
3580   // taking the difference between two stack areas will result in an aligned
3581   // stack.
3582   MinReservedArea =
3583       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3584   FuncInfo->setMinReservedArea(MinReservedArea);
3585
3586   // If the function takes variable number of arguments, make a frame index for
3587   // the start of the first vararg value... for expansion of llvm.va_start.
3588   if (isVarArg) {
3589     int Depth = ArgOffset;
3590
3591     FuncInfo->setVarArgsFrameIndex(
3592       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3593                              Depth, true));
3594     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3595
3596     // If this function is vararg, store any remaining integer argument regs
3597     // to their spots on the stack so that they may be loaded by deferencing the
3598     // result of va_next.
3599     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3600       unsigned VReg;
3601
3602       if (isPPC64)
3603         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3604       else
3605         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3606
3607       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3608       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3609                                    MachinePointerInfo(), false, false, 0);
3610       MemOps.push_back(Store);
3611       // Increment the address by four for the next argument to store
3612       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3613       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3614     }
3615   }
3616
3617   if (!MemOps.empty())
3618     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3619
3620   return Chain;
3621 }
3622
3623 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3624 /// adjusted to accommodate the arguments for the tailcall.
3625 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3626                                    unsigned ParamSize) {
3627
3628   if (!isTailCall) return 0;
3629
3630   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3631   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3632   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3633   // Remember only if the new adjustement is bigger.
3634   if (SPDiff < FI->getTailCallSPDelta())
3635     FI->setTailCallSPDelta(SPDiff);
3636
3637   return SPDiff;
3638 }
3639
3640 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3641 /// for tail call optimization. Targets which want to do tail call
3642 /// optimization should implement this function.
3643 bool
3644 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3645                                                      CallingConv::ID CalleeCC,
3646                                                      bool isVarArg,
3647                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3648                                                      SelectionDAG& DAG) const {
3649   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3650     return false;
3651
3652   // Variable argument functions are not supported.
3653   if (isVarArg)
3654     return false;
3655
3656   MachineFunction &MF = DAG.getMachineFunction();
3657   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3658   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3659     // Functions containing by val parameters are not supported.
3660     for (unsigned i = 0; i != Ins.size(); i++) {
3661        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3662        if (Flags.isByVal()) return false;
3663     }
3664
3665     // Non-PIC/GOT tail calls are supported.
3666     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3667       return true;
3668
3669     // At the moment we can only do local tail calls (in same module, hidden
3670     // or protected) if we are generating PIC.
3671     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3672       return G->getGlobal()->hasHiddenVisibility()
3673           || G->getGlobal()->hasProtectedVisibility();
3674   }
3675
3676   return false;
3677 }
3678
3679 /// isCallCompatibleAddress - Return the immediate to use if the specified
3680 /// 32-bit value is representable in the immediate field of a BxA instruction.
3681 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3682   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3683   if (!C) return nullptr;
3684
3685   int Addr = C->getZExtValue();
3686   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3687       SignExtend32<26>(Addr) != Addr)
3688     return nullptr;  // Top 6 bits have to be sext of immediate.
3689
3690   return DAG.getConstant((int)C->getZExtValue() >> 2,
3691                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3692 }
3693
3694 namespace {
3695
3696 struct TailCallArgumentInfo {
3697   SDValue Arg;
3698   SDValue FrameIdxOp;
3699   int       FrameIdx;
3700
3701   TailCallArgumentInfo() : FrameIdx(0) {}
3702 };
3703
3704 }
3705
3706 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3707 static void
3708 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3709                                            SDValue Chain,
3710                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3711                    SmallVectorImpl<SDValue> &MemOpChains,
3712                    SDLoc dl) {
3713   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3714     SDValue Arg = TailCallArgs[i].Arg;
3715     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3716     int FI = TailCallArgs[i].FrameIdx;
3717     // Store relative to framepointer.
3718     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3719                                        MachinePointerInfo::getFixedStack(FI),
3720                                        false, false, 0));
3721   }
3722 }
3723
3724 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3725 /// the appropriate stack slot for the tail call optimized function call.
3726 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3727                                                MachineFunction &MF,
3728                                                SDValue Chain,
3729                                                SDValue OldRetAddr,
3730                                                SDValue OldFP,
3731                                                int SPDiff,
3732                                                bool isPPC64,
3733                                                bool isDarwinABI,
3734                                                SDLoc dl) {
3735   if (SPDiff) {
3736     // Calculate the new stack slot for the return address.
3737     int SlotSize = isPPC64 ? 8 : 4;
3738     const PPCFrameLowering *FL =
3739         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3740     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3741     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3742                                                           NewRetAddrLoc, true);
3743     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3744     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3745     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3746                          MachinePointerInfo::getFixedStack(NewRetAddr),
3747                          false, false, 0);
3748
3749     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3750     // slot as the FP is never overwritten.
3751     if (isDarwinABI) {
3752       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3753       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3754                                                           true);
3755       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3756       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3757                            MachinePointerInfo::getFixedStack(NewFPIdx),
3758                            false, false, 0);
3759     }
3760   }
3761   return Chain;
3762 }
3763
3764 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3765 /// the position of the argument.
3766 static void
3767 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3768                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3769                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3770   int Offset = ArgOffset + SPDiff;
3771   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3772   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3773   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3774   SDValue FIN = DAG.getFrameIndex(FI, VT);
3775   TailCallArgumentInfo Info;
3776   Info.Arg = Arg;
3777   Info.FrameIdxOp = FIN;
3778   Info.FrameIdx = FI;
3779   TailCallArguments.push_back(Info);
3780 }
3781
3782 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3783 /// stack slot. Returns the chain as result and the loaded frame pointers in
3784 /// LROpOut/FPOpout. Used when tail calling.
3785 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3786                                                         int SPDiff,
3787                                                         SDValue Chain,
3788                                                         SDValue &LROpOut,
3789                                                         SDValue &FPOpOut,
3790                                                         bool isDarwinABI,
3791                                                         SDLoc dl) const {
3792   if (SPDiff) {
3793     // Load the LR and FP stack slot for later adjusting.
3794     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3795     LROpOut = getReturnAddrFrameIndex(DAG);
3796     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3797                           false, false, false, 0);
3798     Chain = SDValue(LROpOut.getNode(), 1);
3799
3800     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3801     // slot as the FP is never overwritten.
3802     if (isDarwinABI) {
3803       FPOpOut = getFramePointerFrameIndex(DAG);
3804       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3805                             false, false, false, 0);
3806       Chain = SDValue(FPOpOut.getNode(), 1);
3807     }
3808   }
3809   return Chain;
3810 }
3811
3812 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3813 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3814 /// specified by the specific parameter attribute. The copy will be passed as
3815 /// a byval function parameter.
3816 /// Sometimes what we are copying is the end of a larger object, the part that
3817 /// does not fit in registers.
3818 static SDValue
3819 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3820                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3821                           SDLoc dl) {
3822   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3823   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3824                        false, false, MachinePointerInfo(),
3825                        MachinePointerInfo());
3826 }
3827
3828 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3829 /// tail calls.
3830 static void
3831 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3832                  SDValue Arg, SDValue PtrOff, int SPDiff,
3833                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3834                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3835                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3836                  SDLoc dl) {
3837   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3838   if (!isTailCall) {
3839     if (isVector) {
3840       SDValue StackPtr;
3841       if (isPPC64)
3842         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3843       else
3844         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3845       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3846                            DAG.getConstant(ArgOffset, PtrVT));
3847     }
3848     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3849                                        MachinePointerInfo(), false, false, 0));
3850   // Calculate and remember argument location.
3851   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3852                                   TailCallArguments);
3853 }
3854
3855 static
3856 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3857                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3858                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3859                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3860   MachineFunction &MF = DAG.getMachineFunction();
3861
3862   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3863   // might overwrite each other in case of tail call optimization.
3864   SmallVector<SDValue, 8> MemOpChains2;
3865   // Do not flag preceding copytoreg stuff together with the following stuff.
3866   InFlag = SDValue();
3867   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3868                                     MemOpChains2, dl);
3869   if (!MemOpChains2.empty())
3870     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3871
3872   // Store the return address to the appropriate stack slot.
3873   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3874                                         isPPC64, isDarwinABI, dl);
3875
3876   // Emit callseq_end just before tailcall node.
3877   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3878                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3879   InFlag = Chain.getValue(1);
3880 }
3881
3882 // Is this global address that of a function that can be called by name? (as
3883 // opposed to something that must hold a descriptor for an indirect call).
3884 static bool isFunctionGlobalAddress(SDValue Callee) {
3885   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3886     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3887         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3888       return false;
3889
3890     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3891   }
3892
3893   return false;
3894 }
3895
3896 static
3897 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3898                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3899                      bool isTailCall, bool IsPatchPoint,
3900                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3901                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3902                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3903
3904   bool isPPC64 = Subtarget.isPPC64();
3905   bool isSVR4ABI = Subtarget.isSVR4ABI();
3906   bool isELFv2ABI = Subtarget.isELFv2ABI();
3907
3908   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3909   NodeTys.push_back(MVT::Other);   // Returns a chain
3910   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3911
3912   unsigned CallOpc = PPCISD::CALL;
3913
3914   bool needIndirectCall = true;
3915   if (!isSVR4ABI || !isPPC64)
3916     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3917       // If this is an absolute destination address, use the munged value.
3918       Callee = SDValue(Dest, 0);
3919       needIndirectCall = false;
3920     }
3921
3922   if (isFunctionGlobalAddress(Callee)) {
3923     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3924     // A call to a TLS address is actually an indirect call to a
3925     // thread-specific pointer.
3926     unsigned OpFlags = 0;
3927     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3928          (Subtarget.getTargetTriple().isMacOSX() &&
3929           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3930          (G->getGlobal()->isDeclaration() ||
3931           G->getGlobal()->isWeakForLinker())) ||
3932         (Subtarget.isTargetELF() && !isPPC64 &&
3933          !G->getGlobal()->hasLocalLinkage() &&
3934          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3935       // PC-relative references to external symbols should go through $stub,
3936       // unless we're building with the leopard linker or later, which
3937       // automatically synthesizes these stubs.
3938       OpFlags = PPCII::MO_PLT_OR_STUB;
3939     }
3940
3941     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3942     // every direct call is) turn it into a TargetGlobalAddress /
3943     // TargetExternalSymbol node so that legalize doesn't hack it.
3944     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3945                                         Callee.getValueType(), 0, OpFlags);
3946     needIndirectCall = false;
3947   }
3948
3949   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3950     unsigned char OpFlags = 0;
3951
3952     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3953          (Subtarget.getTargetTriple().isMacOSX() &&
3954           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3955         (Subtarget.isTargetELF() && !isPPC64 &&
3956          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3957       // PC-relative references to external symbols should go through $stub,
3958       // unless we're building with the leopard linker or later, which
3959       // automatically synthesizes these stubs.
3960       OpFlags = PPCII::MO_PLT_OR_STUB;
3961     }
3962
3963     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3964                                          OpFlags);
3965     needIndirectCall = false;
3966   }
3967
3968   if (IsPatchPoint) {
3969     // We'll form an invalid direct call when lowering a patchpoint; the full
3970     // sequence for an indirect call is complicated, and many of the
3971     // instructions introduced might have side effects (and, thus, can't be
3972     // removed later). The call itself will be removed as soon as the
3973     // argument/return lowering is complete, so the fact that it has the wrong
3974     // kind of operands should not really matter.
3975     needIndirectCall = false;
3976   }
3977
3978   if (needIndirectCall) {
3979     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3980     // to do the call, we can't use PPCISD::CALL.
3981     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3982
3983     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3984       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3985       // entry point, but to the function descriptor (the function entry point
3986       // address is part of the function descriptor though).
3987       // The function descriptor is a three doubleword structure with the
3988       // following fields: function entry point, TOC base address and
3989       // environment pointer.
3990       // Thus for a call through a function pointer, the following actions need
3991       // to be performed:
3992       //   1. Save the TOC of the caller in the TOC save area of its stack
3993       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3994       //   2. Load the address of the function entry point from the function
3995       //      descriptor.
3996       //   3. Load the TOC of the callee from the function descriptor into r2.
3997       //   4. Load the environment pointer from the function descriptor into
3998       //      r11.
3999       //   5. Branch to the function entry point address.
4000       //   6. On return of the callee, the TOC of the caller needs to be
4001       //      restored (this is done in FinishCall()).
4002       //
4003       // The loads are scheduled at the beginning of the call sequence, and the
4004       // register copies are flagged together to ensure that no other
4005       // operations can be scheduled in between. E.g. without flagging the
4006       // copies together, a TOC access in the caller could be scheduled between
4007       // the assignment of the callee TOC and the branch to the callee, which
4008       // results in the TOC access going through the TOC of the callee instead
4009       // of going through the TOC of the caller, which leads to incorrect code.
4010
4011       // Load the address of the function entry point from the function
4012       // descriptor.
4013       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4014       if (LDChain.getValueType() == MVT::Glue)
4015         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4016
4017       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4018
4019       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4020       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4021                                         false, false, LoadsInv, 8);
4022
4023       // Load environment pointer into r11.
4024       SDValue PtrOff = DAG.getIntPtrConstant(16);
4025       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4026       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4027                                        MPI.getWithOffset(16), false, false,
4028                                        LoadsInv, 8);
4029
4030       SDValue TOCOff = DAG.getIntPtrConstant(8);
4031       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4032       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4033                                    MPI.getWithOffset(8), false, false,
4034                                    LoadsInv, 8);
4035
4036       setUsesTOCBasePtr(DAG);
4037       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4038                                         InFlag);
4039       Chain = TOCVal.getValue(0);
4040       InFlag = TOCVal.getValue(1);
4041
4042       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4043                                         InFlag);
4044
4045       Chain = EnvVal.getValue(0);
4046       InFlag = EnvVal.getValue(1);
4047
4048       MTCTROps[0] = Chain;
4049       MTCTROps[1] = LoadFuncPtr;
4050       MTCTROps[2] = InFlag;
4051     }
4052
4053     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4054                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4055     InFlag = Chain.getValue(1);
4056
4057     NodeTys.clear();
4058     NodeTys.push_back(MVT::Other);
4059     NodeTys.push_back(MVT::Glue);
4060     Ops.push_back(Chain);
4061     CallOpc = PPCISD::BCTRL;
4062     Callee.setNode(nullptr);
4063     // Add use of X11 (holding environment pointer)
4064     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4065       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4066     // Add CTR register as callee so a bctr can be emitted later.
4067     if (isTailCall)
4068       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4069   }
4070
4071   // If this is a direct call, pass the chain and the callee.
4072   if (Callee.getNode()) {
4073     Ops.push_back(Chain);
4074     Ops.push_back(Callee);
4075   }
4076   // If this is a tail call add stack pointer delta.
4077   if (isTailCall)
4078     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
4079
4080   // Add argument registers to the end of the list so that they are known live
4081   // into the call.
4082   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4083     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4084                                   RegsToPass[i].second.getValueType()));
4085
4086   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4087   // into the call.
4088   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4089     setUsesTOCBasePtr(DAG);
4090     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4091   }
4092
4093   return CallOpc;
4094 }
4095
4096 static
4097 bool isLocalCall(const SDValue &Callee)
4098 {
4099   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4100     return !G->getGlobal()->isDeclaration() &&
4101            !G->getGlobal()->isWeakForLinker();
4102   return false;
4103 }
4104
4105 SDValue
4106 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4107                                    CallingConv::ID CallConv, bool isVarArg,
4108                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4109                                    SDLoc dl, SelectionDAG &DAG,
4110                                    SmallVectorImpl<SDValue> &InVals) const {
4111
4112   SmallVector<CCValAssign, 16> RVLocs;
4113   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4114                     *DAG.getContext());
4115   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4116
4117   // Copy all of the result registers out of their specified physreg.
4118   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4119     CCValAssign &VA = RVLocs[i];
4120     assert(VA.isRegLoc() && "Can only return in registers!");
4121
4122     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4123                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4124     Chain = Val.getValue(1);
4125     InFlag = Val.getValue(2);
4126
4127     switch (VA.getLocInfo()) {
4128     default: llvm_unreachable("Unknown loc info!");
4129     case CCValAssign::Full: break;
4130     case CCValAssign::AExt:
4131       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4132       break;
4133     case CCValAssign::ZExt:
4134       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4135                         DAG.getValueType(VA.getValVT()));
4136       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4137       break;
4138     case CCValAssign::SExt:
4139       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4140                         DAG.getValueType(VA.getValVT()));
4141       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4142       break;
4143     }
4144
4145     InVals.push_back(Val);
4146   }
4147
4148   return Chain;
4149 }
4150
4151 SDValue
4152 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4153                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4154                               SelectionDAG &DAG,
4155                               SmallVector<std::pair<unsigned, SDValue>, 8>
4156                                 &RegsToPass,
4157                               SDValue InFlag, SDValue Chain,
4158                               SDValue CallSeqStart, SDValue &Callee,
4159                               int SPDiff, unsigned NumBytes,
4160                               const SmallVectorImpl<ISD::InputArg> &Ins,
4161                               SmallVectorImpl<SDValue> &InVals,
4162                               ImmutableCallSite *CS) const {
4163
4164   std::vector<EVT> NodeTys;
4165   SmallVector<SDValue, 8> Ops;
4166   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4167                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4168                                  Ops, NodeTys, CS, Subtarget);
4169
4170   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4171   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4172     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4173
4174   // When performing tail call optimization the callee pops its arguments off
4175   // the stack. Account for this here so these bytes can be pushed back on in
4176   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4177   int BytesCalleePops =
4178     (CallConv == CallingConv::Fast &&
4179      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4180
4181   // Add a register mask operand representing the call-preserved registers.
4182   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4183   const uint32_t *Mask =
4184       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4185   assert(Mask && "Missing call preserved mask for calling convention");
4186   Ops.push_back(DAG.getRegisterMask(Mask));
4187
4188   if (InFlag.getNode())
4189     Ops.push_back(InFlag);
4190
4191   // Emit tail call.
4192   if (isTailCall) {
4193     assert(((Callee.getOpcode() == ISD::Register &&
4194              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4195             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4196             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4197             isa<ConstantSDNode>(Callee)) &&
4198     "Expecting an global address, external symbol, absolute value or register");
4199
4200     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4201   }
4202
4203   // Add a NOP immediately after the branch instruction when using the 64-bit
4204   // SVR4 ABI. At link time, if caller and callee are in a different module and
4205   // thus have a different TOC, the call will be replaced with a call to a stub
4206   // function which saves the current TOC, loads the TOC of the callee and
4207   // branches to the callee. The NOP will be replaced with a load instruction
4208   // which restores the TOC of the caller from the TOC save slot of the current
4209   // stack frame. If caller and callee belong to the same module (and have the
4210   // same TOC), the NOP will remain unchanged.
4211
4212   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4213       !IsPatchPoint) {
4214     if (CallOpc == PPCISD::BCTRL) {
4215       // This is a call through a function pointer.
4216       // Restore the caller TOC from the save area into R2.
4217       // See PrepareCall() for more information about calls through function
4218       // pointers in the 64-bit SVR4 ABI.
4219       // We are using a target-specific load with r2 hard coded, because the
4220       // result of a target-independent load would never go directly into r2,
4221       // since r2 is a reserved register (which prevents the register allocator
4222       // from allocating it), resulting in an additional register being
4223       // allocated and an unnecessary move instruction being generated.
4224       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4225
4226       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4227       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4228       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4229       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
4230       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4231
4232       // The address needs to go after the chain input but before the flag (or
4233       // any other variadic arguments).
4234       Ops.insert(std::next(Ops.begin()), AddTOC);
4235     } else if ((CallOpc == PPCISD::CALL) &&
4236                (!isLocalCall(Callee) ||
4237                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4238       // Otherwise insert NOP for non-local calls.
4239       CallOpc = PPCISD::CALL_NOP;
4240   }
4241
4242   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4243   InFlag = Chain.getValue(1);
4244
4245   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
4246                              DAG.getIntPtrConstant(BytesCalleePops, true),
4247                              InFlag, dl);
4248   if (!Ins.empty())
4249     InFlag = Chain.getValue(1);
4250
4251   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4252                          Ins, dl, DAG, InVals);
4253 }
4254
4255 SDValue
4256 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4257                              SmallVectorImpl<SDValue> &InVals) const {
4258   SelectionDAG &DAG                     = CLI.DAG;
4259   SDLoc &dl                             = CLI.DL;
4260   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4261   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4262   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4263   SDValue Chain                         = CLI.Chain;
4264   SDValue Callee                        = CLI.Callee;
4265   bool &isTailCall                      = CLI.IsTailCall;
4266   CallingConv::ID CallConv              = CLI.CallConv;
4267   bool isVarArg                         = CLI.IsVarArg;
4268   bool IsPatchPoint                     = CLI.IsPatchPoint;
4269   ImmutableCallSite *CS                 = CLI.CS;
4270
4271   if (isTailCall)
4272     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4273                                                    Ins, DAG);
4274
4275   if (!isTailCall && CS && CS->isMustTailCall())
4276     report_fatal_error("failed to perform tail call elimination on a call "
4277                        "site marked musttail");
4278
4279   if (Subtarget.isSVR4ABI()) {
4280     if (Subtarget.isPPC64())
4281       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4282                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4283                               dl, DAG, InVals, CS);
4284     else
4285       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4286                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4287                               dl, DAG, InVals, CS);
4288   }
4289
4290   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4291                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4292                           dl, DAG, InVals, CS);
4293 }
4294
4295 SDValue
4296 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4297                                     CallingConv::ID CallConv, bool isVarArg,
4298                                     bool isTailCall, bool IsPatchPoint,
4299                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4300                                     const SmallVectorImpl<SDValue> &OutVals,
4301                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4302                                     SDLoc dl, SelectionDAG &DAG,
4303                                     SmallVectorImpl<SDValue> &InVals,
4304                                     ImmutableCallSite *CS) const {
4305   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4306   // of the 32-bit SVR4 ABI stack frame layout.
4307
4308   assert((CallConv == CallingConv::C ||
4309           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4310
4311   unsigned PtrByteSize = 4;
4312
4313   MachineFunction &MF = DAG.getMachineFunction();
4314
4315   // Mark this function as potentially containing a function that contains a
4316   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4317   // and restoring the callers stack pointer in this functions epilog. This is
4318   // done because by tail calling the called function might overwrite the value
4319   // in this function's (MF) stack pointer stack slot 0(SP).
4320   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4321       CallConv == CallingConv::Fast)
4322     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4323
4324   // Count how many bytes are to be pushed on the stack, including the linkage
4325   // area, parameter list area and the part of the local variable space which
4326   // contains copies of aggregates which are passed by value.
4327
4328   // Assign locations to all of the outgoing arguments.
4329   SmallVector<CCValAssign, 16> ArgLocs;
4330   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4331                  *DAG.getContext());
4332
4333   // Reserve space for the linkage area on the stack.
4334   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4335                        PtrByteSize);
4336
4337   if (isVarArg) {
4338     // Handle fixed and variable vector arguments differently.
4339     // Fixed vector arguments go into registers as long as registers are
4340     // available. Variable vector arguments always go into memory.
4341     unsigned NumArgs = Outs.size();
4342
4343     for (unsigned i = 0; i != NumArgs; ++i) {
4344       MVT ArgVT = Outs[i].VT;
4345       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4346       bool Result;
4347
4348       if (Outs[i].IsFixed) {
4349         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4350                                CCInfo);
4351       } else {
4352         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4353                                       ArgFlags, CCInfo);
4354       }
4355
4356       if (Result) {
4357 #ifndef NDEBUG
4358         errs() << "Call operand #" << i << " has unhandled type "
4359              << EVT(ArgVT).getEVTString() << "\n";
4360 #endif
4361         llvm_unreachable(nullptr);
4362       }
4363     }
4364   } else {
4365     // All arguments are treated the same.
4366     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4367   }
4368
4369   // Assign locations to all of the outgoing aggregate by value arguments.
4370   SmallVector<CCValAssign, 16> ByValArgLocs;
4371   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4372                       ByValArgLocs, *DAG.getContext());
4373
4374   // Reserve stack space for the allocations in CCInfo.
4375   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4376
4377   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4378
4379   // Size of the linkage area, parameter list area and the part of the local
4380   // space variable where copies of aggregates which are passed by value are
4381   // stored.
4382   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4383
4384   // Calculate by how many bytes the stack has to be adjusted in case of tail
4385   // call optimization.
4386   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4387
4388   // Adjust the stack pointer for the new arguments...
4389   // These operations are automatically eliminated by the prolog/epilog pass
4390   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4391                                dl);
4392   SDValue CallSeqStart = Chain;
4393
4394   // Load the return address and frame pointer so it can be moved somewhere else
4395   // later.
4396   SDValue LROp, FPOp;
4397   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4398                                        dl);
4399
4400   // Set up a copy of the stack pointer for use loading and storing any
4401   // arguments that may not fit in the registers available for argument
4402   // passing.
4403   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4404
4405   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4406   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4407   SmallVector<SDValue, 8> MemOpChains;
4408
4409   bool seenFloatArg = false;
4410   // Walk the register/memloc assignments, inserting copies/loads.
4411   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4412        i != e;
4413        ++i) {
4414     CCValAssign &VA = ArgLocs[i];
4415     SDValue Arg = OutVals[i];
4416     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4417
4418     if (Flags.isByVal()) {
4419       // Argument is an aggregate which is passed by value, thus we need to
4420       // create a copy of it in the local variable space of the current stack
4421       // frame (which is the stack frame of the caller) and pass the address of
4422       // this copy to the callee.
4423       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4424       CCValAssign &ByValVA = ByValArgLocs[j++];
4425       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4426
4427       // Memory reserved in the local variable space of the callers stack frame.
4428       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4429
4430       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4431       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4432
4433       // Create a copy of the argument in the local area of the current
4434       // stack frame.
4435       SDValue MemcpyCall =
4436         CreateCopyOfByValArgument(Arg, PtrOff,
4437                                   CallSeqStart.getNode()->getOperand(0),
4438                                   Flags, DAG, dl);
4439
4440       // This must go outside the CALLSEQ_START..END.
4441       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4442                            CallSeqStart.getNode()->getOperand(1),
4443                            SDLoc(MemcpyCall));
4444       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4445                              NewCallSeqStart.getNode());
4446       Chain = CallSeqStart = NewCallSeqStart;
4447
4448       // Pass the address of the aggregate copy on the stack either in a
4449       // physical register or in the parameter list area of the current stack
4450       // frame to the callee.
4451       Arg = PtrOff;
4452     }
4453
4454     if (VA.isRegLoc()) {
4455       if (Arg.getValueType() == MVT::i1)
4456         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4457
4458       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4459       // Put argument in a physical register.
4460       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4461     } else {
4462       // Put argument in the parameter list area of the current stack frame.
4463       assert(VA.isMemLoc());
4464       unsigned LocMemOffset = VA.getLocMemOffset();
4465
4466       if (!isTailCall) {
4467         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4468         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4469
4470         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4471                                            MachinePointerInfo(),
4472                                            false, false, 0));
4473       } else {
4474         // Calculate and remember argument location.
4475         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4476                                  TailCallArguments);
4477       }
4478     }
4479   }
4480
4481   if (!MemOpChains.empty())
4482     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4483
4484   // Build a sequence of copy-to-reg nodes chained together with token chain
4485   // and flag operands which copy the outgoing args into the appropriate regs.
4486   SDValue InFlag;
4487   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4488     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4489                              RegsToPass[i].second, InFlag);
4490     InFlag = Chain.getValue(1);
4491   }
4492
4493   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4494   // registers.
4495   if (isVarArg) {
4496     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4497     SDValue Ops[] = { Chain, InFlag };
4498
4499     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4500                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4501
4502     InFlag = Chain.getValue(1);
4503   }
4504
4505   if (isTailCall)
4506     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4507                     false, TailCallArguments);
4508
4509   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4510                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4511                     NumBytes, Ins, InVals, CS);
4512 }
4513
4514 // Copy an argument into memory, being careful to do this outside the
4515 // call sequence for the call to which the argument belongs.
4516 SDValue
4517 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4518                                               SDValue CallSeqStart,
4519                                               ISD::ArgFlagsTy Flags,
4520                                               SelectionDAG &DAG,
4521                                               SDLoc dl) const {
4522   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4523                         CallSeqStart.getNode()->getOperand(0),
4524                         Flags, DAG, dl);
4525   // The MEMCPY must go outside the CALLSEQ_START..END.
4526   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4527                              CallSeqStart.getNode()->getOperand(1),
4528                              SDLoc(MemcpyCall));
4529   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4530                          NewCallSeqStart.getNode());
4531   return NewCallSeqStart;
4532 }
4533
4534 SDValue
4535 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4536                                     CallingConv::ID CallConv, bool isVarArg,
4537                                     bool isTailCall, bool IsPatchPoint,
4538                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4539                                     const SmallVectorImpl<SDValue> &OutVals,
4540                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4541                                     SDLoc dl, SelectionDAG &DAG,
4542                                     SmallVectorImpl<SDValue> &InVals,
4543                                     ImmutableCallSite *CS) const {
4544
4545   bool isELFv2ABI = Subtarget.isELFv2ABI();
4546   bool isLittleEndian = Subtarget.isLittleEndian();
4547   unsigned NumOps = Outs.size();
4548
4549   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4550   unsigned PtrByteSize = 8;
4551
4552   MachineFunction &MF = DAG.getMachineFunction();
4553
4554   // Mark this function as potentially containing a function that contains a
4555   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4556   // and restoring the callers stack pointer in this functions epilog. This is
4557   // done because by tail calling the called function might overwrite the value
4558   // in this function's (MF) stack pointer stack slot 0(SP).
4559   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4560       CallConv == CallingConv::Fast)
4561     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4562
4563   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4564          "fastcc not supported on varargs functions");
4565
4566   // Count how many bytes are to be pushed on the stack, including the linkage
4567   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4568   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4569   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4570   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4571   unsigned NumBytes = LinkageSize;
4572   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4573   unsigned &QFPR_idx = FPR_idx;
4574
4575   static const MCPhysReg GPR[] = {
4576     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4577     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4578   };
4579   static const MCPhysReg VR[] = {
4580     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4581     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4582   };
4583   static const MCPhysReg VSRH[] = {
4584     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4585     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4586   };
4587
4588   const unsigned NumGPRs = array_lengthof(GPR);
4589   const unsigned NumFPRs = 13;
4590   const unsigned NumVRs  = array_lengthof(VR);
4591   const unsigned NumQFPRs = NumFPRs;
4592
4593   // When using the fast calling convention, we don't provide backing for
4594   // arguments that will be in registers.
4595   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4596
4597   // Add up all the space actually used.
4598   for (unsigned i = 0; i != NumOps; ++i) {
4599     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4600     EVT ArgVT = Outs[i].VT;
4601     EVT OrigVT = Outs[i].ArgVT;
4602
4603     if (CallConv == CallingConv::Fast) {
4604       if (Flags.isByVal())
4605         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4606       else
4607         switch (ArgVT.getSimpleVT().SimpleTy) {
4608         default: llvm_unreachable("Unexpected ValueType for argument!");
4609         case MVT::i1:
4610         case MVT::i32:
4611         case MVT::i64:
4612           if (++NumGPRsUsed <= NumGPRs)
4613             continue;
4614           break;
4615         case MVT::v4i32:
4616         case MVT::v8i16:
4617         case MVT::v16i8:
4618         case MVT::v2f64:
4619         case MVT::v2i64:
4620           if (++NumVRsUsed <= NumVRs)
4621             continue;
4622           break;
4623         case MVT::v4f32:
4624           // When using QPX, this is handled like a FP register, otherwise, it
4625           // is an Altivec register.
4626           if (Subtarget.hasQPX()) {
4627             if (++NumFPRsUsed <= NumFPRs)
4628               continue;
4629           } else {
4630             if (++NumVRsUsed <= NumVRs)
4631               continue;
4632           }
4633           break;
4634         case MVT::f32:
4635         case MVT::f64:
4636         case MVT::v4f64: // QPX
4637         case MVT::v4i1:  // QPX
4638           if (++NumFPRsUsed <= NumFPRs)
4639             continue;
4640           break;
4641         }
4642     }
4643
4644     /* Respect alignment of argument on the stack.  */
4645     unsigned Align =
4646       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4647     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4648
4649     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4650     if (Flags.isInConsecutiveRegsLast())
4651       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4652   }
4653
4654   unsigned NumBytesActuallyUsed = NumBytes;
4655
4656   // The prolog code of the callee may store up to 8 GPR argument registers to
4657   // the stack, allowing va_start to index over them in memory if its varargs.
4658   // Because we cannot tell if this is needed on the caller side, we have to
4659   // conservatively assume that it is needed.  As such, make sure we have at
4660   // least enough stack space for the caller to store the 8 GPRs.
4661   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4662   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4663
4664   // Tail call needs the stack to be aligned.
4665   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4666       CallConv == CallingConv::Fast)
4667     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4668
4669   // Calculate by how many bytes the stack has to be adjusted in case of tail
4670   // call optimization.
4671   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4672
4673   // To protect arguments on the stack from being clobbered in a tail call,
4674   // force all the loads to happen before doing any other lowering.
4675   if (isTailCall)
4676     Chain = DAG.getStackArgumentTokenFactor(Chain);
4677
4678   // Adjust the stack pointer for the new arguments...
4679   // These operations are automatically eliminated by the prolog/epilog pass
4680   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4681                                dl);
4682   SDValue CallSeqStart = Chain;
4683
4684   // Load the return address and frame pointer so it can be move somewhere else
4685   // later.
4686   SDValue LROp, FPOp;
4687   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4688                                        dl);
4689
4690   // Set up a copy of the stack pointer for use loading and storing any
4691   // arguments that may not fit in the registers available for argument
4692   // passing.
4693   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4694
4695   // Figure out which arguments are going to go in registers, and which in
4696   // memory.  Also, if this is a vararg function, floating point operations
4697   // must be stored to our stack, and loaded into integer regs as well, if
4698   // any integer regs are available for argument passing.
4699   unsigned ArgOffset = LinkageSize;
4700
4701   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4702   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4703
4704   SmallVector<SDValue, 8> MemOpChains;
4705   for (unsigned i = 0; i != NumOps; ++i) {
4706     SDValue Arg = OutVals[i];
4707     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4708     EVT ArgVT = Outs[i].VT;
4709     EVT OrigVT = Outs[i].ArgVT;
4710
4711     // PtrOff will be used to store the current argument to the stack if a
4712     // register cannot be found for it.
4713     SDValue PtrOff;
4714
4715     // We re-align the argument offset for each argument, except when using the
4716     // fast calling convention, when we need to make sure we do that only when
4717     // we'll actually use a stack slot.
4718     auto ComputePtrOff = [&]() {
4719       /* Respect alignment of argument on the stack.  */
4720       unsigned Align =
4721         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4722       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4723
4724       PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4725
4726       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4727     };
4728
4729     if (CallConv != CallingConv::Fast) {
4730       ComputePtrOff();
4731
4732       /* Compute GPR index associated with argument offset.  */
4733       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4734       GPR_idx = std::min(GPR_idx, NumGPRs);
4735     }
4736
4737     // Promote integers to 64-bit values.
4738     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4739       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4740       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4741       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4742     }
4743
4744     // FIXME memcpy is used way more than necessary.  Correctness first.
4745     // Note: "by value" is code for passing a structure by value, not
4746     // basic types.
4747     if (Flags.isByVal()) {
4748       // Note: Size includes alignment padding, so
4749       //   struct x { short a; char b; }
4750       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4751       // These are the proper values we need for right-justifying the
4752       // aggregate in a parameter register.
4753       unsigned Size = Flags.getByValSize();
4754
4755       // An empty aggregate parameter takes up no storage and no
4756       // registers.
4757       if (Size == 0)
4758         continue;
4759
4760       if (CallConv == CallingConv::Fast)
4761         ComputePtrOff();
4762
4763       // All aggregates smaller than 8 bytes must be passed right-justified.
4764       if (Size==1 || Size==2 || Size==4) {
4765         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4766         if (GPR_idx != NumGPRs) {
4767           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4768                                         MachinePointerInfo(), VT,
4769                                         false, false, false, 0);
4770           MemOpChains.push_back(Load.getValue(1));
4771           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4772
4773           ArgOffset += PtrByteSize;
4774           continue;
4775         }
4776       }
4777
4778       if (GPR_idx == NumGPRs && Size < 8) {
4779         SDValue AddPtr = PtrOff;
4780         if (!isLittleEndian) {
4781           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4782                                           PtrOff.getValueType());
4783           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4784         }
4785         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4786                                                           CallSeqStart,
4787                                                           Flags, DAG, dl);
4788         ArgOffset += PtrByteSize;
4789         continue;
4790       }
4791       // Copy entire object into memory.  There are cases where gcc-generated
4792       // code assumes it is there, even if it could be put entirely into
4793       // registers.  (This is not what the doc says.)
4794
4795       // FIXME: The above statement is likely due to a misunderstanding of the
4796       // documents.  All arguments must be copied into the parameter area BY
4797       // THE CALLEE in the event that the callee takes the address of any
4798       // formal argument.  That has not yet been implemented.  However, it is
4799       // reasonable to use the stack area as a staging area for the register
4800       // load.
4801
4802       // Skip this for small aggregates, as we will use the same slot for a
4803       // right-justified copy, below.
4804       if (Size >= 8)
4805         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4806                                                           CallSeqStart,
4807                                                           Flags, DAG, dl);
4808
4809       // When a register is available, pass a small aggregate right-justified.
4810       if (Size < 8 && GPR_idx != NumGPRs) {
4811         // The easiest way to get this right-justified in a register
4812         // is to copy the structure into the rightmost portion of a
4813         // local variable slot, then load the whole slot into the
4814         // register.
4815         // FIXME: The memcpy seems to produce pretty awful code for
4816         // small aggregates, particularly for packed ones.
4817         // FIXME: It would be preferable to use the slot in the
4818         // parameter save area instead of a new local variable.
4819         SDValue AddPtr = PtrOff;
4820         if (!isLittleEndian) {
4821           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4822           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4823         }
4824         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4825                                                           CallSeqStart,
4826                                                           Flags, DAG, dl);
4827
4828         // Load the slot into the register.
4829         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4830                                    MachinePointerInfo(),
4831                                    false, false, false, 0);
4832         MemOpChains.push_back(Load.getValue(1));
4833         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4834
4835         // Done with this argument.
4836         ArgOffset += PtrByteSize;
4837         continue;
4838       }
4839
4840       // For aggregates larger than PtrByteSize, copy the pieces of the
4841       // object that fit into registers from the parameter save area.
4842       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4843         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4844         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4845         if (GPR_idx != NumGPRs) {
4846           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4847                                      MachinePointerInfo(),
4848                                      false, false, false, 0);
4849           MemOpChains.push_back(Load.getValue(1));
4850           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4851           ArgOffset += PtrByteSize;
4852         } else {
4853           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4854           break;
4855         }
4856       }
4857       continue;
4858     }
4859
4860     switch (Arg.getSimpleValueType().SimpleTy) {
4861     default: llvm_unreachable("Unexpected ValueType for argument!");
4862     case MVT::i1:
4863     case MVT::i32:
4864     case MVT::i64:
4865       // These can be scalar arguments or elements of an integer array type
4866       // passed directly.  Clang may use those instead of "byval" aggregate
4867       // types to avoid forcing arguments to memory unnecessarily.
4868       if (GPR_idx != NumGPRs) {
4869         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4870       } else {
4871         if (CallConv == CallingConv::Fast)
4872           ComputePtrOff();
4873
4874         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4875                          true, isTailCall, false, MemOpChains,
4876                          TailCallArguments, dl);
4877         if (CallConv == CallingConv::Fast)
4878           ArgOffset += PtrByteSize;
4879       }
4880       if (CallConv != CallingConv::Fast)
4881         ArgOffset += PtrByteSize;
4882       break;
4883     case MVT::f32:
4884     case MVT::f64: {
4885       // These can be scalar arguments or elements of a float array type
4886       // passed directly.  The latter are used to implement ELFv2 homogenous
4887       // float aggregates.
4888
4889       // Named arguments go into FPRs first, and once they overflow, the
4890       // remaining arguments go into GPRs and then the parameter save area.
4891       // Unnamed arguments for vararg functions always go to GPRs and
4892       // then the parameter save area.  For now, put all arguments to vararg
4893       // routines always in both locations (FPR *and* GPR or stack slot).
4894       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4895       bool NeededLoad = false;
4896
4897       // First load the argument into the next available FPR.
4898       if (FPR_idx != NumFPRs)
4899         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4900
4901       // Next, load the argument into GPR or stack slot if needed.
4902       if (!NeedGPROrStack)
4903         ;
4904       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4905         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4906         // once we support fp <-> gpr moves.
4907
4908         // In the non-vararg case, this can only ever happen in the
4909         // presence of f32 array types, since otherwise we never run
4910         // out of FPRs before running out of GPRs.
4911         SDValue ArgVal;
4912
4913         // Double values are always passed in a single GPR.
4914         if (Arg.getValueType() != MVT::f32) {
4915           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4916
4917         // Non-array float values are extended and passed in a GPR.
4918         } else if (!Flags.isInConsecutiveRegs()) {
4919           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4920           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4921
4922         // If we have an array of floats, we collect every odd element
4923         // together with its predecessor into one GPR.
4924         } else if (ArgOffset % PtrByteSize != 0) {
4925           SDValue Lo, Hi;
4926           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4927           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4928           if (!isLittleEndian)
4929             std::swap(Lo, Hi);
4930           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4931
4932         // The final element, if even, goes into the first half of a GPR.
4933         } else if (Flags.isInConsecutiveRegsLast()) {
4934           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4935           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4936           if (!isLittleEndian)
4937             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4938                                  DAG.getConstant(32, MVT::i32));
4939
4940         // Non-final even elements are skipped; they will be handled
4941         // together the with subsequent argument on the next go-around.
4942         } else
4943           ArgVal = SDValue();
4944
4945         if (ArgVal.getNode())
4946           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
4947       } else {
4948         if (CallConv == CallingConv::Fast)
4949           ComputePtrOff();
4950
4951         // Single-precision floating-point values are mapped to the
4952         // second (rightmost) word of the stack doubleword.
4953         if (Arg.getValueType() == MVT::f32 &&
4954             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4955           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4956           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4957         }
4958
4959         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4960                          true, isTailCall, false, MemOpChains,
4961                          TailCallArguments, dl);
4962
4963         NeededLoad = true;
4964       }
4965       // When passing an array of floats, the array occupies consecutive
4966       // space in the argument area; only round up to the next doubleword
4967       // at the end of the array.  Otherwise, each float takes 8 bytes.
4968       if (CallConv != CallingConv::Fast || NeededLoad) {
4969         ArgOffset += (Arg.getValueType() == MVT::f32 &&
4970                       Flags.isInConsecutiveRegs()) ? 4 : 8;
4971         if (Flags.isInConsecutiveRegsLast())
4972           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4973       }
4974       break;
4975     }
4976     case MVT::v4f32:
4977     case MVT::v4i32:
4978     case MVT::v8i16:
4979     case MVT::v16i8:
4980     case MVT::v2f64:
4981     case MVT::v2i64:
4982       if (!Subtarget.hasQPX()) {
4983       // These can be scalar arguments or elements of a vector array type
4984       // passed directly.  The latter are used to implement ELFv2 homogenous
4985       // vector aggregates.
4986
4987       // For a varargs call, named arguments go into VRs or on the stack as
4988       // usual; unnamed arguments always go to the stack or the corresponding
4989       // GPRs when within range.  For now, we always put the value in both
4990       // locations (or even all three).
4991       if (isVarArg) {
4992         // We could elide this store in the case where the object fits
4993         // entirely in R registers.  Maybe later.
4994         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4995                                      MachinePointerInfo(), false, false, 0);
4996         MemOpChains.push_back(Store);
4997         if (VR_idx != NumVRs) {
4998           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4999                                      MachinePointerInfo(),
5000                                      false, false, false, 0);
5001           MemOpChains.push_back(Load.getValue(1));
5002
5003           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5004                            Arg.getSimpleValueType() == MVT::v2i64) ?
5005                           VSRH[VR_idx] : VR[VR_idx];
5006           ++VR_idx;
5007
5008           RegsToPass.push_back(std::make_pair(VReg, Load));
5009         }
5010         ArgOffset += 16;
5011         for (unsigned i=0; i<16; i+=PtrByteSize) {
5012           if (GPR_idx == NumGPRs)
5013             break;
5014           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5015                                   DAG.getConstant(i, PtrVT));
5016           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5017                                      false, false, false, 0);
5018           MemOpChains.push_back(Load.getValue(1));
5019           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5020         }
5021         break;
5022       }
5023
5024       // Non-varargs Altivec params go into VRs or on the stack.
5025       if (VR_idx != NumVRs) {
5026         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5027                          Arg.getSimpleValueType() == MVT::v2i64) ?
5028                         VSRH[VR_idx] : VR[VR_idx];
5029         ++VR_idx;
5030
5031         RegsToPass.push_back(std::make_pair(VReg, Arg));
5032       } else {
5033         if (CallConv == CallingConv::Fast)
5034           ComputePtrOff();
5035
5036         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5037                          true, isTailCall, true, MemOpChains,
5038                          TailCallArguments, dl);
5039         if (CallConv == CallingConv::Fast)
5040           ArgOffset += 16;
5041       }
5042
5043       if (CallConv != CallingConv::Fast)
5044         ArgOffset += 16;
5045       break;
5046       } // not QPX
5047
5048       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5049              "Invalid QPX parameter type");
5050
5051       /* fall through */
5052     case MVT::v4f64:
5053     case MVT::v4i1: {
5054       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5055       if (isVarArg) {
5056         // We could elide this store in the case where the object fits
5057         // entirely in R registers.  Maybe later.
5058         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5059                                      MachinePointerInfo(), false, false, 0);
5060         MemOpChains.push_back(Store);
5061         if (QFPR_idx != NumQFPRs) {
5062           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5063                                      Store, PtrOff, MachinePointerInfo(),
5064                                      false, false, false, 0);
5065           MemOpChains.push_back(Load.getValue(1));
5066           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5067         }
5068         ArgOffset += (IsF32 ? 16 : 32);
5069         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5070           if (GPR_idx == NumGPRs)
5071             break;
5072           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5073                                   DAG.getConstant(i, PtrVT));
5074           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5075                                      false, false, false, 0);
5076           MemOpChains.push_back(Load.getValue(1));
5077           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5078         }
5079         break;
5080       }
5081
5082       // Non-varargs QPX params go into registers or on the stack.
5083       if (QFPR_idx != NumQFPRs) {
5084         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5085       } else {
5086         if (CallConv == CallingConv::Fast)
5087           ComputePtrOff();
5088
5089         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5090                          true, isTailCall, true, MemOpChains,
5091                          TailCallArguments, dl);
5092         if (CallConv == CallingConv::Fast)
5093           ArgOffset += (IsF32 ? 16 : 32);
5094       }
5095
5096       if (CallConv != CallingConv::Fast)
5097         ArgOffset += (IsF32 ? 16 : 32);
5098       break;
5099       }
5100     }
5101   }
5102
5103   assert(NumBytesActuallyUsed == ArgOffset);
5104   (void)NumBytesActuallyUsed;
5105
5106   if (!MemOpChains.empty())
5107     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5108
5109   // Check if this is an indirect call (MTCTR/BCTRL).
5110   // See PrepareCall() for more information about calls through function
5111   // pointers in the 64-bit SVR4 ABI.
5112   if (!isTailCall && !IsPatchPoint &&
5113       !isFunctionGlobalAddress(Callee) &&
5114       !isa<ExternalSymbolSDNode>(Callee)) {
5115     // Load r2 into a virtual register and store it to the TOC save area.
5116     setUsesTOCBasePtr(DAG);
5117     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5118     // TOC save area offset.
5119     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5120     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
5121     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5122     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5123                          MachinePointerInfo::getStack(TOCSaveOffset),
5124                          false, false, 0);
5125     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5126     // This does not mean the MTCTR instruction must use R12; it's easier
5127     // to model this as an extra parameter, so do that.
5128     if (isELFv2ABI && !IsPatchPoint)
5129       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5130   }
5131
5132   // Build a sequence of copy-to-reg nodes chained together with token chain
5133   // and flag operands which copy the outgoing args into the appropriate regs.
5134   SDValue InFlag;
5135   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5136     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5137                              RegsToPass[i].second, InFlag);
5138     InFlag = Chain.getValue(1);
5139   }
5140
5141   if (isTailCall)
5142     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5143                     FPOp, true, TailCallArguments);
5144
5145   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5146                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5147                     NumBytes, Ins, InVals, CS);
5148 }
5149
5150 SDValue
5151 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5152                                     CallingConv::ID CallConv, bool isVarArg,
5153                                     bool isTailCall, bool IsPatchPoint,
5154                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5155                                     const SmallVectorImpl<SDValue> &OutVals,
5156                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5157                                     SDLoc dl, SelectionDAG &DAG,
5158                                     SmallVectorImpl<SDValue> &InVals,
5159                                     ImmutableCallSite *CS) const {
5160
5161   unsigned NumOps = Outs.size();
5162
5163   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5164   bool isPPC64 = PtrVT == MVT::i64;
5165   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5166
5167   MachineFunction &MF = DAG.getMachineFunction();
5168
5169   // Mark this function as potentially containing a function that contains a
5170   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5171   // and restoring the callers stack pointer in this functions epilog. This is
5172   // done because by tail calling the called function might overwrite the value
5173   // in this function's (MF) stack pointer stack slot 0(SP).
5174   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5175       CallConv == CallingConv::Fast)
5176     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5177
5178   // Count how many bytes are to be pushed on the stack, including the linkage
5179   // area, and parameter passing area.  We start with 24/48 bytes, which is
5180   // prereserved space for [SP][CR][LR][3 x unused].
5181   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5182   unsigned NumBytes = LinkageSize;
5183
5184   // Add up all the space actually used.
5185   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5186   // they all go in registers, but we must reserve stack space for them for
5187   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5188   // assigned stack space in order, with padding so Altivec parameters are
5189   // 16-byte aligned.
5190   unsigned nAltivecParamsAtEnd = 0;
5191   for (unsigned i = 0; i != NumOps; ++i) {
5192     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5193     EVT ArgVT = Outs[i].VT;
5194     // Varargs Altivec parameters are padded to a 16 byte boundary.
5195     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5196         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5197         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5198       if (!isVarArg && !isPPC64) {
5199         // Non-varargs Altivec parameters go after all the non-Altivec
5200         // parameters; handle those later so we know how much padding we need.
5201         nAltivecParamsAtEnd++;
5202         continue;
5203       }
5204       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5205       NumBytes = ((NumBytes+15)/16)*16;
5206     }
5207     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5208   }
5209
5210   // Allow for Altivec parameters at the end, if needed.
5211   if (nAltivecParamsAtEnd) {
5212     NumBytes = ((NumBytes+15)/16)*16;
5213     NumBytes += 16*nAltivecParamsAtEnd;
5214   }
5215
5216   // The prolog code of the callee may store up to 8 GPR argument registers to
5217   // the stack, allowing va_start to index over them in memory if its varargs.
5218   // Because we cannot tell if this is needed on the caller side, we have to
5219   // conservatively assume that it is needed.  As such, make sure we have at
5220   // least enough stack space for the caller to store the 8 GPRs.
5221   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5222
5223   // Tail call needs the stack to be aligned.
5224   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5225       CallConv == CallingConv::Fast)
5226     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5227
5228   // Calculate by how many bytes the stack has to be adjusted in case of tail
5229   // call optimization.
5230   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5231
5232   // To protect arguments on the stack from being clobbered in a tail call,
5233   // force all the loads to happen before doing any other lowering.
5234   if (isTailCall)
5235     Chain = DAG.getStackArgumentTokenFactor(Chain);
5236
5237   // Adjust the stack pointer for the new arguments...
5238   // These operations are automatically eliminated by the prolog/epilog pass
5239   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
5240                                dl);
5241   SDValue CallSeqStart = Chain;
5242
5243   // Load the return address and frame pointer so it can be move somewhere else
5244   // later.
5245   SDValue LROp, FPOp;
5246   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5247                                        dl);
5248
5249   // Set up a copy of the stack pointer for use loading and storing any
5250   // arguments that may not fit in the registers available for argument
5251   // passing.
5252   SDValue StackPtr;
5253   if (isPPC64)
5254     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5255   else
5256     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5257
5258   // Figure out which arguments are going to go in registers, and which in
5259   // memory.  Also, if this is a vararg function, floating point operations
5260   // must be stored to our stack, and loaded into integer regs as well, if
5261   // any integer regs are available for argument passing.
5262   unsigned ArgOffset = LinkageSize;
5263   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5264
5265   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5266     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5267     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5268   };
5269   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5270     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5271     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5272   };
5273   static const MCPhysReg VR[] = {
5274     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5275     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5276   };
5277   const unsigned NumGPRs = array_lengthof(GPR_32);
5278   const unsigned NumFPRs = 13;
5279   const unsigned NumVRs  = array_lengthof(VR);
5280
5281   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5282
5283   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5284   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5285
5286   SmallVector<SDValue, 8> MemOpChains;
5287   for (unsigned i = 0; i != NumOps; ++i) {
5288     SDValue Arg = OutVals[i];
5289     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5290
5291     // PtrOff will be used to store the current argument to the stack if a
5292     // register cannot be found for it.
5293     SDValue PtrOff;
5294
5295     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
5296
5297     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5298
5299     // On PPC64, promote integers to 64-bit values.
5300     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5301       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5302       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5303       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5304     }
5305
5306     // FIXME memcpy is used way more than necessary.  Correctness first.
5307     // Note: "by value" is code for passing a structure by value, not
5308     // basic types.
5309     if (Flags.isByVal()) {
5310       unsigned Size = Flags.getByValSize();
5311       // Very small objects are passed right-justified.  Everything else is
5312       // passed left-justified.
5313       if (Size==1 || Size==2) {
5314         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5315         if (GPR_idx != NumGPRs) {
5316           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5317                                         MachinePointerInfo(), VT,
5318                                         false, false, false, 0);
5319           MemOpChains.push_back(Load.getValue(1));
5320           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5321
5322           ArgOffset += PtrByteSize;
5323         } else {
5324           SDValue Const = DAG.getConstant(PtrByteSize - Size,
5325                                           PtrOff.getValueType());
5326           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5327           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5328                                                             CallSeqStart,
5329                                                             Flags, DAG, dl);
5330           ArgOffset += PtrByteSize;
5331         }
5332         continue;
5333       }
5334       // Copy entire object into memory.  There are cases where gcc-generated
5335       // code assumes it is there, even if it could be put entirely into
5336       // registers.  (This is not what the doc says.)
5337       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5338                                                         CallSeqStart,
5339                                                         Flags, DAG, dl);
5340
5341       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5342       // copy the pieces of the object that fit into registers from the
5343       // parameter save area.
5344       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5345         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
5346         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5347         if (GPR_idx != NumGPRs) {
5348           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5349                                      MachinePointerInfo(),
5350                                      false, false, false, 0);
5351           MemOpChains.push_back(Load.getValue(1));
5352           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5353           ArgOffset += PtrByteSize;
5354         } else {
5355           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5356           break;
5357         }
5358       }
5359       continue;
5360     }
5361
5362     switch (Arg.getSimpleValueType().SimpleTy) {
5363     default: llvm_unreachable("Unexpected ValueType for argument!");
5364     case MVT::i1:
5365     case MVT::i32:
5366     case MVT::i64:
5367       if (GPR_idx != NumGPRs) {
5368         if (Arg.getValueType() == MVT::i1)
5369           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5370
5371         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5372       } else {
5373         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5374                          isPPC64, isTailCall, false, MemOpChains,
5375                          TailCallArguments, dl);
5376       }
5377       ArgOffset += PtrByteSize;
5378       break;
5379     case MVT::f32:
5380     case MVT::f64:
5381       if (FPR_idx != NumFPRs) {
5382         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5383
5384         if (isVarArg) {
5385           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5386                                        MachinePointerInfo(), false, false, 0);
5387           MemOpChains.push_back(Store);
5388
5389           // Float varargs are always shadowed in available integer registers
5390           if (GPR_idx != NumGPRs) {
5391             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5392                                        MachinePointerInfo(), false, false,
5393                                        false, 0);
5394             MemOpChains.push_back(Load.getValue(1));
5395             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5396           }
5397           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5398             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
5399             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5400             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5401                                        MachinePointerInfo(),
5402                                        false, false, false, 0);
5403             MemOpChains.push_back(Load.getValue(1));
5404             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5405           }
5406         } else {
5407           // If we have any FPRs remaining, we may also have GPRs remaining.
5408           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5409           // GPRs.
5410           if (GPR_idx != NumGPRs)
5411             ++GPR_idx;
5412           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5413               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5414             ++GPR_idx;
5415         }
5416       } else
5417         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5418                          isPPC64, isTailCall, false, MemOpChains,
5419                          TailCallArguments, dl);
5420       if (isPPC64)
5421         ArgOffset += 8;
5422       else
5423         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5424       break;
5425     case MVT::v4f32:
5426     case MVT::v4i32:
5427     case MVT::v8i16:
5428     case MVT::v16i8:
5429       if (isVarArg) {
5430         // These go aligned on the stack, or in the corresponding R registers
5431         // when within range.  The Darwin PPC ABI doc claims they also go in
5432         // V registers; in fact gcc does this only for arguments that are
5433         // prototyped, not for those that match the ...  We do it for all
5434         // arguments, seems to work.
5435         while (ArgOffset % 16 !=0) {
5436           ArgOffset += PtrByteSize;
5437           if (GPR_idx != NumGPRs)
5438             GPR_idx++;
5439         }
5440         // We could elide this store in the case where the object fits
5441         // entirely in R registers.  Maybe later.
5442         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5443                             DAG.getConstant(ArgOffset, PtrVT));
5444         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5445                                      MachinePointerInfo(), false, false, 0);
5446         MemOpChains.push_back(Store);
5447         if (VR_idx != NumVRs) {
5448           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5449                                      MachinePointerInfo(),
5450                                      false, false, false, 0);
5451           MemOpChains.push_back(Load.getValue(1));
5452           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5453         }
5454         ArgOffset += 16;
5455         for (unsigned i=0; i<16; i+=PtrByteSize) {
5456           if (GPR_idx == NumGPRs)
5457             break;
5458           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5459                                   DAG.getConstant(i, PtrVT));
5460           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5461                                      false, false, false, 0);
5462           MemOpChains.push_back(Load.getValue(1));
5463           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5464         }
5465         break;
5466       }
5467
5468       // Non-varargs Altivec params generally go in registers, but have
5469       // stack space allocated at the end.
5470       if (VR_idx != NumVRs) {
5471         // Doesn't have GPR space allocated.
5472         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5473       } else if (nAltivecParamsAtEnd==0) {
5474         // We are emitting Altivec params in order.
5475         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5476                          isPPC64, isTailCall, true, MemOpChains,
5477                          TailCallArguments, dl);
5478         ArgOffset += 16;
5479       }
5480       break;
5481     }
5482   }
5483   // If all Altivec parameters fit in registers, as they usually do,
5484   // they get stack space following the non-Altivec parameters.  We
5485   // don't track this here because nobody below needs it.
5486   // If there are more Altivec parameters than fit in registers emit
5487   // the stores here.
5488   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5489     unsigned j = 0;
5490     // Offset is aligned; skip 1st 12 params which go in V registers.
5491     ArgOffset = ((ArgOffset+15)/16)*16;
5492     ArgOffset += 12*16;
5493     for (unsigned i = 0; i != NumOps; ++i) {
5494       SDValue Arg = OutVals[i];
5495       EVT ArgType = Outs[i].VT;
5496       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5497           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5498         if (++j > NumVRs) {
5499           SDValue PtrOff;
5500           // We are emitting Altivec params in order.
5501           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5502                            isPPC64, isTailCall, true, MemOpChains,
5503                            TailCallArguments, dl);
5504           ArgOffset += 16;
5505         }
5506       }
5507     }
5508   }
5509
5510   if (!MemOpChains.empty())
5511     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5512
5513   // On Darwin, R12 must contain the address of an indirect callee.  This does
5514   // not mean the MTCTR instruction must use R12; it's easier to model this as
5515   // an extra parameter, so do that.
5516   if (!isTailCall &&
5517       !isFunctionGlobalAddress(Callee) &&
5518       !isa<ExternalSymbolSDNode>(Callee) &&
5519       !isBLACompatibleAddress(Callee, DAG))
5520     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5521                                                    PPC::R12), Callee));
5522
5523   // Build a sequence of copy-to-reg nodes chained together with token chain
5524   // and flag operands which copy the outgoing args into the appropriate regs.
5525   SDValue InFlag;
5526   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5527     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5528                              RegsToPass[i].second, InFlag);
5529     InFlag = Chain.getValue(1);
5530   }
5531
5532   if (isTailCall)
5533     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5534                     FPOp, true, TailCallArguments);
5535
5536   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5537                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5538                     NumBytes, Ins, InVals, CS);
5539 }
5540
5541 bool
5542 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5543                                   MachineFunction &MF, bool isVarArg,
5544                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5545                                   LLVMContext &Context) const {
5546   SmallVector<CCValAssign, 16> RVLocs;
5547   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5548   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5549 }
5550
5551 SDValue
5552 PPCTargetLowering::LowerReturn(SDValue Chain,
5553                                CallingConv::ID CallConv, bool isVarArg,
5554                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5555                                const SmallVectorImpl<SDValue> &OutVals,
5556                                SDLoc dl, SelectionDAG &DAG) const {
5557
5558   SmallVector<CCValAssign, 16> RVLocs;
5559   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5560                  *DAG.getContext());
5561   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5562
5563   SDValue Flag;
5564   SmallVector<SDValue, 4> RetOps(1, Chain);
5565
5566   // Copy the result values into the output registers.
5567   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5568     CCValAssign &VA = RVLocs[i];
5569     assert(VA.isRegLoc() && "Can only return in registers!");
5570
5571     SDValue Arg = OutVals[i];
5572
5573     switch (VA.getLocInfo()) {
5574     default: llvm_unreachable("Unknown loc info!");
5575     case CCValAssign::Full: break;
5576     case CCValAssign::AExt:
5577       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5578       break;
5579     case CCValAssign::ZExt:
5580       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5581       break;
5582     case CCValAssign::SExt:
5583       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5584       break;
5585     }
5586
5587     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5588     Flag = Chain.getValue(1);
5589     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5590   }
5591
5592   RetOps[0] = Chain;  // Update chain.
5593
5594   // Add the flag if we have it.
5595   if (Flag.getNode())
5596     RetOps.push_back(Flag);
5597
5598   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5599 }
5600
5601 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5602                                    const PPCSubtarget &Subtarget) const {
5603   // When we pop the dynamic allocation we need to restore the SP link.
5604   SDLoc dl(Op);
5605
5606   // Get the corect type for pointers.
5607   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5608
5609   // Construct the stack pointer operand.
5610   bool isPPC64 = Subtarget.isPPC64();
5611   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5612   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5613
5614   // Get the operands for the STACKRESTORE.
5615   SDValue Chain = Op.getOperand(0);
5616   SDValue SaveSP = Op.getOperand(1);
5617
5618   // Load the old link SP.
5619   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5620                                    MachinePointerInfo(),
5621                                    false, false, false, 0);
5622
5623   // Restore the stack pointer.
5624   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5625
5626   // Store the old link SP.
5627   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5628                       false, false, 0);
5629 }
5630
5631
5632
5633 SDValue
5634 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5635   MachineFunction &MF = DAG.getMachineFunction();
5636   bool isPPC64 = Subtarget.isPPC64();
5637   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5638
5639   // Get current frame pointer save index.  The users of this index will be
5640   // primarily DYNALLOC instructions.
5641   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5642   int RASI = FI->getReturnAddrSaveIndex();
5643
5644   // If the frame pointer save index hasn't been defined yet.
5645   if (!RASI) {
5646     // Find out what the fix offset of the frame pointer save area.
5647     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5648     // Allocate the frame index for frame pointer save area.
5649     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5650     // Save the result.
5651     FI->setReturnAddrSaveIndex(RASI);
5652   }
5653   return DAG.getFrameIndex(RASI, PtrVT);
5654 }
5655
5656 SDValue
5657 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5658   MachineFunction &MF = DAG.getMachineFunction();
5659   bool isPPC64 = Subtarget.isPPC64();
5660   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5661
5662   // Get current frame pointer save index.  The users of this index will be
5663   // primarily DYNALLOC instructions.
5664   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5665   int FPSI = FI->getFramePointerSaveIndex();
5666
5667   // If the frame pointer save index hasn't been defined yet.
5668   if (!FPSI) {
5669     // Find out what the fix offset of the frame pointer save area.
5670     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5671     // Allocate the frame index for frame pointer save area.
5672     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5673     // Save the result.
5674     FI->setFramePointerSaveIndex(FPSI);
5675   }
5676   return DAG.getFrameIndex(FPSI, PtrVT);
5677 }
5678
5679 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5680                                          SelectionDAG &DAG,
5681                                          const PPCSubtarget &Subtarget) const {
5682   // Get the inputs.
5683   SDValue Chain = Op.getOperand(0);
5684   SDValue Size  = Op.getOperand(1);
5685   SDLoc dl(Op);
5686
5687   // Get the corect type for pointers.
5688   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5689   // Negate the size.
5690   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5691                                   DAG.getConstant(0, PtrVT), Size);
5692   // Construct a node for the frame pointer save index.
5693   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5694   // Build a DYNALLOC node.
5695   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5696   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5697   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5698 }
5699
5700 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5701                                                SelectionDAG &DAG) const {
5702   SDLoc DL(Op);
5703   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5704                      DAG.getVTList(MVT::i32, MVT::Other),
5705                      Op.getOperand(0), Op.getOperand(1));
5706 }
5707
5708 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5709                                                 SelectionDAG &DAG) const {
5710   SDLoc DL(Op);
5711   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5712                      Op.getOperand(0), Op.getOperand(1));
5713 }
5714
5715 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5716   if (Op.getValueType().isVector())
5717     return LowerVectorLoad(Op, DAG);
5718
5719   assert(Op.getValueType() == MVT::i1 &&
5720          "Custom lowering only for i1 loads");
5721
5722   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5723
5724   SDLoc dl(Op);
5725   LoadSDNode *LD = cast<LoadSDNode>(Op);
5726
5727   SDValue Chain = LD->getChain();
5728   SDValue BasePtr = LD->getBasePtr();
5729   MachineMemOperand *MMO = LD->getMemOperand();
5730
5731   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5732                                  BasePtr, MVT::i8, MMO);
5733   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5734
5735   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5736   return DAG.getMergeValues(Ops, dl);
5737 }
5738
5739 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5740   if (Op.getOperand(1).getValueType().isVector())
5741     return LowerVectorStore(Op, DAG);
5742
5743   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5744          "Custom lowering only for i1 stores");
5745
5746   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5747
5748   SDLoc dl(Op);
5749   StoreSDNode *ST = cast<StoreSDNode>(Op);
5750
5751   SDValue Chain = ST->getChain();
5752   SDValue BasePtr = ST->getBasePtr();
5753   SDValue Value = ST->getValue();
5754   MachineMemOperand *MMO = ST->getMemOperand();
5755
5756   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5757   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5758 }
5759
5760 // FIXME: Remove this once the ANDI glue bug is fixed:
5761 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5762   assert(Op.getValueType() == MVT::i1 &&
5763          "Custom lowering only for i1 results");
5764
5765   SDLoc DL(Op);
5766   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5767                      Op.getOperand(0));
5768 }
5769
5770 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5771 /// possible.
5772 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5773   // Not FP? Not a fsel.
5774   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5775       !Op.getOperand(2).getValueType().isFloatingPoint())
5776     return Op;
5777
5778   // We might be able to do better than this under some circumstances, but in
5779   // general, fsel-based lowering of select is a finite-math-only optimization.
5780   // For more information, see section F.3 of the 2.06 ISA specification.
5781   if (!DAG.getTarget().Options.NoInfsFPMath ||
5782       !DAG.getTarget().Options.NoNaNsFPMath)
5783     return Op;
5784
5785   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5786
5787   EVT ResVT = Op.getValueType();
5788   EVT CmpVT = Op.getOperand(0).getValueType();
5789   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5790   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5791   SDLoc dl(Op);
5792
5793   // If the RHS of the comparison is a 0.0, we don't need to do the
5794   // subtraction at all.
5795   SDValue Sel1;
5796   if (isFloatingPointZero(RHS))
5797     switch (CC) {
5798     default: break;       // SETUO etc aren't handled by fsel.
5799     case ISD::SETNE:
5800       std::swap(TV, FV);
5801     case ISD::SETEQ:
5802       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5803         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5804       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5805       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5806         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5807       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5808                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5809     case ISD::SETULT:
5810     case ISD::SETLT:
5811       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5812     case ISD::SETOGE:
5813     case ISD::SETGE:
5814       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5815         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5816       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5817     case ISD::SETUGT:
5818     case ISD::SETGT:
5819       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5820     case ISD::SETOLE:
5821     case ISD::SETLE:
5822       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5823         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5824       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5825                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5826     }
5827
5828   SDValue Cmp;
5829   switch (CC) {
5830   default: break;       // SETUO etc aren't handled by fsel.
5831   case ISD::SETNE:
5832     std::swap(TV, FV);
5833   case ISD::SETEQ:
5834     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5835     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5836       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5837     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5838     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5839       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5840     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5841                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5842   case ISD::SETULT:
5843   case ISD::SETLT:
5844     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5845     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5846       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5847     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5848   case ISD::SETOGE:
5849   case ISD::SETGE:
5850     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5851     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5852       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5853     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5854   case ISD::SETUGT:
5855   case ISD::SETGT:
5856     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5857     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5858       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5859     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5860   case ISD::SETOLE:
5861   case ISD::SETLE:
5862     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5863     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5864       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5865     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5866   }
5867   return Op;
5868 }
5869
5870 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5871                                                SelectionDAG &DAG,
5872                                                SDLoc dl) const {
5873   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5874   SDValue Src = Op.getOperand(0);
5875   if (Src.getValueType() == MVT::f32)
5876     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5877
5878   SDValue Tmp;
5879   switch (Op.getSimpleValueType().SimpleTy) {
5880   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5881   case MVT::i32:
5882     Tmp = DAG.getNode(
5883         Op.getOpcode() == ISD::FP_TO_SINT
5884             ? PPCISD::FCTIWZ
5885             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5886         dl, MVT::f64, Src);
5887     break;
5888   case MVT::i64:
5889     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5890            "i64 FP_TO_UINT is supported only with FPCVT");
5891     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5892                                                         PPCISD::FCTIDUZ,
5893                       dl, MVT::f64, Src);
5894     break;
5895   }
5896
5897   // Convert the FP value to an int value through memory.
5898   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5899     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5900   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5901   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5902   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5903
5904   // Emit a store to the stack slot.
5905   SDValue Chain;
5906   if (i32Stack) {
5907     MachineFunction &MF = DAG.getMachineFunction();
5908     MachineMemOperand *MMO =
5909       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5910     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5911     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5912               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5913   } else
5914     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5915                          MPI, false, false, 0);
5916
5917   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5918   // add in a bias.
5919   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5920     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5921                         DAG.getConstant(4, FIPtr.getValueType()));
5922     MPI = MPI.getWithOffset(4);
5923   }
5924
5925   RLI.Chain = Chain;
5926   RLI.Ptr = FIPtr;
5927   RLI.MPI = MPI;
5928 }
5929
5930 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5931                                           SDLoc dl) const {
5932   ReuseLoadInfo RLI;
5933   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5934
5935   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5936                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5937                      RLI.Ranges);
5938 }
5939
5940 // We're trying to insert a regular store, S, and then a load, L. If the
5941 // incoming value, O, is a load, we might just be able to have our load use the
5942 // address used by O. However, we don't know if anything else will store to
5943 // that address before we can load from it. To prevent this situation, we need
5944 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5945 // the same chain operand as O, we create a token factor from the chain results
5946 // of O and L, and we replace all uses of O's chain result with that token
5947 // factor (see spliceIntoChain below for this last part).
5948 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5949                                             ReuseLoadInfo &RLI,
5950                                             SelectionDAG &DAG,
5951                                             ISD::LoadExtType ET) const {
5952   SDLoc dl(Op);
5953   if (ET == ISD::NON_EXTLOAD &&
5954       (Op.getOpcode() == ISD::FP_TO_UINT ||
5955        Op.getOpcode() == ISD::FP_TO_SINT) &&
5956       isOperationLegalOrCustom(Op.getOpcode(),
5957                                Op.getOperand(0).getValueType())) {
5958
5959     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5960     return true;
5961   }
5962
5963   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5964   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5965       LD->isNonTemporal())
5966     return false;
5967   if (LD->getMemoryVT() != MemVT)
5968     return false;
5969
5970   RLI.Ptr = LD->getBasePtr();
5971   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5972     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5973            "Non-pre-inc AM on PPC?");
5974     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5975                           LD->getOffset());
5976   }
5977
5978   RLI.Chain = LD->getChain();
5979   RLI.MPI = LD->getPointerInfo();
5980   RLI.IsInvariant = LD->isInvariant();
5981   RLI.Alignment = LD->getAlignment();
5982   RLI.AAInfo = LD->getAAInfo();
5983   RLI.Ranges = LD->getRanges();
5984
5985   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5986   return true;
5987 }
5988
5989 // Given the head of the old chain, ResChain, insert a token factor containing
5990 // it and NewResChain, and make users of ResChain now be users of that token
5991 // factor.
5992 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5993                                         SDValue NewResChain,
5994                                         SelectionDAG &DAG) const {
5995   if (!ResChain)
5996     return;
5997
5998   SDLoc dl(NewResChain);
5999
6000   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6001                            NewResChain, DAG.getUNDEF(MVT::Other));
6002   assert(TF.getNode() != NewResChain.getNode() &&
6003          "A new TF really is required here");
6004
6005   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6006   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6007 }
6008
6009 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6010                                           SelectionDAG &DAG) const {
6011   SDLoc dl(Op);
6012
6013   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6014     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6015       return SDValue();
6016
6017     SDValue Value = Op.getOperand(0);
6018     // The values are now known to be -1 (false) or 1 (true). To convert this
6019     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6020     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6021     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6022   
6023     SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
6024     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6025                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6026   
6027     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6028
6029     if (Op.getValueType() != MVT::v4f64)
6030       Value = DAG.getNode(ISD::FP_ROUND, dl,
6031                           Op.getValueType(), Value, DAG.getIntPtrConstant(1));
6032     return Value;
6033   }
6034
6035   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6036   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6037     return SDValue();
6038
6039   if (Op.getOperand(0).getValueType() == MVT::i1)
6040     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6041                        DAG.getConstantFP(1.0, Op.getValueType()),
6042                        DAG.getConstantFP(0.0, Op.getValueType()));
6043
6044   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6045          "UINT_TO_FP is supported only with FPCVT");
6046
6047   // If we have FCFIDS, then use it when converting to single-precision.
6048   // Otherwise, convert to double-precision and then round.
6049   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6050                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6051                                                             : PPCISD::FCFIDS)
6052                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6053                                                             : PPCISD::FCFID);
6054   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6055                   ? MVT::f32
6056                   : MVT::f64;
6057
6058   if (Op.getOperand(0).getValueType() == MVT::i64) {
6059     SDValue SINT = Op.getOperand(0);
6060     // When converting to single-precision, we actually need to convert
6061     // to double-precision first and then round to single-precision.
6062     // To avoid double-rounding effects during that operation, we have
6063     // to prepare the input operand.  Bits that might be truncated when
6064     // converting to double-precision are replaced by a bit that won't
6065     // be lost at this stage, but is below the single-precision rounding
6066     // position.
6067     //
6068     // However, if -enable-unsafe-fp-math is in effect, accept double
6069     // rounding to avoid the extra overhead.
6070     if (Op.getValueType() == MVT::f32 &&
6071         !Subtarget.hasFPCVT() &&
6072         !DAG.getTarget().Options.UnsafeFPMath) {
6073
6074       // Twiddle input to make sure the low 11 bits are zero.  (If this
6075       // is the case, we are guaranteed the value will fit into the 53 bit
6076       // mantissa of an IEEE double-precision value without rounding.)
6077       // If any of those low 11 bits were not zero originally, make sure
6078       // bit 12 (value 2048) is set instead, so that the final rounding
6079       // to single-precision gets the correct result.
6080       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6081                                   SINT, DAG.getConstant(2047, MVT::i64));
6082       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6083                           Round, DAG.getConstant(2047, MVT::i64));
6084       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6085       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6086                           Round, DAG.getConstant(-2048, MVT::i64));
6087
6088       // However, we cannot use that value unconditionally: if the magnitude
6089       // of the input value is small, the bit-twiddling we did above might
6090       // end up visibly changing the output.  Fortunately, in that case, we
6091       // don't need to twiddle bits since the original input will convert
6092       // exactly to double-precision floating-point already.  Therefore,
6093       // construct a conditional to use the original value if the top 11
6094       // bits are all sign-bit copies, and use the rounded value computed
6095       // above otherwise.
6096       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6097                                  SINT, DAG.getConstant(53, MVT::i32));
6098       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6099                          Cond, DAG.getConstant(1, MVT::i64));
6100       Cond = DAG.getSetCC(dl, MVT::i32,
6101                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
6102
6103       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6104     }
6105
6106     ReuseLoadInfo RLI;
6107     SDValue Bits;
6108
6109     MachineFunction &MF = DAG.getMachineFunction();
6110     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6111       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6112                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6113                          RLI.Ranges);
6114       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6115     } else if (Subtarget.hasLFIWAX() &&
6116                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6117       MachineMemOperand *MMO =
6118         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6119                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6120       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6121       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6122                                      DAG.getVTList(MVT::f64, MVT::Other),
6123                                      Ops, MVT::i32, MMO);
6124       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6125     } else if (Subtarget.hasFPCVT() &&
6126                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6127       MachineMemOperand *MMO =
6128         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6129                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6130       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6131       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6132                                      DAG.getVTList(MVT::f64, MVT::Other),
6133                                      Ops, MVT::i32, MMO);
6134       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6135     } else if (((Subtarget.hasLFIWAX() &&
6136                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6137                 (Subtarget.hasFPCVT() &&
6138                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6139                SINT.getOperand(0).getValueType() == MVT::i32) {
6140       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6141       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6142
6143       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6144       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6145
6146       SDValue Store =
6147         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6148                      MachinePointerInfo::getFixedStack(FrameIdx),
6149                      false, false, 0);
6150
6151       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6152              "Expected an i32 store");
6153
6154       RLI.Ptr = FIdx;
6155       RLI.Chain = Store;
6156       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6157       RLI.Alignment = 4;
6158
6159       MachineMemOperand *MMO =
6160         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6161                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6162       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6163       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6164                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6165                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6166                                      Ops, MVT::i32, MMO);
6167     } else
6168       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6169
6170     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6171
6172     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6173       FP = DAG.getNode(ISD::FP_ROUND, dl,
6174                        MVT::f32, FP, DAG.getIntPtrConstant(0));
6175     return FP;
6176   }
6177
6178   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6179          "Unhandled INT_TO_FP type in custom expander!");
6180   // Since we only generate this in 64-bit mode, we can take advantage of
6181   // 64-bit registers.  In particular, sign extend the input value into the
6182   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6183   // then lfd it and fcfid it.
6184   MachineFunction &MF = DAG.getMachineFunction();
6185   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6186   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6187
6188   SDValue Ld;
6189   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6190     ReuseLoadInfo RLI;
6191     bool ReusingLoad;
6192     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6193                                             DAG))) {
6194       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6195       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6196
6197       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6198                                    MachinePointerInfo::getFixedStack(FrameIdx),
6199                                    false, false, 0);
6200
6201       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6202              "Expected an i32 store");
6203
6204       RLI.Ptr = FIdx;
6205       RLI.Chain = Store;
6206       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6207       RLI.Alignment = 4;
6208     }
6209
6210     MachineMemOperand *MMO =
6211       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6212                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6213     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6214     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6215                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6216                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6217                                  Ops, MVT::i32, MMO);
6218     if (ReusingLoad)
6219       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6220   } else {
6221     assert(Subtarget.isPPC64() &&
6222            "i32->FP without LFIWAX supported only on PPC64");
6223
6224     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6225     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6226
6227     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6228                                 Op.getOperand(0));
6229
6230     // STD the extended value into the stack slot.
6231     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6232                                  MachinePointerInfo::getFixedStack(FrameIdx),
6233                                  false, false, 0);
6234
6235     // Load the value as a double.
6236     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6237                      MachinePointerInfo::getFixedStack(FrameIdx),
6238                      false, false, false, 0);
6239   }
6240
6241   // FCFID it and return it.
6242   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6243   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6244     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
6245   return FP;
6246 }
6247
6248 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6249                                             SelectionDAG &DAG) const {
6250   SDLoc dl(Op);
6251   /*
6252    The rounding mode is in bits 30:31 of FPSR, and has the following
6253    settings:
6254      00 Round to nearest
6255      01 Round to 0
6256      10 Round to +inf
6257      11 Round to -inf
6258
6259   FLT_ROUNDS, on the other hand, expects the following:
6260     -1 Undefined
6261      0 Round to 0
6262      1 Round to nearest
6263      2 Round to +inf
6264      3 Round to -inf
6265
6266   To perform the conversion, we do:
6267     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6268   */
6269
6270   MachineFunction &MF = DAG.getMachineFunction();
6271   EVT VT = Op.getValueType();
6272   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6273
6274   // Save FP Control Word to register
6275   EVT NodeTys[] = {
6276     MVT::f64,    // return register
6277     MVT::Glue    // unused in this context
6278   };
6279   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6280
6281   // Save FP register to stack slot
6282   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6283   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6284   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6285                                StackSlot, MachinePointerInfo(), false, false,0);
6286
6287   // Load FP Control Word from low 32 bits of stack slot.
6288   SDValue Four = DAG.getConstant(4, PtrVT);
6289   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6290   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6291                             false, false, false, 0);
6292
6293   // Transform as necessary
6294   SDValue CWD1 =
6295     DAG.getNode(ISD::AND, dl, MVT::i32,
6296                 CWD, DAG.getConstant(3, MVT::i32));
6297   SDValue CWD2 =
6298     DAG.getNode(ISD::SRL, dl, MVT::i32,
6299                 DAG.getNode(ISD::AND, dl, MVT::i32,
6300                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6301                                         CWD, DAG.getConstant(3, MVT::i32)),
6302                             DAG.getConstant(3, MVT::i32)),
6303                 DAG.getConstant(1, MVT::i32));
6304
6305   SDValue RetVal =
6306     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6307
6308   return DAG.getNode((VT.getSizeInBits() < 16 ?
6309                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6310 }
6311
6312 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6313   EVT VT = Op.getValueType();
6314   unsigned BitWidth = VT.getSizeInBits();
6315   SDLoc dl(Op);
6316   assert(Op.getNumOperands() == 3 &&
6317          VT == Op.getOperand(1).getValueType() &&
6318          "Unexpected SHL!");
6319
6320   // Expand into a bunch of logical ops.  Note that these ops
6321   // depend on the PPC behavior for oversized shift amounts.
6322   SDValue Lo = Op.getOperand(0);
6323   SDValue Hi = Op.getOperand(1);
6324   SDValue Amt = Op.getOperand(2);
6325   EVT AmtVT = Amt.getValueType();
6326
6327   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6328                              DAG.getConstant(BitWidth, AmtVT), Amt);
6329   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6330   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6331   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6332   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6333                              DAG.getConstant(-BitWidth, AmtVT));
6334   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6335   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6336   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6337   SDValue OutOps[] = { OutLo, OutHi };
6338   return DAG.getMergeValues(OutOps, dl);
6339 }
6340
6341 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6342   EVT VT = Op.getValueType();
6343   SDLoc dl(Op);
6344   unsigned BitWidth = VT.getSizeInBits();
6345   assert(Op.getNumOperands() == 3 &&
6346          VT == Op.getOperand(1).getValueType() &&
6347          "Unexpected SRL!");
6348
6349   // Expand into a bunch of logical ops.  Note that these ops
6350   // depend on the PPC behavior for oversized shift amounts.
6351   SDValue Lo = Op.getOperand(0);
6352   SDValue Hi = Op.getOperand(1);
6353   SDValue Amt = Op.getOperand(2);
6354   EVT AmtVT = Amt.getValueType();
6355
6356   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6357                              DAG.getConstant(BitWidth, AmtVT), Amt);
6358   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6359   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6360   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6361   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6362                              DAG.getConstant(-BitWidth, AmtVT));
6363   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6364   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6365   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6366   SDValue OutOps[] = { OutLo, OutHi };
6367   return DAG.getMergeValues(OutOps, dl);
6368 }
6369
6370 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6371   SDLoc dl(Op);
6372   EVT VT = Op.getValueType();
6373   unsigned BitWidth = VT.getSizeInBits();
6374   assert(Op.getNumOperands() == 3 &&
6375          VT == Op.getOperand(1).getValueType() &&
6376          "Unexpected SRA!");
6377
6378   // Expand into a bunch of logical ops, followed by a select_cc.
6379   SDValue Lo = Op.getOperand(0);
6380   SDValue Hi = Op.getOperand(1);
6381   SDValue Amt = Op.getOperand(2);
6382   EVT AmtVT = Amt.getValueType();
6383
6384   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6385                              DAG.getConstant(BitWidth, AmtVT), Amt);
6386   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6387   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6388   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6389   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6390                              DAG.getConstant(-BitWidth, AmtVT));
6391   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6392   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6393   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
6394                                   Tmp4, Tmp6, ISD::SETLE);
6395   SDValue OutOps[] = { OutLo, OutHi };
6396   return DAG.getMergeValues(OutOps, dl);
6397 }
6398
6399 //===----------------------------------------------------------------------===//
6400 // Vector related lowering.
6401 //
6402
6403 /// BuildSplatI - Build a canonical splati of Val with an element size of
6404 /// SplatSize.  Cast the result to VT.
6405 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6406                              SelectionDAG &DAG, SDLoc dl) {
6407   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6408
6409   static const MVT VTys[] = { // canonical VT to use for each size.
6410     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6411   };
6412
6413   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6414
6415   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6416   if (Val == -1)
6417     SplatSize = 1;
6418
6419   EVT CanonicalVT = VTys[SplatSize-1];
6420
6421   // Build a canonical splat for this value.
6422   SDValue Elt = DAG.getConstant(Val, MVT::i32);
6423   SmallVector<SDValue, 8> Ops;
6424   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6425   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6426   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6427 }
6428
6429 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6430 /// specified intrinsic ID.
6431 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6432                                 SelectionDAG &DAG, SDLoc dl,
6433                                 EVT DestVT = MVT::Other) {
6434   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6435   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6436                      DAG.getConstant(IID, MVT::i32), Op);
6437 }
6438
6439 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6440 /// specified intrinsic ID.
6441 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6442                                 SelectionDAG &DAG, SDLoc dl,
6443                                 EVT DestVT = MVT::Other) {
6444   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6445   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6446                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
6447 }
6448
6449 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6450 /// specified intrinsic ID.
6451 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6452                                 SDValue Op2, SelectionDAG &DAG,
6453                                 SDLoc dl, EVT DestVT = MVT::Other) {
6454   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6455   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6456                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
6457 }
6458
6459
6460 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6461 /// amount.  The result has the specified value type.
6462 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6463                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6464   // Force LHS/RHS to be the right type.
6465   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6466   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6467
6468   int Ops[16];
6469   for (unsigned i = 0; i != 16; ++i)
6470     Ops[i] = i + Amt;
6471   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6472   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6473 }
6474
6475 // If this is a case we can't handle, return null and let the default
6476 // expansion code take care of it.  If we CAN select this case, and if it
6477 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6478 // this case more efficiently than a constant pool load, lower it to the
6479 // sequence of ops that should be used.
6480 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6481                                              SelectionDAG &DAG) const {
6482   SDLoc dl(Op);
6483   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6484   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6485
6486   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6487     // We first build an i32 vector, load it into a QPX register,
6488     // then convert it to a floating-point vector and compare it
6489     // to a zero vector to get the boolean result.
6490     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6491     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6492     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6493     EVT PtrVT = getPointerTy();
6494     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6495
6496     assert(BVN->getNumOperands() == 4 &&
6497       "BUILD_VECTOR for v4i1 does not have 4 operands");
6498
6499     bool IsConst = true;
6500     for (unsigned i = 0; i < 4; ++i) {
6501       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6502       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6503         IsConst = false;
6504         break;
6505       }
6506     }
6507
6508     if (IsConst) {
6509       Constant *One =
6510         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6511       Constant *NegOne =
6512         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6513
6514       SmallVector<Constant*, 4> CV(4, NegOne);
6515       for (unsigned i = 0; i < 4; ++i) {
6516         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6517           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6518         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6519                    getConstantIntValue()->isZero())
6520           continue;
6521         else
6522           CV[i] = One;
6523       }
6524
6525       Constant *CP = ConstantVector::get(CV);
6526       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6527                       16 /* alignment */);
6528  
6529       SmallVector<SDValue, 2> Ops;
6530       Ops.push_back(DAG.getEntryNode());
6531       Ops.push_back(CPIdx);
6532
6533       SmallVector<EVT, 2> ValueVTs;
6534       ValueVTs.push_back(MVT::v4i1);
6535       ValueVTs.push_back(MVT::Other); // chain
6536       SDVTList VTs = DAG.getVTList(ValueVTs);
6537
6538       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6539         dl, VTs, Ops, MVT::v4f32,
6540         MachinePointerInfo::getConstantPool());
6541     }
6542
6543     SmallVector<SDValue, 4> Stores;
6544     for (unsigned i = 0; i < 4; ++i) {
6545       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6546
6547       unsigned Offset = 4*i;
6548       SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
6549       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6550
6551       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6552       if (StoreSize > 4) {
6553         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6554                                            BVN->getOperand(i), Idx,
6555                                            PtrInfo.getWithOffset(Offset),
6556                                            MVT::i32, false, false, 0));
6557       } else {
6558         SDValue StoreValue = BVN->getOperand(i);
6559         if (StoreSize < 4)
6560           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6561
6562         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6563                                       StoreValue, Idx,
6564                                       PtrInfo.getWithOffset(Offset),
6565                                       false, false, 0));
6566       }
6567     }
6568
6569     SDValue StoreChain;
6570     if (!Stores.empty())
6571       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6572     else
6573       StoreChain = DAG.getEntryNode();
6574
6575     // Now load from v4i32 into the QPX register; this will extend it to
6576     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6577     // is typed as v4f64 because the QPX register integer states are not
6578     // explicitly represented.
6579
6580     SmallVector<SDValue, 2> Ops;
6581     Ops.push_back(StoreChain);
6582     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, MVT::i32));
6583     Ops.push_back(FIdx);
6584
6585     SmallVector<EVT, 2> ValueVTs;
6586     ValueVTs.push_back(MVT::v4f64);
6587     ValueVTs.push_back(MVT::Other); // chain
6588     SDVTList VTs = DAG.getVTList(ValueVTs);
6589
6590     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6591       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6592     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6593       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, MVT::i32),
6594       LoadedVect);
6595
6596     SDValue FPZeros = DAG.getConstantFP(0.0, MVT::f64);
6597     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6598                           FPZeros, FPZeros, FPZeros, FPZeros);
6599
6600     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6601   }
6602
6603   // All other QPX vectors are handled by generic code.
6604   if (Subtarget.hasQPX())
6605     return SDValue();
6606
6607   // Check if this is a splat of a constant value.
6608   APInt APSplatBits, APSplatUndef;
6609   unsigned SplatBitSize;
6610   bool HasAnyUndefs;
6611   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6612                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6613     return SDValue();
6614
6615   unsigned SplatBits = APSplatBits.getZExtValue();
6616   unsigned SplatUndef = APSplatUndef.getZExtValue();
6617   unsigned SplatSize = SplatBitSize / 8;
6618
6619   // First, handle single instruction cases.
6620
6621   // All zeros?
6622   if (SplatBits == 0) {
6623     // Canonicalize all zero vectors to be v4i32.
6624     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6625       SDValue Z = DAG.getConstant(0, MVT::i32);
6626       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6627       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6628     }
6629     return Op;
6630   }
6631
6632   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6633   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6634                     (32-SplatBitSize));
6635   if (SextVal >= -16 && SextVal <= 15)
6636     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6637
6638
6639   // Two instruction sequences.
6640
6641   // If this value is in the range [-32,30] and is even, use:
6642   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6643   // If this value is in the range [17,31] and is odd, use:
6644   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6645   // If this value is in the range [-31,-17] and is odd, use:
6646   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6647   // Note the last two are three-instruction sequences.
6648   if (SextVal >= -32 && SextVal <= 31) {
6649     // To avoid having these optimizations undone by constant folding,
6650     // we convert to a pseudo that will be expanded later into one of
6651     // the above forms.
6652     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6653     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6654               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6655     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6656     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6657     if (VT == Op.getValueType())
6658       return RetVal;
6659     else
6660       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6661   }
6662
6663   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6664   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6665   // for fneg/fabs.
6666   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6667     // Make -1 and vspltisw -1:
6668     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6669
6670     // Make the VSLW intrinsic, computing 0x8000_0000.
6671     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6672                                    OnesV, DAG, dl);
6673
6674     // xor by OnesV to invert it.
6675     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6676     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6677   }
6678
6679   // The remaining cases assume either big endian element order or
6680   // a splat-size that equates to the element size of the vector
6681   // to be built.  An example that doesn't work for little endian is
6682   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6683   // and a vector element size of 16 bits.  The code below will
6684   // produce the vector in big endian element order, which for little
6685   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6686
6687   // For now, just avoid these optimizations in that case.
6688   // FIXME: Develop correct optimizations for LE with mismatched
6689   // splat and element sizes.
6690
6691   if (Subtarget.isLittleEndian() &&
6692       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6693     return SDValue();
6694
6695   // Check to see if this is a wide variety of vsplti*, binop self cases.
6696   static const signed char SplatCsts[] = {
6697     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6698     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6699   };
6700
6701   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6702     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6703     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6704     int i = SplatCsts[idx];
6705
6706     // Figure out what shift amount will be used by altivec if shifted by i in
6707     // this splat size.
6708     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6709
6710     // vsplti + shl self.
6711     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6712       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6713       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6714         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6715         Intrinsic::ppc_altivec_vslw
6716       };
6717       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6718       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6719     }
6720
6721     // vsplti + srl self.
6722     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6723       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6724       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6725         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6726         Intrinsic::ppc_altivec_vsrw
6727       };
6728       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6729       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6730     }
6731
6732     // vsplti + sra self.
6733     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6734       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6735       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6736         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6737         Intrinsic::ppc_altivec_vsraw
6738       };
6739       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6740       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6741     }
6742
6743     // vsplti + rol self.
6744     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6745                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6746       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6747       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6748         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6749         Intrinsic::ppc_altivec_vrlw
6750       };
6751       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6752       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6753     }
6754
6755     // t = vsplti c, result = vsldoi t, t, 1
6756     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6757       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6758       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6759     }
6760     // t = vsplti c, result = vsldoi t, t, 2
6761     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6762       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6763       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6764     }
6765     // t = vsplti c, result = vsldoi t, t, 3
6766     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6767       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6768       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6769     }
6770   }
6771
6772   return SDValue();
6773 }
6774
6775 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6776 /// the specified operations to build the shuffle.
6777 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6778                                       SDValue RHS, SelectionDAG &DAG,
6779                                       SDLoc dl) {
6780   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6781   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6782   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6783
6784   enum {
6785     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6786     OP_VMRGHW,
6787     OP_VMRGLW,
6788     OP_VSPLTISW0,
6789     OP_VSPLTISW1,
6790     OP_VSPLTISW2,
6791     OP_VSPLTISW3,
6792     OP_VSLDOI4,
6793     OP_VSLDOI8,
6794     OP_VSLDOI12
6795   };
6796
6797   if (OpNum == OP_COPY) {
6798     if (LHSID == (1*9+2)*9+3) return LHS;
6799     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6800     return RHS;
6801   }
6802
6803   SDValue OpLHS, OpRHS;
6804   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6805   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6806
6807   int ShufIdxs[16];
6808   switch (OpNum) {
6809   default: llvm_unreachable("Unknown i32 permute!");
6810   case OP_VMRGHW:
6811     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6812     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6813     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6814     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6815     break;
6816   case OP_VMRGLW:
6817     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6818     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6819     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6820     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6821     break;
6822   case OP_VSPLTISW0:
6823     for (unsigned i = 0; i != 16; ++i)
6824       ShufIdxs[i] = (i&3)+0;
6825     break;
6826   case OP_VSPLTISW1:
6827     for (unsigned i = 0; i != 16; ++i)
6828       ShufIdxs[i] = (i&3)+4;
6829     break;
6830   case OP_VSPLTISW2:
6831     for (unsigned i = 0; i != 16; ++i)
6832       ShufIdxs[i] = (i&3)+8;
6833     break;
6834   case OP_VSPLTISW3:
6835     for (unsigned i = 0; i != 16; ++i)
6836       ShufIdxs[i] = (i&3)+12;
6837     break;
6838   case OP_VSLDOI4:
6839     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6840   case OP_VSLDOI8:
6841     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6842   case OP_VSLDOI12:
6843     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6844   }
6845   EVT VT = OpLHS.getValueType();
6846   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6847   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6848   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6849   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6850 }
6851
6852 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6853 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6854 /// return the code it can be lowered into.  Worst case, it can always be
6855 /// lowered into a vperm.
6856 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6857                                                SelectionDAG &DAG) const {
6858   SDLoc dl(Op);
6859   SDValue V1 = Op.getOperand(0);
6860   SDValue V2 = Op.getOperand(1);
6861   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6862   EVT VT = Op.getValueType();
6863   bool isLittleEndian = Subtarget.isLittleEndian();
6864
6865   if (Subtarget.hasQPX()) {
6866     if (VT.getVectorNumElements() != 4)
6867       return SDValue();
6868
6869     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6870
6871     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
6872     if (AlignIdx != -1) {
6873       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
6874                          DAG.getConstant(AlignIdx, MVT::i32));
6875     } else if (SVOp->isSplat()) {
6876       int SplatIdx = SVOp->getSplatIndex();
6877       if (SplatIdx >= 4) {
6878         std::swap(V1, V2);
6879         SplatIdx -= 4;
6880       }
6881
6882       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
6883       // nothing to do.
6884
6885       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
6886                          DAG.getConstant(SplatIdx, MVT::i32));
6887     }
6888
6889     // Lower this into a qvgpci/qvfperm pair.
6890
6891     // Compute the qvgpci literal
6892     unsigned idx = 0;
6893     for (unsigned i = 0; i < 4; ++i) {
6894       int m = SVOp->getMaskElt(i);
6895       unsigned mm = m >= 0 ? (unsigned) m : i;
6896       idx |= mm << (3-i)*3;
6897     }
6898
6899     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
6900                              DAG.getConstant(idx, MVT::i32));
6901     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
6902   }
6903
6904   // Cases that are handled by instructions that take permute immediates
6905   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6906   // selected by the instruction selector.
6907   if (V2.getOpcode() == ISD::UNDEF) {
6908     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6909         PPC::isSplatShuffleMask(SVOp, 2) ||
6910         PPC::isSplatShuffleMask(SVOp, 4) ||
6911         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6912         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6913         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6914         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6915         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6916         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6917         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6918         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6919         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6920       return Op;
6921     }
6922   }
6923
6924   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6925   // and produce a fixed permutation.  If any of these match, do not lower to
6926   // VPERM.
6927   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6928   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6929       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6930       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6931       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6932       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6933       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6934       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6935       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6936       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6937     return Op;
6938
6939   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6940   // perfect shuffle table to emit an optimal matching sequence.
6941   ArrayRef<int> PermMask = SVOp->getMask();
6942
6943   unsigned PFIndexes[4];
6944   bool isFourElementShuffle = true;
6945   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6946     unsigned EltNo = 8;   // Start out undef.
6947     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6948       if (PermMask[i*4+j] < 0)
6949         continue;   // Undef, ignore it.
6950
6951       unsigned ByteSource = PermMask[i*4+j];
6952       if ((ByteSource & 3) != j) {
6953         isFourElementShuffle = false;
6954         break;
6955       }
6956
6957       if (EltNo == 8) {
6958         EltNo = ByteSource/4;
6959       } else if (EltNo != ByteSource/4) {
6960         isFourElementShuffle = false;
6961         break;
6962       }
6963     }
6964     PFIndexes[i] = EltNo;
6965   }
6966
6967   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6968   // perfect shuffle vector to determine if it is cost effective to do this as
6969   // discrete instructions, or whether we should use a vperm.
6970   // For now, we skip this for little endian until such time as we have a
6971   // little-endian perfect shuffle table.
6972   if (isFourElementShuffle && !isLittleEndian) {
6973     // Compute the index in the perfect shuffle table.
6974     unsigned PFTableIndex =
6975       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6976
6977     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6978     unsigned Cost  = (PFEntry >> 30);
6979
6980     // Determining when to avoid vperm is tricky.  Many things affect the cost
6981     // of vperm, particularly how many times the perm mask needs to be computed.
6982     // For example, if the perm mask can be hoisted out of a loop or is already
6983     // used (perhaps because there are multiple permutes with the same shuffle
6984     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6985     // the loop requires an extra register.
6986     //
6987     // As a compromise, we only emit discrete instructions if the shuffle can be
6988     // generated in 3 or fewer operations.  When we have loop information
6989     // available, if this block is within a loop, we should avoid using vperm
6990     // for 3-operation perms and use a constant pool load instead.
6991     if (Cost < 3)
6992       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6993   }
6994
6995   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6996   // vector that will get spilled to the constant pool.
6997   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6998
6999   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7000   // that it is in input element units, not in bytes.  Convert now.
7001
7002   // For little endian, the order of the input vectors is reversed, and
7003   // the permutation mask is complemented with respect to 31.  This is
7004   // necessary to produce proper semantics with the big-endian-biased vperm
7005   // instruction.
7006   EVT EltVT = V1.getValueType().getVectorElementType();
7007   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7008
7009   SmallVector<SDValue, 16> ResultMask;
7010   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7011     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7012
7013     for (unsigned j = 0; j != BytesPerElement; ++j)
7014       if (isLittleEndian)
7015         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
7016                                              MVT::i32));
7017       else
7018         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
7019                                              MVT::i32));
7020   }
7021
7022   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7023                                   ResultMask);
7024   if (isLittleEndian)
7025     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7026                        V2, V1, VPermMask);
7027   else
7028     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7029                        V1, V2, VPermMask);
7030 }
7031
7032 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7033 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7034 /// information about the intrinsic.
7035 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7036                                   bool &isDot, const PPCSubtarget &Subtarget) {
7037   unsigned IntrinsicID =
7038     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7039   CompareOpc = -1;
7040   isDot = false;
7041   switch (IntrinsicID) {
7042   default: return false;
7043     // Comparison predicates.
7044   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7045   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7046   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7047   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7048   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7049   case Intrinsic::ppc_altivec_vcmpequd_p: 
7050     if (Subtarget.hasP8Altivec()) {
7051       CompareOpc = 199; 
7052       isDot = 1; 
7053     }
7054     else 
7055       return false;
7056
7057     break;
7058   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7059   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7060   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7061   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7062   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7063   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7064     if (Subtarget.hasP8Altivec()) {
7065       CompareOpc = 967; 
7066       isDot = 1; 
7067     }
7068     else 
7069       return false;
7070
7071     break;
7072   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7073   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7074   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7075   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7076     if (Subtarget.hasP8Altivec()) {
7077       CompareOpc = 711; 
7078       isDot = 1; 
7079     }
7080     else 
7081       return false;
7082
7083     break;
7084       
7085     // Normal Comparisons.
7086   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7087   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7088   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7089   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7090   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7091   case Intrinsic::ppc_altivec_vcmpequd:
7092     if (Subtarget.hasP8Altivec()) {
7093       CompareOpc = 199; 
7094       isDot = 0; 
7095     }
7096     else
7097       return false;
7098
7099     break;
7100   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7101   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7102   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7103   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7104   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7105   case Intrinsic::ppc_altivec_vcmpgtsd:   
7106     if (Subtarget.hasP8Altivec()) {
7107       CompareOpc = 967; 
7108       isDot = 0; 
7109     }
7110     else
7111       return false;
7112
7113     break;
7114   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7115   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7116   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7117   case Intrinsic::ppc_altivec_vcmpgtud:   
7118     if (Subtarget.hasP8Altivec()) {
7119       CompareOpc = 711; 
7120       isDot = 0; 
7121     }
7122     else
7123       return false;
7124
7125     break;
7126   }
7127   return true;
7128 }
7129
7130 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7131 /// lower, do it, otherwise return null.
7132 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7133                                                    SelectionDAG &DAG) const {
7134   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7135   // opcode number of the comparison.
7136   SDLoc dl(Op);
7137   int CompareOpc;
7138   bool isDot;
7139   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7140     return SDValue();    // Don't custom lower most intrinsics.
7141
7142   // If this is a non-dot comparison, make the VCMP node and we are done.
7143   if (!isDot) {
7144     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7145                               Op.getOperand(1), Op.getOperand(2),
7146                               DAG.getConstant(CompareOpc, MVT::i32));
7147     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7148   }
7149
7150   // Create the PPCISD altivec 'dot' comparison node.
7151   SDValue Ops[] = {
7152     Op.getOperand(2),  // LHS
7153     Op.getOperand(3),  // RHS
7154     DAG.getConstant(CompareOpc, MVT::i32)
7155   };
7156   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7157   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7158
7159   // Now that we have the comparison, emit a copy from the CR to a GPR.
7160   // This is flagged to the above dot comparison.
7161   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7162                                 DAG.getRegister(PPC::CR6, MVT::i32),
7163                                 CompNode.getValue(1));
7164
7165   // Unpack the result based on how the target uses it.
7166   unsigned BitNo;   // Bit # of CR6.
7167   bool InvertBit;   // Invert result?
7168   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7169   default:  // Can't happen, don't crash on invalid number though.
7170   case 0:   // Return the value of the EQ bit of CR6.
7171     BitNo = 0; InvertBit = false;
7172     break;
7173   case 1:   // Return the inverted value of the EQ bit of CR6.
7174     BitNo = 0; InvertBit = true;
7175     break;
7176   case 2:   // Return the value of the LT bit of CR6.
7177     BitNo = 2; InvertBit = false;
7178     break;
7179   case 3:   // Return the inverted value of the LT bit of CR6.
7180     BitNo = 2; InvertBit = true;
7181     break;
7182   }
7183
7184   // Shift the bit into the low position.
7185   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7186                       DAG.getConstant(8-(3-BitNo), MVT::i32));
7187   // Isolate the bit.
7188   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7189                       DAG.getConstant(1, MVT::i32));
7190
7191   // If we are supposed to, toggle the bit.
7192   if (InvertBit)
7193     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7194                         DAG.getConstant(1, MVT::i32));
7195   return Flags;
7196 }
7197
7198 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7199                                                   SelectionDAG &DAG) const {
7200   SDLoc dl(Op);
7201   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7202   // instructions), but for smaller types, we need to first extend up to v2i32
7203   // before doing going farther.
7204   if (Op.getValueType() == MVT::v2i64) {
7205     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7206     if (ExtVT != MVT::v2i32) {
7207       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7208       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7209                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7210                                         ExtVT.getVectorElementType(), 4)));
7211       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7212       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7213                        DAG.getValueType(MVT::v2i32));
7214     }
7215
7216     return Op;
7217   }
7218
7219   return SDValue();
7220 }
7221
7222 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7223                                                    SelectionDAG &DAG) const {
7224   SDLoc dl(Op);
7225   // Create a stack slot that is 16-byte aligned.
7226   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7227   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7228   EVT PtrVT = getPointerTy();
7229   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7230
7231   // Store the input value into Value#0 of the stack slot.
7232   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7233                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7234                                false, false, 0);
7235   // Load it out.
7236   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7237                      false, false, false, 0);
7238 }
7239
7240 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7241                                                    SelectionDAG &DAG) const {
7242   SDLoc dl(Op);
7243   SDNode *N = Op.getNode();
7244
7245   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7246          "Unknown extract_vector_elt type");
7247
7248   SDValue Value = N->getOperand(0);
7249
7250   // The first part of this is like the store lowering except that we don't
7251   // need to track the chain.
7252
7253   // The values are now known to be -1 (false) or 1 (true). To convert this
7254   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7255   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7256   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7257
7258   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7259   // understand how to form the extending load.
7260   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7261   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7262                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7263
7264   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7265
7266   // Now convert to an integer and store.
7267   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7268     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7269     Value);
7270
7271   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7272   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7273   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7274   EVT PtrVT = getPointerTy();
7275   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7276
7277   SDValue StoreChain = DAG.getEntryNode();
7278   SmallVector<SDValue, 2> Ops;
7279   Ops.push_back(StoreChain);
7280   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7281   Ops.push_back(Value);
7282   Ops.push_back(FIdx);
7283
7284   SmallVector<EVT, 2> ValueVTs;
7285   ValueVTs.push_back(MVT::Other); // chain
7286   SDVTList VTs = DAG.getVTList(ValueVTs);
7287
7288   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7289     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7290
7291   // Extract the value requested.
7292   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7293   SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7294   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7295
7296   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7297                                PtrInfo.getWithOffset(Offset),
7298                                false, false, false, 0);
7299
7300   if (!Subtarget.useCRBits())
7301     return IntVal;
7302
7303   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7304 }
7305
7306 /// Lowering for QPX v4i1 loads
7307 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7308                                            SelectionDAG &DAG) const {
7309   SDLoc dl(Op);
7310   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7311   SDValue LoadChain = LN->getChain();
7312   SDValue BasePtr = LN->getBasePtr();
7313
7314   if (Op.getValueType() == MVT::v4f64 ||
7315       Op.getValueType() == MVT::v4f32) {
7316     EVT MemVT = LN->getMemoryVT();
7317     unsigned Alignment = LN->getAlignment();
7318
7319     // If this load is properly aligned, then it is legal.
7320     if (Alignment >= MemVT.getStoreSize())
7321       return Op;
7322
7323     EVT ScalarVT = Op.getValueType().getScalarType(),
7324         ScalarMemVT = MemVT.getScalarType();
7325     unsigned Stride = ScalarMemVT.getStoreSize();
7326
7327     SmallVector<SDValue, 8> Vals, LoadChains;
7328     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7329       SDValue Load;
7330       if (ScalarVT != ScalarMemVT)
7331         Load =
7332           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7333                          BasePtr,
7334                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7335                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7336                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7337                          LN->getAAInfo());
7338       else
7339         Load =
7340           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7341                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7342                        LN->isVolatile(), LN->isNonTemporal(),
7343                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7344                        LN->getAAInfo());
7345
7346       if (Idx == 0 && LN->isIndexed()) {
7347         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7348                "Unknown addressing mode on vector load");
7349         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7350                                   LN->getAddressingMode());
7351       }
7352
7353       Vals.push_back(Load);
7354       LoadChains.push_back(Load.getValue(1));
7355
7356       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7357                             DAG.getConstant(Stride, BasePtr.getValueType()));
7358     }
7359
7360     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7361     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7362                                    Op.getValueType(), Vals);
7363
7364     if (LN->isIndexed()) {
7365       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7366       return DAG.getMergeValues(RetOps, dl);
7367     }
7368
7369     SDValue RetOps[] = { Value, TF };
7370     return DAG.getMergeValues(RetOps, dl);
7371   }
7372
7373   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7374   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7375
7376   // To lower v4i1 from a byte array, we load the byte elements of the
7377   // vector and then reuse the BUILD_VECTOR logic.
7378
7379   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7380   for (unsigned i = 0; i < 4; ++i) {
7381     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7382     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7383
7384     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7385                         dl, MVT::i32, LoadChain, Idx,
7386                         LN->getPointerInfo().getWithOffset(i),
7387                         MVT::i8 /* memory type */,
7388                         LN->isVolatile(), LN->isNonTemporal(),
7389                         LN->isInvariant(),
7390                         1 /* alignment */, LN->getAAInfo()));
7391     VectElmtChains.push_back(VectElmts[i].getValue(1));
7392   }
7393
7394   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7395   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7396
7397   SDValue RVals[] = { Value, LoadChain };
7398   return DAG.getMergeValues(RVals, dl);
7399 }
7400
7401 /// Lowering for QPX v4i1 stores
7402 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7403                                             SelectionDAG &DAG) const {
7404   SDLoc dl(Op);
7405   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7406   SDValue StoreChain = SN->getChain();
7407   SDValue BasePtr = SN->getBasePtr();
7408   SDValue Value = SN->getValue();
7409
7410   if (Value.getValueType() == MVT::v4f64 ||
7411       Value.getValueType() == MVT::v4f32) {
7412     EVT MemVT = SN->getMemoryVT();
7413     unsigned Alignment = SN->getAlignment();
7414
7415     // If this store is properly aligned, then it is legal.
7416     if (Alignment >= MemVT.getStoreSize())
7417       return Op;
7418
7419     EVT ScalarVT = Value.getValueType().getScalarType(),
7420         ScalarMemVT = MemVT.getScalarType();
7421     unsigned Stride = ScalarMemVT.getStoreSize();
7422
7423     SmallVector<SDValue, 8> Stores;
7424     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7425       SDValue Ex =
7426         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7427                     DAG.getConstant(Idx, getVectorIdxTy()));
7428       SDValue Store;
7429       if (ScalarVT != ScalarMemVT)
7430         Store =
7431           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7432                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7433                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7434                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7435       else
7436         Store =
7437           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7438                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7439                        SN->isVolatile(), SN->isNonTemporal(),
7440                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7441
7442       if (Idx == 0 && SN->isIndexed()) {
7443         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7444                "Unknown addressing mode on vector store");
7445         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7446                                     SN->getAddressingMode());
7447       }
7448
7449       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7450                             DAG.getConstant(Stride, BasePtr.getValueType()));
7451       Stores.push_back(Store);
7452     }
7453
7454     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7455
7456     if (SN->isIndexed()) {
7457       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7458       return DAG.getMergeValues(RetOps, dl);
7459     }
7460
7461     return TF;
7462   }
7463
7464   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7465   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7466
7467   // The values are now known to be -1 (false) or 1 (true). To convert this
7468   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7469   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7470   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7471
7472   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7473   // understand how to form the extending load.
7474   SDValue FPHalfs = DAG.getConstantFP(0.5, MVT::f64);
7475   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7476                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7477
7478   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7479
7480   // Now convert to an integer and store.
7481   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7482     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, MVT::i32),
7483     Value);
7484
7485   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7486   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7487   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7488   EVT PtrVT = getPointerTy();
7489   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7490
7491   SmallVector<SDValue, 2> Ops;
7492   Ops.push_back(StoreChain);
7493   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, MVT::i32));
7494   Ops.push_back(Value);
7495   Ops.push_back(FIdx);
7496
7497   SmallVector<EVT, 2> ValueVTs;
7498   ValueVTs.push_back(MVT::Other); // chain
7499   SDVTList VTs = DAG.getVTList(ValueVTs);
7500
7501   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7502     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7503
7504   // Move data into the byte array.
7505   SmallVector<SDValue, 4> Loads, LoadChains;
7506   for (unsigned i = 0; i < 4; ++i) {
7507     unsigned Offset = 4*i;
7508     SDValue Idx = DAG.getConstant(Offset, FIdx.getValueType());
7509     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7510
7511     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7512                                    PtrInfo.getWithOffset(Offset),
7513                                    false, false, false, 0));
7514     LoadChains.push_back(Loads[i].getValue(1));
7515   }
7516
7517   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7518
7519   SmallVector<SDValue, 4> Stores;
7520   for (unsigned i = 0; i < 4; ++i) {
7521     SDValue Idx = DAG.getConstant(i, BasePtr.getValueType());
7522     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7523
7524     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7525                                        SN->getPointerInfo().getWithOffset(i),
7526                                        MVT::i8 /* memory type */,
7527                                        SN->isNonTemporal(), SN->isVolatile(), 
7528                                        1 /* alignment */, SN->getAAInfo()));
7529   }
7530
7531   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7532
7533   return StoreChain;
7534 }
7535
7536 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7537   SDLoc dl(Op);
7538   if (Op.getValueType() == MVT::v4i32) {
7539     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7540
7541     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7542     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7543
7544     SDValue RHSSwap =   // = vrlw RHS, 16
7545       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7546
7547     // Shrinkify inputs to v8i16.
7548     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7549     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7550     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7551
7552     // Low parts multiplied together, generating 32-bit results (we ignore the
7553     // top parts).
7554     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7555                                         LHS, RHS, DAG, dl, MVT::v4i32);
7556
7557     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7558                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7559     // Shift the high parts up 16 bits.
7560     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7561                               Neg16, DAG, dl);
7562     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7563   } else if (Op.getValueType() == MVT::v8i16) {
7564     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7565
7566     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7567
7568     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7569                             LHS, RHS, Zero, DAG, dl);
7570   } else if (Op.getValueType() == MVT::v16i8) {
7571     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7572     bool isLittleEndian = Subtarget.isLittleEndian();
7573
7574     // Multiply the even 8-bit parts, producing 16-bit sums.
7575     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7576                                            LHS, RHS, DAG, dl, MVT::v8i16);
7577     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7578
7579     // Multiply the odd 8-bit parts, producing 16-bit sums.
7580     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7581                                           LHS, RHS, DAG, dl, MVT::v8i16);
7582     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7583
7584     // Merge the results together.  Because vmuleub and vmuloub are
7585     // instructions with a big-endian bias, we must reverse the
7586     // element numbering and reverse the meaning of "odd" and "even"
7587     // when generating little endian code.
7588     int Ops[16];
7589     for (unsigned i = 0; i != 8; ++i) {
7590       if (isLittleEndian) {
7591         Ops[i*2  ] = 2*i;
7592         Ops[i*2+1] = 2*i+16;
7593       } else {
7594         Ops[i*2  ] = 2*i+1;
7595         Ops[i*2+1] = 2*i+1+16;
7596       }
7597     }
7598     if (isLittleEndian)
7599       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7600     else
7601       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7602   } else {
7603     llvm_unreachable("Unknown mul to lower!");
7604   }
7605 }
7606
7607 /// LowerOperation - Provide custom lowering hooks for some operations.
7608 ///
7609 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7610   switch (Op.getOpcode()) {
7611   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7612   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7613   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7614   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7615   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7616   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7617   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7618   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7619   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7620   case ISD::VASTART:
7621     return LowerVASTART(Op, DAG, Subtarget);
7622
7623   case ISD::VAARG:
7624     return LowerVAARG(Op, DAG, Subtarget);
7625
7626   case ISD::VACOPY:
7627     return LowerVACOPY(Op, DAG, Subtarget);
7628
7629   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7630   case ISD::DYNAMIC_STACKALLOC:
7631     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7632
7633   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7634   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7635
7636   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7637   case ISD::STORE:              return LowerSTORE(Op, DAG);
7638   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7639   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7640   case ISD::FP_TO_UINT:
7641   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7642                                                       SDLoc(Op));
7643   case ISD::UINT_TO_FP:
7644   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7645   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7646
7647   // Lower 64-bit shifts.
7648   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7649   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7650   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7651
7652   // Vector-related lowering.
7653   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7654   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7655   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7656   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7657   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7658   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7659   case ISD::MUL:                return LowerMUL(Op, DAG);
7660
7661   // For counter-based loop handling.
7662   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7663
7664   // Frame & Return address.
7665   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7666   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7667   }
7668 }
7669
7670 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7671                                            SmallVectorImpl<SDValue>&Results,
7672                                            SelectionDAG &DAG) const {
7673   SDLoc dl(N);
7674   switch (N->getOpcode()) {
7675   default:
7676     llvm_unreachable("Do not know how to custom type legalize this operation!");
7677   case ISD::READCYCLECOUNTER: {
7678     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7679     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7680
7681     Results.push_back(RTB);
7682     Results.push_back(RTB.getValue(1));
7683     Results.push_back(RTB.getValue(2));
7684     break;
7685   }
7686   case ISD::INTRINSIC_W_CHAIN: {
7687     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7688         Intrinsic::ppc_is_decremented_ctr_nonzero)
7689       break;
7690
7691     assert(N->getValueType(0) == MVT::i1 &&
7692            "Unexpected result type for CTR decrement intrinsic");
7693     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7694     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7695     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7696                                  N->getOperand(1)); 
7697
7698     Results.push_back(NewInt);
7699     Results.push_back(NewInt.getValue(1));
7700     break;
7701   }
7702   case ISD::VAARG: {
7703     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7704       return;
7705
7706     EVT VT = N->getValueType(0);
7707
7708     if (VT == MVT::i64) {
7709       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7710
7711       Results.push_back(NewNode);
7712       Results.push_back(NewNode.getValue(1));
7713     }
7714     return;
7715   }
7716   case ISD::FP_ROUND_INREG: {
7717     assert(N->getValueType(0) == MVT::ppcf128);
7718     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7719     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7720                              MVT::f64, N->getOperand(0),
7721                              DAG.getIntPtrConstant(0));
7722     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7723                              MVT::f64, N->getOperand(0),
7724                              DAG.getIntPtrConstant(1));
7725
7726     // Add the two halves of the long double in round-to-zero mode.
7727     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7728
7729     // We know the low half is about to be thrown away, so just use something
7730     // convenient.
7731     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7732                                 FPreg, FPreg));
7733     return;
7734   }
7735   case ISD::FP_TO_SINT:
7736     // LowerFP_TO_INT() can only handle f32 and f64.
7737     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7738       return;
7739     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7740     return;
7741   }
7742 }
7743
7744
7745 //===----------------------------------------------------------------------===//
7746 //  Other Lowering Code
7747 //===----------------------------------------------------------------------===//
7748
7749 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7750   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7751   Function *Func = Intrinsic::getDeclaration(M, Id);
7752   return Builder.CreateCall(Func);
7753 }
7754
7755 // The mappings for emitLeading/TrailingFence is taken from
7756 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7757 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7758                                          AtomicOrdering Ord, bool IsStore,
7759                                          bool IsLoad) const {
7760   if (Ord == SequentiallyConsistent)
7761     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7762   else if (isAtLeastRelease(Ord))
7763     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7764   else
7765     return nullptr;
7766 }
7767
7768 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7769                                           AtomicOrdering Ord, bool IsStore,
7770                                           bool IsLoad) const {
7771   if (IsLoad && isAtLeastAcquire(Ord))
7772     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7773   // FIXME: this is too conservative, a dependent branch + isync is enough.
7774   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7775   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7776   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7777   else
7778     return nullptr;
7779 }
7780
7781 MachineBasicBlock *
7782 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7783                                     unsigned AtomicSize,
7784                                     unsigned BinOpcode) const {
7785   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7786   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7787
7788   auto LoadMnemonic = PPC::LDARX;
7789   auto StoreMnemonic = PPC::STDCX;
7790   switch (AtomicSize) {
7791   default:
7792     llvm_unreachable("Unexpected size of atomic entity");
7793   case 1:
7794     LoadMnemonic = PPC::LBARX;
7795     StoreMnemonic = PPC::STBCX;
7796     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7797     break;
7798   case 2:
7799     LoadMnemonic = PPC::LHARX;
7800     StoreMnemonic = PPC::STHCX;
7801     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7802     break;
7803   case 4:
7804     LoadMnemonic = PPC::LWARX;
7805     StoreMnemonic = PPC::STWCX;
7806     break;
7807   case 8:
7808     LoadMnemonic = PPC::LDARX;
7809     StoreMnemonic = PPC::STDCX;
7810     break;
7811   }
7812
7813   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7814   MachineFunction *F = BB->getParent();
7815   MachineFunction::iterator It = BB;
7816   ++It;
7817
7818   unsigned dest = MI->getOperand(0).getReg();
7819   unsigned ptrA = MI->getOperand(1).getReg();
7820   unsigned ptrB = MI->getOperand(2).getReg();
7821   unsigned incr = MI->getOperand(3).getReg();
7822   DebugLoc dl = MI->getDebugLoc();
7823
7824   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7825   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7826   F->insert(It, loopMBB);
7827   F->insert(It, exitMBB);
7828   exitMBB->splice(exitMBB->begin(), BB,
7829                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7830   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7831
7832   MachineRegisterInfo &RegInfo = F->getRegInfo();
7833   unsigned TmpReg = (!BinOpcode) ? incr :
7834     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7835                                            : &PPC::GPRCRegClass);
7836
7837   //  thisMBB:
7838   //   ...
7839   //   fallthrough --> loopMBB
7840   BB->addSuccessor(loopMBB);
7841
7842   //  loopMBB:
7843   //   l[wd]arx dest, ptr
7844   //   add r0, dest, incr
7845   //   st[wd]cx. r0, ptr
7846   //   bne- loopMBB
7847   //   fallthrough --> exitMBB
7848   BB = loopMBB;
7849   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7850     .addReg(ptrA).addReg(ptrB);
7851   if (BinOpcode)
7852     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7853   BuildMI(BB, dl, TII->get(StoreMnemonic))
7854     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7855   BuildMI(BB, dl, TII->get(PPC::BCC))
7856     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7857   BB->addSuccessor(loopMBB);
7858   BB->addSuccessor(exitMBB);
7859
7860   //  exitMBB:
7861   //   ...
7862   BB = exitMBB;
7863   return BB;
7864 }
7865
7866 MachineBasicBlock *
7867 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
7868                                             MachineBasicBlock *BB,
7869                                             bool is8bit,    // operation
7870                                             unsigned BinOpcode) const {
7871   // If we support part-word atomic mnemonics, just use them
7872   if (Subtarget.hasPartwordAtomics())
7873     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
7874
7875   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7876   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7877   // In 64 bit mode we have to use 64 bits for addresses, even though the
7878   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
7879   // registers without caring whether they're 32 or 64, but here we're
7880   // doing actual arithmetic on the addresses.
7881   bool is64bit = Subtarget.isPPC64();
7882   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7883
7884   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7885   MachineFunction *F = BB->getParent();
7886   MachineFunction::iterator It = BB;
7887   ++It;
7888
7889   unsigned dest = MI->getOperand(0).getReg();
7890   unsigned ptrA = MI->getOperand(1).getReg();
7891   unsigned ptrB = MI->getOperand(2).getReg();
7892   unsigned incr = MI->getOperand(3).getReg();
7893   DebugLoc dl = MI->getDebugLoc();
7894
7895   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7896   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7897   F->insert(It, loopMBB);
7898   F->insert(It, exitMBB);
7899   exitMBB->splice(exitMBB->begin(), BB,
7900                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7901   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7902
7903   MachineRegisterInfo &RegInfo = F->getRegInfo();
7904   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7905                                           : &PPC::GPRCRegClass;
7906   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7907   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7908   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7909   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
7910   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7911   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7912   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7913   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7914   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
7915   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7916   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7917   unsigned Ptr1Reg;
7918   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
7919
7920   //  thisMBB:
7921   //   ...
7922   //   fallthrough --> loopMBB
7923   BB->addSuccessor(loopMBB);
7924
7925   // The 4-byte load must be aligned, while a char or short may be
7926   // anywhere in the word.  Hence all this nasty bookkeeping code.
7927   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7928   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7929   //   xori shift, shift1, 24 [16]
7930   //   rlwinm ptr, ptr1, 0, 0, 29
7931   //   slw incr2, incr, shift
7932   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7933   //   slw mask, mask2, shift
7934   //  loopMBB:
7935   //   lwarx tmpDest, ptr
7936   //   add tmp, tmpDest, incr2
7937   //   andc tmp2, tmpDest, mask
7938   //   and tmp3, tmp, mask
7939   //   or tmp4, tmp3, tmp2
7940   //   stwcx. tmp4, ptr
7941   //   bne- loopMBB
7942   //   fallthrough --> exitMBB
7943   //   srw dest, tmpDest, shift
7944   if (ptrA != ZeroReg) {
7945     Ptr1Reg = RegInfo.createVirtualRegister(RC);
7946     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7947       .addReg(ptrA).addReg(ptrB);
7948   } else {
7949     Ptr1Reg = ptrB;
7950   }
7951   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7952       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7953   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7954       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7955   if (is64bit)
7956     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7957       .addReg(Ptr1Reg).addImm(0).addImm(61);
7958   else
7959     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7960       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7961   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
7962       .addReg(incr).addReg(ShiftReg);
7963   if (is8bit)
7964     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7965   else {
7966     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7967     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
7968   }
7969   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7970       .addReg(Mask2Reg).addReg(ShiftReg);
7971
7972   BB = loopMBB;
7973   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7974     .addReg(ZeroReg).addReg(PtrReg);
7975   if (BinOpcode)
7976     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
7977       .addReg(Incr2Reg).addReg(TmpDestReg);
7978   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
7979     .addReg(TmpDestReg).addReg(MaskReg);
7980   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
7981     .addReg(TmpReg).addReg(MaskReg);
7982   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
7983     .addReg(Tmp3Reg).addReg(Tmp2Reg);
7984   BuildMI(BB, dl, TII->get(PPC::STWCX))
7985     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
7986   BuildMI(BB, dl, TII->get(PPC::BCC))
7987     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7988   BB->addSuccessor(loopMBB);
7989   BB->addSuccessor(exitMBB);
7990
7991   //  exitMBB:
7992   //   ...
7993   BB = exitMBB;
7994   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
7995     .addReg(ShiftReg);
7996   return BB;
7997 }
7998
7999 llvm::MachineBasicBlock*
8000 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8001                                     MachineBasicBlock *MBB) const {
8002   DebugLoc DL = MI->getDebugLoc();
8003   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8004
8005   MachineFunction *MF = MBB->getParent();
8006   MachineRegisterInfo &MRI = MF->getRegInfo();
8007
8008   const BasicBlock *BB = MBB->getBasicBlock();
8009   MachineFunction::iterator I = MBB;
8010   ++I;
8011
8012   // Memory Reference
8013   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8014   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8015
8016   unsigned DstReg = MI->getOperand(0).getReg();
8017   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8018   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8019   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8020   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8021
8022   MVT PVT = getPointerTy();
8023   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8024          "Invalid Pointer Size!");
8025   // For v = setjmp(buf), we generate
8026   //
8027   // thisMBB:
8028   //  SjLjSetup mainMBB
8029   //  bl mainMBB
8030   //  v_restore = 1
8031   //  b sinkMBB
8032   //
8033   // mainMBB:
8034   //  buf[LabelOffset] = LR
8035   //  v_main = 0
8036   //
8037   // sinkMBB:
8038   //  v = phi(main, restore)
8039   //
8040
8041   MachineBasicBlock *thisMBB = MBB;
8042   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8043   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8044   MF->insert(I, mainMBB);
8045   MF->insert(I, sinkMBB);
8046
8047   MachineInstrBuilder MIB;
8048
8049   // Transfer the remainder of BB and its successor edges to sinkMBB.
8050   sinkMBB->splice(sinkMBB->begin(), MBB,
8051                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8052   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8053
8054   // Note that the structure of the jmp_buf used here is not compatible
8055   // with that used by libc, and is not designed to be. Specifically, it
8056   // stores only those 'reserved' registers that LLVM does not otherwise
8057   // understand how to spill. Also, by convention, by the time this
8058   // intrinsic is called, Clang has already stored the frame address in the
8059   // first slot of the buffer and stack address in the third. Following the
8060   // X86 target code, we'll store the jump address in the second slot. We also
8061   // need to save the TOC pointer (R2) to handle jumps between shared
8062   // libraries, and that will be stored in the fourth slot. The thread
8063   // identifier (R13) is not affected.
8064
8065   // thisMBB:
8066   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8067   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8068   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8069
8070   // Prepare IP either in reg.
8071   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8072   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8073   unsigned BufReg = MI->getOperand(1).getReg();
8074
8075   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8076     setUsesTOCBasePtr(*MBB->getParent());
8077     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8078             .addReg(PPC::X2)
8079             .addImm(TOCOffset)
8080             .addReg(BufReg);
8081     MIB.setMemRefs(MMOBegin, MMOEnd);
8082   }
8083
8084   // Naked functions never have a base pointer, and so we use r1. For all
8085   // other functions, this decision must be delayed until during PEI.
8086   unsigned BaseReg;
8087   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8088     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8089   else
8090     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8091
8092   MIB = BuildMI(*thisMBB, MI, DL,
8093                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8094             .addReg(BaseReg)
8095             .addImm(BPOffset)
8096             .addReg(BufReg);
8097   MIB.setMemRefs(MMOBegin, MMOEnd);
8098
8099   // Setup
8100   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8101   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8102   MIB.addRegMask(TRI->getNoPreservedMask());
8103
8104   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8105
8106   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8107           .addMBB(mainMBB);
8108   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8109
8110   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8111   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8112
8113   // mainMBB:
8114   //  mainDstReg = 0
8115   MIB =
8116       BuildMI(mainMBB, DL,
8117               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8118
8119   // Store IP
8120   if (Subtarget.isPPC64()) {
8121     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8122             .addReg(LabelReg)
8123             .addImm(LabelOffset)
8124             .addReg(BufReg);
8125   } else {
8126     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8127             .addReg(LabelReg)
8128             .addImm(LabelOffset)
8129             .addReg(BufReg);
8130   }
8131
8132   MIB.setMemRefs(MMOBegin, MMOEnd);
8133
8134   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8135   mainMBB->addSuccessor(sinkMBB);
8136
8137   // sinkMBB:
8138   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8139           TII->get(PPC::PHI), DstReg)
8140     .addReg(mainDstReg).addMBB(mainMBB)
8141     .addReg(restoreDstReg).addMBB(thisMBB);
8142
8143   MI->eraseFromParent();
8144   return sinkMBB;
8145 }
8146
8147 MachineBasicBlock *
8148 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8149                                      MachineBasicBlock *MBB) const {
8150   DebugLoc DL = MI->getDebugLoc();
8151   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8152
8153   MachineFunction *MF = MBB->getParent();
8154   MachineRegisterInfo &MRI = MF->getRegInfo();
8155
8156   // Memory Reference
8157   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8158   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8159
8160   MVT PVT = getPointerTy();
8161   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8162          "Invalid Pointer Size!");
8163
8164   const TargetRegisterClass *RC =
8165     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8166   unsigned Tmp = MRI.createVirtualRegister(RC);
8167   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8168   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8169   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8170   unsigned BP =
8171       (PVT == MVT::i64)
8172           ? PPC::X30
8173           : (Subtarget.isSVR4ABI() &&
8174                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8175                  ? PPC::R29
8176                  : PPC::R30);
8177
8178   MachineInstrBuilder MIB;
8179
8180   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8181   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8182   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8183   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8184
8185   unsigned BufReg = MI->getOperand(0).getReg();
8186
8187   // Reload FP (the jumped-to function may not have had a
8188   // frame pointer, and if so, then its r31 will be restored
8189   // as necessary).
8190   if (PVT == MVT::i64) {
8191     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8192             .addImm(0)
8193             .addReg(BufReg);
8194   } else {
8195     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8196             .addImm(0)
8197             .addReg(BufReg);
8198   }
8199   MIB.setMemRefs(MMOBegin, MMOEnd);
8200
8201   // Reload IP
8202   if (PVT == MVT::i64) {
8203     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8204             .addImm(LabelOffset)
8205             .addReg(BufReg);
8206   } else {
8207     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8208             .addImm(LabelOffset)
8209             .addReg(BufReg);
8210   }
8211   MIB.setMemRefs(MMOBegin, MMOEnd);
8212
8213   // Reload SP
8214   if (PVT == MVT::i64) {
8215     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8216             .addImm(SPOffset)
8217             .addReg(BufReg);
8218   } else {
8219     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8220             .addImm(SPOffset)
8221             .addReg(BufReg);
8222   }
8223   MIB.setMemRefs(MMOBegin, MMOEnd);
8224
8225   // Reload BP
8226   if (PVT == MVT::i64) {
8227     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8228             .addImm(BPOffset)
8229             .addReg(BufReg);
8230   } else {
8231     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8232             .addImm(BPOffset)
8233             .addReg(BufReg);
8234   }
8235   MIB.setMemRefs(MMOBegin, MMOEnd);
8236
8237   // Reload TOC
8238   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8239     setUsesTOCBasePtr(*MBB->getParent());
8240     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8241             .addImm(TOCOffset)
8242             .addReg(BufReg);
8243
8244     MIB.setMemRefs(MMOBegin, MMOEnd);
8245   }
8246
8247   // Jump
8248   BuildMI(*MBB, MI, DL,
8249           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8250   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8251
8252   MI->eraseFromParent();
8253   return MBB;
8254 }
8255
8256 MachineBasicBlock *
8257 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8258                                                MachineBasicBlock *BB) const {
8259   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8260       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8261     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8262         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8263       // Call lowering should have added an r2 operand to indicate a dependence
8264       // on the TOC base pointer value. It can't however, because there is no
8265       // way to mark the dependence as implicit there, and so the stackmap code
8266       // will confuse it with a regular operand. Instead, add the dependence
8267       // here.
8268       setUsesTOCBasePtr(*BB->getParent());
8269       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8270     }
8271
8272     return emitPatchPoint(MI, BB);
8273   }
8274
8275   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8276       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8277     return emitEHSjLjSetJmp(MI, BB);
8278   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8279              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8280     return emitEHSjLjLongJmp(MI, BB);
8281   }
8282
8283   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8284
8285   // To "insert" these instructions we actually have to insert their
8286   // control-flow patterns.
8287   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8288   MachineFunction::iterator It = BB;
8289   ++It;
8290
8291   MachineFunction *F = BB->getParent();
8292
8293   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8294                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8295                               MI->getOpcode() == PPC::SELECT_I4 ||
8296                               MI->getOpcode() == PPC::SELECT_I8)) {
8297     SmallVector<MachineOperand, 2> Cond;
8298     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8299         MI->getOpcode() == PPC::SELECT_CC_I8)
8300       Cond.push_back(MI->getOperand(4));
8301     else
8302       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8303     Cond.push_back(MI->getOperand(1));
8304
8305     DebugLoc dl = MI->getDebugLoc();
8306     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8307                       Cond, MI->getOperand(2).getReg(),
8308                       MI->getOperand(3).getReg());
8309   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8310              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8311              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8312              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8313              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8314              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8315              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8316              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8317              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8318              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8319              MI->getOpcode() == PPC::SELECT_I4 ||
8320              MI->getOpcode() == PPC::SELECT_I8 ||
8321              MI->getOpcode() == PPC::SELECT_F4 ||
8322              MI->getOpcode() == PPC::SELECT_F8 ||
8323              MI->getOpcode() == PPC::SELECT_QFRC ||
8324              MI->getOpcode() == PPC::SELECT_QSRC ||
8325              MI->getOpcode() == PPC::SELECT_QBRC ||
8326              MI->getOpcode() == PPC::SELECT_VRRC ||
8327              MI->getOpcode() == PPC::SELECT_VSFRC ||
8328              MI->getOpcode() == PPC::SELECT_VSRC) {
8329     // The incoming instruction knows the destination vreg to set, the
8330     // condition code register to branch on, the true/false values to
8331     // select between, and a branch opcode to use.
8332
8333     //  thisMBB:
8334     //  ...
8335     //   TrueVal = ...
8336     //   cmpTY ccX, r1, r2
8337     //   bCC copy1MBB
8338     //   fallthrough --> copy0MBB
8339     MachineBasicBlock *thisMBB = BB;
8340     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8341     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8342     DebugLoc dl = MI->getDebugLoc();
8343     F->insert(It, copy0MBB);
8344     F->insert(It, sinkMBB);
8345
8346     // Transfer the remainder of BB and its successor edges to sinkMBB.
8347     sinkMBB->splice(sinkMBB->begin(), BB,
8348                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8349     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8350
8351     // Next, add the true and fallthrough blocks as its successors.
8352     BB->addSuccessor(copy0MBB);
8353     BB->addSuccessor(sinkMBB);
8354
8355     if (MI->getOpcode() == PPC::SELECT_I4 ||
8356         MI->getOpcode() == PPC::SELECT_I8 ||
8357         MI->getOpcode() == PPC::SELECT_F4 ||
8358         MI->getOpcode() == PPC::SELECT_F8 ||
8359         MI->getOpcode() == PPC::SELECT_QFRC ||
8360         MI->getOpcode() == PPC::SELECT_QSRC ||
8361         MI->getOpcode() == PPC::SELECT_QBRC ||
8362         MI->getOpcode() == PPC::SELECT_VRRC ||
8363         MI->getOpcode() == PPC::SELECT_VSFRC ||
8364         MI->getOpcode() == PPC::SELECT_VSRC) {
8365       BuildMI(BB, dl, TII->get(PPC::BC))
8366         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8367     } else {
8368       unsigned SelectPred = MI->getOperand(4).getImm();
8369       BuildMI(BB, dl, TII->get(PPC::BCC))
8370         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8371     }
8372
8373     //  copy0MBB:
8374     //   %FalseValue = ...
8375     //   # fallthrough to sinkMBB
8376     BB = copy0MBB;
8377
8378     // Update machine-CFG edges
8379     BB->addSuccessor(sinkMBB);
8380
8381     //  sinkMBB:
8382     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8383     //  ...
8384     BB = sinkMBB;
8385     BuildMI(*BB, BB->begin(), dl,
8386             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8387       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8388       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8389   } else if (MI->getOpcode() == PPC::ReadTB) {
8390     // To read the 64-bit time-base register on a 32-bit target, we read the
8391     // two halves. Should the counter have wrapped while it was being read, we
8392     // need to try again.
8393     // ...
8394     // readLoop:
8395     // mfspr Rx,TBU # load from TBU
8396     // mfspr Ry,TB  # load from TB
8397     // mfspr Rz,TBU # load from TBU
8398     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8399     // bne readLoop   # branch if they're not equal
8400     // ...
8401
8402     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8403     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8404     DebugLoc dl = MI->getDebugLoc();
8405     F->insert(It, readMBB);
8406     F->insert(It, sinkMBB);
8407
8408     // Transfer the remainder of BB and its successor edges to sinkMBB.
8409     sinkMBB->splice(sinkMBB->begin(), BB,
8410                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8411     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8412
8413     BB->addSuccessor(readMBB);
8414     BB = readMBB;
8415
8416     MachineRegisterInfo &RegInfo = F->getRegInfo();
8417     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8418     unsigned LoReg = MI->getOperand(0).getReg();
8419     unsigned HiReg = MI->getOperand(1).getReg();
8420
8421     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8422     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8423     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8424
8425     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8426
8427     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8428       .addReg(HiReg).addReg(ReadAgainReg);
8429     BuildMI(BB, dl, TII->get(PPC::BCC))
8430       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8431
8432     BB->addSuccessor(readMBB);
8433     BB->addSuccessor(sinkMBB);
8434   }
8435   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8436     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8437   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8438     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8439   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8440     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8441   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8442     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8443
8444   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8445     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8446   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8447     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8448   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8449     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8450   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8451     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8452
8453   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8454     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8455   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8456     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8457   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8458     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8459   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8460     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8461
8462   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8463     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8464   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8465     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8466   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8467     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8468   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8469     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8470
8471   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8472     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8473   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8474     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8475   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8476     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8477   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8478     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8479
8480   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8481     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8482   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8483     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8484   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8485     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8486   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8487     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8488
8489   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8490     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8491   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8492     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8493   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8494     BB = EmitAtomicBinary(MI, BB, 4, 0);
8495   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8496     BB = EmitAtomicBinary(MI, BB, 8, 0);
8497
8498   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8499            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8500            (Subtarget.hasPartwordAtomics() &&
8501             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8502            (Subtarget.hasPartwordAtomics() &&
8503             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8504     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8505
8506     auto LoadMnemonic = PPC::LDARX;
8507     auto StoreMnemonic = PPC::STDCX;
8508     switch(MI->getOpcode()) {
8509     default:
8510       llvm_unreachable("Compare and swap of unknown size");
8511     case PPC::ATOMIC_CMP_SWAP_I8:
8512       LoadMnemonic = PPC::LBARX;
8513       StoreMnemonic = PPC::STBCX;
8514       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8515       break;
8516     case PPC::ATOMIC_CMP_SWAP_I16:
8517       LoadMnemonic = PPC::LHARX;
8518       StoreMnemonic = PPC::STHCX;
8519       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8520       break;
8521     case PPC::ATOMIC_CMP_SWAP_I32:
8522       LoadMnemonic = PPC::LWARX;
8523       StoreMnemonic = PPC::STWCX;
8524       break;
8525     case PPC::ATOMIC_CMP_SWAP_I64:
8526       LoadMnemonic = PPC::LDARX;
8527       StoreMnemonic = PPC::STDCX;
8528       break;
8529     }
8530     unsigned dest   = MI->getOperand(0).getReg();
8531     unsigned ptrA   = MI->getOperand(1).getReg();
8532     unsigned ptrB   = MI->getOperand(2).getReg();
8533     unsigned oldval = MI->getOperand(3).getReg();
8534     unsigned newval = MI->getOperand(4).getReg();
8535     DebugLoc dl     = MI->getDebugLoc();
8536
8537     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8538     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8539     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8540     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8541     F->insert(It, loop1MBB);
8542     F->insert(It, loop2MBB);
8543     F->insert(It, midMBB);
8544     F->insert(It, exitMBB);
8545     exitMBB->splice(exitMBB->begin(), BB,
8546                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8547     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8548
8549     //  thisMBB:
8550     //   ...
8551     //   fallthrough --> loopMBB
8552     BB->addSuccessor(loop1MBB);
8553
8554     // loop1MBB:
8555     //   l[bhwd]arx dest, ptr
8556     //   cmp[wd] dest, oldval
8557     //   bne- midMBB
8558     // loop2MBB:
8559     //   st[bhwd]cx. newval, ptr
8560     //   bne- loopMBB
8561     //   b exitBB
8562     // midMBB:
8563     //   st[bhwd]cx. dest, ptr
8564     // exitBB:
8565     BB = loop1MBB;
8566     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8567       .addReg(ptrA).addReg(ptrB);
8568     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8569       .addReg(oldval).addReg(dest);
8570     BuildMI(BB, dl, TII->get(PPC::BCC))
8571       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8572     BB->addSuccessor(loop2MBB);
8573     BB->addSuccessor(midMBB);
8574
8575     BB = loop2MBB;
8576     BuildMI(BB, dl, TII->get(StoreMnemonic))
8577       .addReg(newval).addReg(ptrA).addReg(ptrB);
8578     BuildMI(BB, dl, TII->get(PPC::BCC))
8579       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8580     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8581     BB->addSuccessor(loop1MBB);
8582     BB->addSuccessor(exitMBB);
8583
8584     BB = midMBB;
8585     BuildMI(BB, dl, TII->get(StoreMnemonic))
8586       .addReg(dest).addReg(ptrA).addReg(ptrB);
8587     BB->addSuccessor(exitMBB);
8588
8589     //  exitMBB:
8590     //   ...
8591     BB = exitMBB;
8592   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8593              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8594     // We must use 64-bit registers for addresses when targeting 64-bit,
8595     // since we're actually doing arithmetic on them.  Other registers
8596     // can be 32-bit.
8597     bool is64bit = Subtarget.isPPC64();
8598     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8599
8600     unsigned dest   = MI->getOperand(0).getReg();
8601     unsigned ptrA   = MI->getOperand(1).getReg();
8602     unsigned ptrB   = MI->getOperand(2).getReg();
8603     unsigned oldval = MI->getOperand(3).getReg();
8604     unsigned newval = MI->getOperand(4).getReg();
8605     DebugLoc dl     = MI->getDebugLoc();
8606
8607     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8608     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8609     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8610     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8611     F->insert(It, loop1MBB);
8612     F->insert(It, loop2MBB);
8613     F->insert(It, midMBB);
8614     F->insert(It, exitMBB);
8615     exitMBB->splice(exitMBB->begin(), BB,
8616                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8617     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8618
8619     MachineRegisterInfo &RegInfo = F->getRegInfo();
8620     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8621                                             : &PPC::GPRCRegClass;
8622     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8623     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8624     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8625     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8626     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8627     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8628     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8629     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8630     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8631     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8632     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8633     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8634     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8635     unsigned Ptr1Reg;
8636     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8637     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8638     //  thisMBB:
8639     //   ...
8640     //   fallthrough --> loopMBB
8641     BB->addSuccessor(loop1MBB);
8642
8643     // The 4-byte load must be aligned, while a char or short may be
8644     // anywhere in the word.  Hence all this nasty bookkeeping code.
8645     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8646     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8647     //   xori shift, shift1, 24 [16]
8648     //   rlwinm ptr, ptr1, 0, 0, 29
8649     //   slw newval2, newval, shift
8650     //   slw oldval2, oldval,shift
8651     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8652     //   slw mask, mask2, shift
8653     //   and newval3, newval2, mask
8654     //   and oldval3, oldval2, mask
8655     // loop1MBB:
8656     //   lwarx tmpDest, ptr
8657     //   and tmp, tmpDest, mask
8658     //   cmpw tmp, oldval3
8659     //   bne- midMBB
8660     // loop2MBB:
8661     //   andc tmp2, tmpDest, mask
8662     //   or tmp4, tmp2, newval3
8663     //   stwcx. tmp4, ptr
8664     //   bne- loop1MBB
8665     //   b exitBB
8666     // midMBB:
8667     //   stwcx. tmpDest, ptr
8668     // exitBB:
8669     //   srw dest, tmpDest, shift
8670     if (ptrA != ZeroReg) {
8671       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8672       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8673         .addReg(ptrA).addReg(ptrB);
8674     } else {
8675       Ptr1Reg = ptrB;
8676     }
8677     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8678         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8679     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8680         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8681     if (is64bit)
8682       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8683         .addReg(Ptr1Reg).addImm(0).addImm(61);
8684     else
8685       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8686         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8687     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8688         .addReg(newval).addReg(ShiftReg);
8689     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8690         .addReg(oldval).addReg(ShiftReg);
8691     if (is8bit)
8692       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8693     else {
8694       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8695       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8696         .addReg(Mask3Reg).addImm(65535);
8697     }
8698     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8699         .addReg(Mask2Reg).addReg(ShiftReg);
8700     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8701         .addReg(NewVal2Reg).addReg(MaskReg);
8702     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8703         .addReg(OldVal2Reg).addReg(MaskReg);
8704
8705     BB = loop1MBB;
8706     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8707         .addReg(ZeroReg).addReg(PtrReg);
8708     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8709         .addReg(TmpDestReg).addReg(MaskReg);
8710     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8711         .addReg(TmpReg).addReg(OldVal3Reg);
8712     BuildMI(BB, dl, TII->get(PPC::BCC))
8713         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8714     BB->addSuccessor(loop2MBB);
8715     BB->addSuccessor(midMBB);
8716
8717     BB = loop2MBB;
8718     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8719         .addReg(TmpDestReg).addReg(MaskReg);
8720     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8721         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8722     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8723         .addReg(ZeroReg).addReg(PtrReg);
8724     BuildMI(BB, dl, TII->get(PPC::BCC))
8725       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8726     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8727     BB->addSuccessor(loop1MBB);
8728     BB->addSuccessor(exitMBB);
8729
8730     BB = midMBB;
8731     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8732       .addReg(ZeroReg).addReg(PtrReg);
8733     BB->addSuccessor(exitMBB);
8734
8735     //  exitMBB:
8736     //   ...
8737     BB = exitMBB;
8738     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8739       .addReg(ShiftReg);
8740   } else if (MI->getOpcode() == PPC::FADDrtz) {
8741     // This pseudo performs an FADD with rounding mode temporarily forced
8742     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8743     // is not modeled at the SelectionDAG level.
8744     unsigned Dest = MI->getOperand(0).getReg();
8745     unsigned Src1 = MI->getOperand(1).getReg();
8746     unsigned Src2 = MI->getOperand(2).getReg();
8747     DebugLoc dl   = MI->getDebugLoc();
8748
8749     MachineRegisterInfo &RegInfo = F->getRegInfo();
8750     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8751
8752     // Save FPSCR value.
8753     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8754
8755     // Set rounding mode to round-to-zero.
8756     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8757     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8758
8759     // Perform addition.
8760     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8761
8762     // Restore FPSCR value.
8763     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8764   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8765              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8766              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8767              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8768     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8769                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8770                       PPC::ANDIo8 : PPC::ANDIo;
8771     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8772                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8773
8774     MachineRegisterInfo &RegInfo = F->getRegInfo();
8775     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8776                                                   &PPC::GPRCRegClass :
8777                                                   &PPC::G8RCRegClass);
8778
8779     DebugLoc dl   = MI->getDebugLoc();
8780     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8781       .addReg(MI->getOperand(1).getReg()).addImm(1);
8782     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8783             MI->getOperand(0).getReg())
8784       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8785   } else {
8786     llvm_unreachable("Unexpected instr type to insert");
8787   }
8788
8789   MI->eraseFromParent();   // The pseudo instruction is gone now.
8790   return BB;
8791 }
8792
8793 //===----------------------------------------------------------------------===//
8794 // Target Optimization Hooks
8795 //===----------------------------------------------------------------------===//
8796
8797 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8798                                             DAGCombinerInfo &DCI,
8799                                             unsigned &RefinementSteps,
8800                                             bool &UseOneConstNR) const {
8801   EVT VT = Operand.getValueType();
8802   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8803       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8804       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8805       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8806       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8807       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8808     // Convergence is quadratic, so we essentially double the number of digits
8809     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8810     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8811     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8812     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8813     if (VT.getScalarType() == MVT::f64)
8814       ++RefinementSteps;
8815     UseOneConstNR = true;
8816     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8817   }
8818   return SDValue();
8819 }
8820
8821 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8822                                             DAGCombinerInfo &DCI,
8823                                             unsigned &RefinementSteps) const {
8824   EVT VT = Operand.getValueType();
8825   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8826       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8827       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8828       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8829       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8830       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8831     // Convergence is quadratic, so we essentially double the number of digits
8832     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8833     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8834     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8835     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8836     if (VT.getScalarType() == MVT::f64)
8837       ++RefinementSteps;
8838     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8839   }
8840   return SDValue();
8841 }
8842
8843 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8844   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8845   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8846   // enabled for division), this functionality is redundant with the default
8847   // combiner logic (once the division -> reciprocal/multiply transformation
8848   // has taken place). As a result, this matters more for older cores than for
8849   // newer ones.
8850
8851   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8852   // reciprocal if there are two or more FDIVs (for embedded cores with only
8853   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8854   switch (Subtarget.getDarwinDirective()) {
8855   default:
8856     return NumUsers > 2;
8857   case PPC::DIR_440:
8858   case PPC::DIR_A2:
8859   case PPC::DIR_E500mc:
8860   case PPC::DIR_E5500:
8861     return NumUsers > 1;
8862   }
8863 }
8864
8865 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
8866                             unsigned Bytes, int Dist,
8867                             SelectionDAG &DAG) {
8868   if (VT.getSizeInBits() / 8 != Bytes)
8869     return false;
8870
8871   SDValue BaseLoc = Base->getBasePtr();
8872   if (Loc.getOpcode() == ISD::FrameIndex) {
8873     if (BaseLoc.getOpcode() != ISD::FrameIndex)
8874       return false;
8875     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8876     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
8877     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
8878     int FS  = MFI->getObjectSize(FI);
8879     int BFS = MFI->getObjectSize(BFI);
8880     if (FS != BFS || FS != (int)Bytes) return false;
8881     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
8882   }
8883
8884   // Handle X+C
8885   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
8886       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
8887     return true;
8888
8889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8890   const GlobalValue *GV1 = nullptr;
8891   const GlobalValue *GV2 = nullptr;
8892   int64_t Offset1 = 0;
8893   int64_t Offset2 = 0;
8894   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
8895   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
8896   if (isGA1 && isGA2 && GV1 == GV2)
8897     return Offset1 == (Offset2 + Dist*Bytes);
8898   return false;
8899 }
8900
8901 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
8902 // not enforce equality of the chain operands.
8903 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
8904                             unsigned Bytes, int Dist,
8905                             SelectionDAG &DAG) {
8906   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
8907     EVT VT = LS->getMemoryVT();
8908     SDValue Loc = LS->getBasePtr();
8909     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
8910   }
8911
8912   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
8913     EVT VT;
8914     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8915     default: return false;
8916     case Intrinsic::ppc_qpx_qvlfd:
8917     case Intrinsic::ppc_qpx_qvlfda:
8918       VT = MVT::v4f64;
8919       break;
8920     case Intrinsic::ppc_qpx_qvlfs:
8921     case Intrinsic::ppc_qpx_qvlfsa:
8922       VT = MVT::v4f32;
8923       break;
8924     case Intrinsic::ppc_qpx_qvlfcd:
8925     case Intrinsic::ppc_qpx_qvlfcda:
8926       VT = MVT::v2f64;
8927       break;
8928     case Intrinsic::ppc_qpx_qvlfcs:
8929     case Intrinsic::ppc_qpx_qvlfcsa:
8930       VT = MVT::v2f32;
8931       break;
8932     case Intrinsic::ppc_qpx_qvlfiwa:
8933     case Intrinsic::ppc_qpx_qvlfiwz:
8934     case Intrinsic::ppc_altivec_lvx:
8935     case Intrinsic::ppc_altivec_lvxl:
8936     case Intrinsic::ppc_vsx_lxvw4x:
8937       VT = MVT::v4i32;
8938       break;
8939     case Intrinsic::ppc_vsx_lxvd2x:
8940       VT = MVT::v2f64;
8941       break;
8942     case Intrinsic::ppc_altivec_lvebx:
8943       VT = MVT::i8;
8944       break;
8945     case Intrinsic::ppc_altivec_lvehx:
8946       VT = MVT::i16;
8947       break;
8948     case Intrinsic::ppc_altivec_lvewx:
8949       VT = MVT::i32;
8950       break;
8951     }
8952
8953     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
8954   }
8955
8956   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
8957     EVT VT;
8958     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8959     default: return false;
8960     case Intrinsic::ppc_qpx_qvstfd:
8961     case Intrinsic::ppc_qpx_qvstfda:
8962       VT = MVT::v4f64;
8963       break;
8964     case Intrinsic::ppc_qpx_qvstfs:
8965     case Intrinsic::ppc_qpx_qvstfsa:
8966       VT = MVT::v4f32;
8967       break;
8968     case Intrinsic::ppc_qpx_qvstfcd:
8969     case Intrinsic::ppc_qpx_qvstfcda:
8970       VT = MVT::v2f64;
8971       break;
8972     case Intrinsic::ppc_qpx_qvstfcs:
8973     case Intrinsic::ppc_qpx_qvstfcsa:
8974       VT = MVT::v2f32;
8975       break;
8976     case Intrinsic::ppc_qpx_qvstfiw:
8977     case Intrinsic::ppc_qpx_qvstfiwa:
8978     case Intrinsic::ppc_altivec_stvx:
8979     case Intrinsic::ppc_altivec_stvxl:
8980     case Intrinsic::ppc_vsx_stxvw4x:
8981       VT = MVT::v4i32;
8982       break;
8983     case Intrinsic::ppc_vsx_stxvd2x:
8984       VT = MVT::v2f64;
8985       break;
8986     case Intrinsic::ppc_altivec_stvebx:
8987       VT = MVT::i8;
8988       break;
8989     case Intrinsic::ppc_altivec_stvehx:
8990       VT = MVT::i16;
8991       break;
8992     case Intrinsic::ppc_altivec_stvewx:
8993       VT = MVT::i32;
8994       break;
8995     }
8996
8997     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
8998   }
8999
9000   return false;
9001 }
9002
9003 // Return true is there is a nearyby consecutive load to the one provided
9004 // (regardless of alignment). We search up and down the chain, looking though
9005 // token factors and other loads (but nothing else). As a result, a true result
9006 // indicates that it is safe to create a new consecutive load adjacent to the
9007 // load provided.
9008 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9009   SDValue Chain = LD->getChain();
9010   EVT VT = LD->getMemoryVT();
9011
9012   SmallSet<SDNode *, 16> LoadRoots;
9013   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9014   SmallSet<SDNode *, 16> Visited;
9015
9016   // First, search up the chain, branching to follow all token-factor operands.
9017   // If we find a consecutive load, then we're done, otherwise, record all
9018   // nodes just above the top-level loads and token factors.
9019   while (!Queue.empty()) {
9020     SDNode *ChainNext = Queue.pop_back_val();
9021     if (!Visited.insert(ChainNext).second)
9022       continue;
9023
9024     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9025       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9026         return true;
9027
9028       if (!Visited.count(ChainLD->getChain().getNode()))
9029         Queue.push_back(ChainLD->getChain().getNode());
9030     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9031       for (const SDUse &O : ChainNext->ops())
9032         if (!Visited.count(O.getNode()))
9033           Queue.push_back(O.getNode());
9034     } else
9035       LoadRoots.insert(ChainNext);
9036   }
9037
9038   // Second, search down the chain, starting from the top-level nodes recorded
9039   // in the first phase. These top-level nodes are the nodes just above all
9040   // loads and token factors. Starting with their uses, recursively look though
9041   // all loads (just the chain uses) and token factors to find a consecutive
9042   // load.
9043   Visited.clear();
9044   Queue.clear();
9045
9046   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9047        IE = LoadRoots.end(); I != IE; ++I) {
9048     Queue.push_back(*I);
9049        
9050     while (!Queue.empty()) {
9051       SDNode *LoadRoot = Queue.pop_back_val();
9052       if (!Visited.insert(LoadRoot).second)
9053         continue;
9054
9055       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9056         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9057           return true;
9058
9059       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9060            UE = LoadRoot->use_end(); UI != UE; ++UI)
9061         if (((isa<MemSDNode>(*UI) &&
9062             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9063             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9064           Queue.push_back(*UI);
9065     }
9066   }
9067
9068   return false;
9069 }
9070
9071 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9072                                                   DAGCombinerInfo &DCI) const {
9073   SelectionDAG &DAG = DCI.DAG;
9074   SDLoc dl(N);
9075
9076   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9077   // If we're tracking CR bits, we need to be careful that we don't have:
9078   //   trunc(binary-ops(zext(x), zext(y)))
9079   // or
9080   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9081   // such that we're unnecessarily moving things into GPRs when it would be
9082   // better to keep them in CR bits.
9083
9084   // Note that trunc here can be an actual i1 trunc, or can be the effective
9085   // truncation that comes from a setcc or select_cc.
9086   if (N->getOpcode() == ISD::TRUNCATE &&
9087       N->getValueType(0) != MVT::i1)
9088     return SDValue();
9089
9090   if (N->getOperand(0).getValueType() != MVT::i32 &&
9091       N->getOperand(0).getValueType() != MVT::i64)
9092     return SDValue();
9093
9094   if (N->getOpcode() == ISD::SETCC ||
9095       N->getOpcode() == ISD::SELECT_CC) {
9096     // If we're looking at a comparison, then we need to make sure that the
9097     // high bits (all except for the first) don't matter the result.
9098     ISD::CondCode CC =
9099       cast<CondCodeSDNode>(N->getOperand(
9100         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9101     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9102
9103     if (ISD::isSignedIntSetCC(CC)) {
9104       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9105           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9106         return SDValue();
9107     } else if (ISD::isUnsignedIntSetCC(CC)) {
9108       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9109                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9110           !DAG.MaskedValueIsZero(N->getOperand(1),
9111                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9112         return SDValue();
9113     } else {
9114       // This is neither a signed nor an unsigned comparison, just make sure
9115       // that the high bits are equal.
9116       APInt Op1Zero, Op1One;
9117       APInt Op2Zero, Op2One;
9118       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9119       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9120
9121       // We don't really care about what is known about the first bit (if
9122       // anything), so clear it in all masks prior to comparing them.
9123       Op1Zero.clearBit(0); Op1One.clearBit(0);
9124       Op2Zero.clearBit(0); Op2One.clearBit(0);
9125
9126       if (Op1Zero != Op2Zero || Op1One != Op2One)
9127         return SDValue();
9128     }
9129   }
9130
9131   // We now know that the higher-order bits are irrelevant, we just need to
9132   // make sure that all of the intermediate operations are bit operations, and
9133   // all inputs are extensions.
9134   if (N->getOperand(0).getOpcode() != ISD::AND &&
9135       N->getOperand(0).getOpcode() != ISD::OR  &&
9136       N->getOperand(0).getOpcode() != ISD::XOR &&
9137       N->getOperand(0).getOpcode() != ISD::SELECT &&
9138       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9139       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9140       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9141       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9142       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9143     return SDValue();
9144
9145   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9146       N->getOperand(1).getOpcode() != ISD::AND &&
9147       N->getOperand(1).getOpcode() != ISD::OR  &&
9148       N->getOperand(1).getOpcode() != ISD::XOR &&
9149       N->getOperand(1).getOpcode() != ISD::SELECT &&
9150       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9151       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9152       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9153       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9154       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9155     return SDValue();
9156
9157   SmallVector<SDValue, 4> Inputs;
9158   SmallVector<SDValue, 8> BinOps, PromOps;
9159   SmallPtrSet<SDNode *, 16> Visited;
9160
9161   for (unsigned i = 0; i < 2; ++i) {
9162     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9163           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9164           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9165           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9166         isa<ConstantSDNode>(N->getOperand(i)))
9167       Inputs.push_back(N->getOperand(i));
9168     else
9169       BinOps.push_back(N->getOperand(i));
9170
9171     if (N->getOpcode() == ISD::TRUNCATE)
9172       break;
9173   }
9174
9175   // Visit all inputs, collect all binary operations (and, or, xor and
9176   // select) that are all fed by extensions. 
9177   while (!BinOps.empty()) {
9178     SDValue BinOp = BinOps.back();
9179     BinOps.pop_back();
9180
9181     if (!Visited.insert(BinOp.getNode()).second)
9182       continue;
9183
9184     PromOps.push_back(BinOp);
9185
9186     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9187       // The condition of the select is not promoted.
9188       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9189         continue;
9190       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9191         continue;
9192
9193       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9194             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9195             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9196            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9197           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9198         Inputs.push_back(BinOp.getOperand(i)); 
9199       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9200                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9201                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9202                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9203                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9204                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9205                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9206                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9207                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9208         BinOps.push_back(BinOp.getOperand(i));
9209       } else {
9210         // We have an input that is not an extension or another binary
9211         // operation; we'll abort this transformation.
9212         return SDValue();
9213       }
9214     }
9215   }
9216
9217   // Make sure that this is a self-contained cluster of operations (which
9218   // is not quite the same thing as saying that everything has only one
9219   // use).
9220   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9221     if (isa<ConstantSDNode>(Inputs[i]))
9222       continue;
9223
9224     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9225                               UE = Inputs[i].getNode()->use_end();
9226          UI != UE; ++UI) {
9227       SDNode *User = *UI;
9228       if (User != N && !Visited.count(User))
9229         return SDValue();
9230
9231       // Make sure that we're not going to promote the non-output-value
9232       // operand(s) or SELECT or SELECT_CC.
9233       // FIXME: Although we could sometimes handle this, and it does occur in
9234       // practice that one of the condition inputs to the select is also one of
9235       // the outputs, we currently can't deal with this.
9236       if (User->getOpcode() == ISD::SELECT) {
9237         if (User->getOperand(0) == Inputs[i])
9238           return SDValue();
9239       } else if (User->getOpcode() == ISD::SELECT_CC) {
9240         if (User->getOperand(0) == Inputs[i] ||
9241             User->getOperand(1) == Inputs[i])
9242           return SDValue();
9243       }
9244     }
9245   }
9246
9247   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9248     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9249                               UE = PromOps[i].getNode()->use_end();
9250          UI != UE; ++UI) {
9251       SDNode *User = *UI;
9252       if (User != N && !Visited.count(User))
9253         return SDValue();
9254
9255       // Make sure that we're not going to promote the non-output-value
9256       // operand(s) or SELECT or SELECT_CC.
9257       // FIXME: Although we could sometimes handle this, and it does occur in
9258       // practice that one of the condition inputs to the select is also one of
9259       // the outputs, we currently can't deal with this.
9260       if (User->getOpcode() == ISD::SELECT) {
9261         if (User->getOperand(0) == PromOps[i])
9262           return SDValue();
9263       } else if (User->getOpcode() == ISD::SELECT_CC) {
9264         if (User->getOperand(0) == PromOps[i] ||
9265             User->getOperand(1) == PromOps[i])
9266           return SDValue();
9267       }
9268     }
9269   }
9270
9271   // Replace all inputs with the extension operand.
9272   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9273     // Constants may have users outside the cluster of to-be-promoted nodes,
9274     // and so we need to replace those as we do the promotions.
9275     if (isa<ConstantSDNode>(Inputs[i]))
9276       continue;
9277     else
9278       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9279   }
9280
9281   // Replace all operations (these are all the same, but have a different
9282   // (i1) return type). DAG.getNode will validate that the types of
9283   // a binary operator match, so go through the list in reverse so that
9284   // we've likely promoted both operands first. Any intermediate truncations or
9285   // extensions disappear.
9286   while (!PromOps.empty()) {
9287     SDValue PromOp = PromOps.back();
9288     PromOps.pop_back();
9289
9290     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9291         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9292         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9293         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9294       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9295           PromOp.getOperand(0).getValueType() != MVT::i1) {
9296         // The operand is not yet ready (see comment below).
9297         PromOps.insert(PromOps.begin(), PromOp);
9298         continue;
9299       }
9300
9301       SDValue RepValue = PromOp.getOperand(0);
9302       if (isa<ConstantSDNode>(RepValue))
9303         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9304
9305       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9306       continue;
9307     }
9308
9309     unsigned C;
9310     switch (PromOp.getOpcode()) {
9311     default:             C = 0; break;
9312     case ISD::SELECT:    C = 1; break;
9313     case ISD::SELECT_CC: C = 2; break;
9314     }
9315
9316     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9317          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9318         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9319          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9320       // The to-be-promoted operands of this node have not yet been
9321       // promoted (this should be rare because we're going through the
9322       // list backward, but if one of the operands has several users in
9323       // this cluster of to-be-promoted nodes, it is possible).
9324       PromOps.insert(PromOps.begin(), PromOp);
9325       continue;
9326     }
9327
9328     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9329                                 PromOp.getNode()->op_end());
9330
9331     // If there are any constant inputs, make sure they're replaced now.
9332     for (unsigned i = 0; i < 2; ++i)
9333       if (isa<ConstantSDNode>(Ops[C+i]))
9334         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9335
9336     DAG.ReplaceAllUsesOfValueWith(PromOp,
9337       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9338   }
9339
9340   // Now we're left with the initial truncation itself.
9341   if (N->getOpcode() == ISD::TRUNCATE)
9342     return N->getOperand(0);
9343
9344   // Otherwise, this is a comparison. The operands to be compared have just
9345   // changed type (to i1), but everything else is the same.
9346   return SDValue(N, 0);
9347 }
9348
9349 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9350                                                   DAGCombinerInfo &DCI) const {
9351   SelectionDAG &DAG = DCI.DAG;
9352   SDLoc dl(N);
9353
9354   // If we're tracking CR bits, we need to be careful that we don't have:
9355   //   zext(binary-ops(trunc(x), trunc(y)))
9356   // or
9357   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9358   // such that we're unnecessarily moving things into CR bits that can more
9359   // efficiently stay in GPRs. Note that if we're not certain that the high
9360   // bits are set as required by the final extension, we still may need to do
9361   // some masking to get the proper behavior.
9362
9363   // This same functionality is important on PPC64 when dealing with
9364   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9365   // the return values of functions. Because it is so similar, it is handled
9366   // here as well.
9367
9368   if (N->getValueType(0) != MVT::i32 &&
9369       N->getValueType(0) != MVT::i64)
9370     return SDValue();
9371
9372   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9373         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9374     return SDValue();
9375
9376   if (N->getOperand(0).getOpcode() != ISD::AND &&
9377       N->getOperand(0).getOpcode() != ISD::OR  &&
9378       N->getOperand(0).getOpcode() != ISD::XOR &&
9379       N->getOperand(0).getOpcode() != ISD::SELECT &&
9380       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9381     return SDValue();
9382
9383   SmallVector<SDValue, 4> Inputs;
9384   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9385   SmallPtrSet<SDNode *, 16> Visited;
9386
9387   // Visit all inputs, collect all binary operations (and, or, xor and
9388   // select) that are all fed by truncations. 
9389   while (!BinOps.empty()) {
9390     SDValue BinOp = BinOps.back();
9391     BinOps.pop_back();
9392
9393     if (!Visited.insert(BinOp.getNode()).second)
9394       continue;
9395
9396     PromOps.push_back(BinOp);
9397
9398     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9399       // The condition of the select is not promoted.
9400       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9401         continue;
9402       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9403         continue;
9404
9405       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9406           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9407         Inputs.push_back(BinOp.getOperand(i)); 
9408       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9409                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9410                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9411                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9412                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9413         BinOps.push_back(BinOp.getOperand(i));
9414       } else {
9415         // We have an input that is not a truncation or another binary
9416         // operation; we'll abort this transformation.
9417         return SDValue();
9418       }
9419     }
9420   }
9421
9422   // The operands of a select that must be truncated when the select is
9423   // promoted because the operand is actually part of the to-be-promoted set.
9424   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9425
9426   // Make sure that this is a self-contained cluster of operations (which
9427   // is not quite the same thing as saying that everything has only one
9428   // use).
9429   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9430     if (isa<ConstantSDNode>(Inputs[i]))
9431       continue;
9432
9433     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9434                               UE = Inputs[i].getNode()->use_end();
9435          UI != UE; ++UI) {
9436       SDNode *User = *UI;
9437       if (User != N && !Visited.count(User))
9438         return SDValue();
9439
9440       // If we're going to promote the non-output-value operand(s) or SELECT or
9441       // SELECT_CC, record them for truncation.
9442       if (User->getOpcode() == ISD::SELECT) {
9443         if (User->getOperand(0) == Inputs[i])
9444           SelectTruncOp[0].insert(std::make_pair(User,
9445                                     User->getOperand(0).getValueType()));
9446       } else if (User->getOpcode() == ISD::SELECT_CC) {
9447         if (User->getOperand(0) == Inputs[i])
9448           SelectTruncOp[0].insert(std::make_pair(User,
9449                                     User->getOperand(0).getValueType()));
9450         if (User->getOperand(1) == Inputs[i])
9451           SelectTruncOp[1].insert(std::make_pair(User,
9452                                     User->getOperand(1).getValueType()));
9453       }
9454     }
9455   }
9456
9457   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9458     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9459                               UE = PromOps[i].getNode()->use_end();
9460          UI != UE; ++UI) {
9461       SDNode *User = *UI;
9462       if (User != N && !Visited.count(User))
9463         return SDValue();
9464
9465       // If we're going to promote the non-output-value operand(s) or SELECT or
9466       // SELECT_CC, record them for truncation.
9467       if (User->getOpcode() == ISD::SELECT) {
9468         if (User->getOperand(0) == PromOps[i])
9469           SelectTruncOp[0].insert(std::make_pair(User,
9470                                     User->getOperand(0).getValueType()));
9471       } else if (User->getOpcode() == ISD::SELECT_CC) {
9472         if (User->getOperand(0) == PromOps[i])
9473           SelectTruncOp[0].insert(std::make_pair(User,
9474                                     User->getOperand(0).getValueType()));
9475         if (User->getOperand(1) == PromOps[i])
9476           SelectTruncOp[1].insert(std::make_pair(User,
9477                                     User->getOperand(1).getValueType()));
9478       }
9479     }
9480   }
9481
9482   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9483   bool ReallyNeedsExt = false;
9484   if (N->getOpcode() != ISD::ANY_EXTEND) {
9485     // If all of the inputs are not already sign/zero extended, then
9486     // we'll still need to do that at the end.
9487     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9488       if (isa<ConstantSDNode>(Inputs[i]))
9489         continue;
9490
9491       unsigned OpBits =
9492         Inputs[i].getOperand(0).getValueSizeInBits();
9493       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9494
9495       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9496            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9497                                   APInt::getHighBitsSet(OpBits,
9498                                                         OpBits-PromBits))) ||
9499           (N->getOpcode() == ISD::SIGN_EXTEND &&
9500            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9501              (OpBits-(PromBits-1)))) {
9502         ReallyNeedsExt = true;
9503         break;
9504       }
9505     }
9506   }
9507
9508   // Replace all inputs, either with the truncation operand, or a
9509   // truncation or extension to the final output type.
9510   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9511     // Constant inputs need to be replaced with the to-be-promoted nodes that
9512     // use them because they might have users outside of the cluster of
9513     // promoted nodes.
9514     if (isa<ConstantSDNode>(Inputs[i]))
9515       continue;
9516
9517     SDValue InSrc = Inputs[i].getOperand(0);
9518     if (Inputs[i].getValueType() == N->getValueType(0))
9519       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9520     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9521       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9522         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9523     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9524       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9525         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9526     else
9527       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9528         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9529   }
9530
9531   // Replace all operations (these are all the same, but have a different
9532   // (promoted) return type). DAG.getNode will validate that the types of
9533   // a binary operator match, so go through the list in reverse so that
9534   // we've likely promoted both operands first.
9535   while (!PromOps.empty()) {
9536     SDValue PromOp = PromOps.back();
9537     PromOps.pop_back();
9538
9539     unsigned C;
9540     switch (PromOp.getOpcode()) {
9541     default:             C = 0; break;
9542     case ISD::SELECT:    C = 1; break;
9543     case ISD::SELECT_CC: C = 2; break;
9544     }
9545
9546     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9547          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9548         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9549          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9550       // The to-be-promoted operands of this node have not yet been
9551       // promoted (this should be rare because we're going through the
9552       // list backward, but if one of the operands has several users in
9553       // this cluster of to-be-promoted nodes, it is possible).
9554       PromOps.insert(PromOps.begin(), PromOp);
9555       continue;
9556     }
9557
9558     // For SELECT and SELECT_CC nodes, we do a similar check for any
9559     // to-be-promoted comparison inputs.
9560     if (PromOp.getOpcode() == ISD::SELECT ||
9561         PromOp.getOpcode() == ISD::SELECT_CC) {
9562       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9563            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9564           (SelectTruncOp[1].count(PromOp.getNode()) &&
9565            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9566         PromOps.insert(PromOps.begin(), PromOp);
9567         continue;
9568       }
9569     }
9570
9571     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9572                                 PromOp.getNode()->op_end());
9573
9574     // If this node has constant inputs, then they'll need to be promoted here.
9575     for (unsigned i = 0; i < 2; ++i) {
9576       if (!isa<ConstantSDNode>(Ops[C+i]))
9577         continue;
9578       if (Ops[C+i].getValueType() == N->getValueType(0))
9579         continue;
9580
9581       if (N->getOpcode() == ISD::SIGN_EXTEND)
9582         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9583       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9584         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9585       else
9586         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9587     }
9588
9589     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9590     // truncate them again to the original value type.
9591     if (PromOp.getOpcode() == ISD::SELECT ||
9592         PromOp.getOpcode() == ISD::SELECT_CC) {
9593       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9594       if (SI0 != SelectTruncOp[0].end())
9595         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9596       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9597       if (SI1 != SelectTruncOp[1].end())
9598         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9599     }
9600
9601     DAG.ReplaceAllUsesOfValueWith(PromOp,
9602       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9603   }
9604
9605   // Now we're left with the initial extension itself.
9606   if (!ReallyNeedsExt)
9607     return N->getOperand(0);
9608
9609   // To zero extend, just mask off everything except for the first bit (in the
9610   // i1 case).
9611   if (N->getOpcode() == ISD::ZERO_EXTEND)
9612     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9613                        DAG.getConstant(APInt::getLowBitsSet(
9614                                          N->getValueSizeInBits(0), PromBits),
9615                                        N->getValueType(0)));
9616
9617   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9618          "Invalid extension type");
9619   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9620   SDValue ShiftCst =
9621     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
9622   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9623                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9624                                  N->getOperand(0), ShiftCst), ShiftCst);
9625 }
9626
9627 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9628                                               DAGCombinerInfo &DCI) const {
9629   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9630           N->getOpcode() == ISD::UINT_TO_FP) &&
9631          "Need an int -> FP conversion node here");
9632
9633   if (!Subtarget.has64BitSupport())
9634     return SDValue();
9635
9636   SelectionDAG &DAG = DCI.DAG;
9637   SDLoc dl(N);
9638   SDValue Op(N, 0);
9639
9640   // Don't handle ppc_fp128 here or i1 conversions.
9641   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9642     return SDValue();
9643   if (Op.getOperand(0).getValueType() == MVT::i1)
9644     return SDValue();
9645
9646   // For i32 intermediate values, unfortunately, the conversion functions
9647   // leave the upper 32 bits of the value are undefined. Within the set of
9648   // scalar instructions, we have no method for zero- or sign-extending the
9649   // value. Thus, we cannot handle i32 intermediate values here.
9650   if (Op.getOperand(0).getValueType() == MVT::i32)
9651     return SDValue();
9652
9653   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9654          "UINT_TO_FP is supported only with FPCVT");
9655
9656   // If we have FCFIDS, then use it when converting to single-precision.
9657   // Otherwise, convert to double-precision and then round.
9658   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9659                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9660                                                             : PPCISD::FCFIDS)
9661                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9662                                                             : PPCISD::FCFID);
9663   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9664                   ? MVT::f32
9665                   : MVT::f64;
9666
9667   // If we're converting from a float, to an int, and back to a float again,
9668   // then we don't need the store/load pair at all.
9669   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9670        Subtarget.hasFPCVT()) ||
9671       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9672     SDValue Src = Op.getOperand(0).getOperand(0);
9673     if (Src.getValueType() == MVT::f32) {
9674       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9675       DCI.AddToWorklist(Src.getNode());
9676     }
9677
9678     unsigned FCTOp =
9679       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9680                                                         PPCISD::FCTIDUZ;
9681
9682     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9683     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9684
9685     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9686       FP = DAG.getNode(ISD::FP_ROUND, dl,
9687                        MVT::f32, FP, DAG.getIntPtrConstant(0));
9688       DCI.AddToWorklist(FP.getNode());
9689     }
9690
9691     return FP;
9692   }
9693
9694   return SDValue();
9695 }
9696
9697 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9698 // builtins) into loads with swaps.
9699 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9700                                               DAGCombinerInfo &DCI) const {
9701   SelectionDAG &DAG = DCI.DAG;
9702   SDLoc dl(N);
9703   SDValue Chain;
9704   SDValue Base;
9705   MachineMemOperand *MMO;
9706
9707   switch (N->getOpcode()) {
9708   default:
9709     llvm_unreachable("Unexpected opcode for little endian VSX load");
9710   case ISD::LOAD: {
9711     LoadSDNode *LD = cast<LoadSDNode>(N);
9712     Chain = LD->getChain();
9713     Base = LD->getBasePtr();
9714     MMO = LD->getMemOperand();
9715     // If the MMO suggests this isn't a load of a full vector, leave
9716     // things alone.  For a built-in, we have to make the change for
9717     // correctness, so if there is a size problem that will be a bug.
9718     if (MMO->getSize() < 16)
9719       return SDValue();
9720     break;
9721   }
9722   case ISD::INTRINSIC_W_CHAIN: {
9723     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9724     Chain = Intrin->getChain();
9725     Base = Intrin->getBasePtr();
9726     MMO = Intrin->getMemOperand();
9727     break;
9728   }
9729   }
9730
9731   MVT VecTy = N->getValueType(0).getSimpleVT();
9732   SDValue LoadOps[] = { Chain, Base };
9733   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9734                                          DAG.getVTList(VecTy, MVT::Other),
9735                                          LoadOps, VecTy, MMO);
9736   DCI.AddToWorklist(Load.getNode());
9737   Chain = Load.getValue(1);
9738   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9739                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9740   DCI.AddToWorklist(Swap.getNode());
9741   return Swap;
9742 }
9743
9744 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9745 // builtins) into stores with swaps.
9746 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9747                                                DAGCombinerInfo &DCI) const {
9748   SelectionDAG &DAG = DCI.DAG;
9749   SDLoc dl(N);
9750   SDValue Chain;
9751   SDValue Base;
9752   unsigned SrcOpnd;
9753   MachineMemOperand *MMO;
9754
9755   switch (N->getOpcode()) {
9756   default:
9757     llvm_unreachable("Unexpected opcode for little endian VSX store");
9758   case ISD::STORE: {
9759     StoreSDNode *ST = cast<StoreSDNode>(N);
9760     Chain = ST->getChain();
9761     Base = ST->getBasePtr();
9762     MMO = ST->getMemOperand();
9763     SrcOpnd = 1;
9764     // If the MMO suggests this isn't a store of a full vector, leave
9765     // things alone.  For a built-in, we have to make the change for
9766     // correctness, so if there is a size problem that will be a bug.
9767     if (MMO->getSize() < 16)
9768       return SDValue();
9769     break;
9770   }
9771   case ISD::INTRINSIC_VOID: {
9772     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9773     Chain = Intrin->getChain();
9774     // Intrin->getBasePtr() oddly does not get what we want.
9775     Base = Intrin->getOperand(3);
9776     MMO = Intrin->getMemOperand();
9777     SrcOpnd = 2;
9778     break;
9779   }
9780   }
9781
9782   SDValue Src = N->getOperand(SrcOpnd);
9783   MVT VecTy = Src.getValueType().getSimpleVT();
9784   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9785                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9786   DCI.AddToWorklist(Swap.getNode());
9787   Chain = Swap.getValue(1);
9788   SDValue StoreOps[] = { Chain, Swap, Base };
9789   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9790                                           DAG.getVTList(MVT::Other),
9791                                           StoreOps, VecTy, MMO);
9792   DCI.AddToWorklist(Store.getNode());
9793   return Store;
9794 }
9795
9796 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9797                                              DAGCombinerInfo &DCI) const {
9798   SelectionDAG &DAG = DCI.DAG;
9799   SDLoc dl(N);
9800   switch (N->getOpcode()) {
9801   default: break;
9802   case PPCISD::SHL:
9803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9804       if (C->isNullValue())   // 0 << V -> 0.
9805         return N->getOperand(0);
9806     }
9807     break;
9808   case PPCISD::SRL:
9809     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9810       if (C->isNullValue())   // 0 >>u V -> 0.
9811         return N->getOperand(0);
9812     }
9813     break;
9814   case PPCISD::SRA:
9815     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9816       if (C->isNullValue() ||   //  0 >>s V -> 0.
9817           C->isAllOnesValue())    // -1 >>s V -> -1.
9818         return N->getOperand(0);
9819     }
9820     break;
9821   case ISD::SIGN_EXTEND:
9822   case ISD::ZERO_EXTEND:
9823   case ISD::ANY_EXTEND: 
9824     return DAGCombineExtBoolTrunc(N, DCI);
9825   case ISD::TRUNCATE:
9826   case ISD::SETCC:
9827   case ISD::SELECT_CC:
9828     return DAGCombineTruncBoolExt(N, DCI);
9829   case ISD::SINT_TO_FP:
9830   case ISD::UINT_TO_FP:
9831     return combineFPToIntToFP(N, DCI);
9832   case ISD::STORE: {
9833     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9834     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9835         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9836         N->getOperand(1).getValueType() == MVT::i32 &&
9837         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9838       SDValue Val = N->getOperand(1).getOperand(0);
9839       if (Val.getValueType() == MVT::f32) {
9840         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9841         DCI.AddToWorklist(Val.getNode());
9842       }
9843       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9844       DCI.AddToWorklist(Val.getNode());
9845
9846       SDValue Ops[] = {
9847         N->getOperand(0), Val, N->getOperand(2),
9848         DAG.getValueType(N->getOperand(1).getValueType())
9849       };
9850
9851       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9852               DAG.getVTList(MVT::Other), Ops,
9853               cast<StoreSDNode>(N)->getMemoryVT(),
9854               cast<StoreSDNode>(N)->getMemOperand());
9855       DCI.AddToWorklist(Val.getNode());
9856       return Val;
9857     }
9858
9859     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
9860     if (cast<StoreSDNode>(N)->isUnindexed() &&
9861         N->getOperand(1).getOpcode() == ISD::BSWAP &&
9862         N->getOperand(1).getNode()->hasOneUse() &&
9863         (N->getOperand(1).getValueType() == MVT::i32 ||
9864          N->getOperand(1).getValueType() == MVT::i16 ||
9865          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
9866           N->getOperand(1).getValueType() == MVT::i64))) {
9867       SDValue BSwapOp = N->getOperand(1).getOperand(0);
9868       // Do an any-extend to 32-bits if this is a half-word input.
9869       if (BSwapOp.getValueType() == MVT::i16)
9870         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
9871
9872       SDValue Ops[] = {
9873         N->getOperand(0), BSwapOp, N->getOperand(2),
9874         DAG.getValueType(N->getOperand(1).getValueType())
9875       };
9876       return
9877         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
9878                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
9879                                 cast<StoreSDNode>(N)->getMemOperand());
9880     }
9881
9882     // For little endian, VSX stores require generating xxswapd/lxvd2x.
9883     EVT VT = N->getOperand(1).getValueType();
9884     if (VT.isSimple()) {
9885       MVT StoreVT = VT.getSimpleVT();
9886       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9887           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
9888            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
9889         return expandVSXStoreForLE(N, DCI);
9890     }
9891     break;
9892   }
9893   case ISD::LOAD: {
9894     LoadSDNode *LD = cast<LoadSDNode>(N);
9895     EVT VT = LD->getValueType(0);
9896
9897     // For little endian, VSX loads require generating lxvd2x/xxswapd.
9898     if (VT.isSimple()) {
9899       MVT LoadVT = VT.getSimpleVT();
9900       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
9901           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
9902            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
9903         return expandVSXLoadForLE(N, DCI);
9904     }
9905
9906     EVT MemVT = LD->getMemoryVT();
9907     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
9908     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
9909     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
9910     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
9911     if (LD->isUnindexed() && VT.isVector() &&
9912         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
9913           // P8 and later hardware should just use LOAD.
9914           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
9915                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
9916          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
9917           LD->getAlignment() >= ScalarABIAlignment)) &&
9918         LD->getAlignment() < ABIAlignment) {
9919       // This is a type-legal unaligned Altivec or QPX load.
9920       SDValue Chain = LD->getChain();
9921       SDValue Ptr = LD->getBasePtr();
9922       bool isLittleEndian = Subtarget.isLittleEndian();
9923
9924       // This implements the loading of unaligned vectors as described in
9925       // the venerable Apple Velocity Engine overview. Specifically:
9926       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
9927       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
9928       //
9929       // The general idea is to expand a sequence of one or more unaligned
9930       // loads into an alignment-based permutation-control instruction (lvsl
9931       // or lvsr), a series of regular vector loads (which always truncate
9932       // their input address to an aligned address), and a series of
9933       // permutations.  The results of these permutations are the requested
9934       // loaded values.  The trick is that the last "extra" load is not taken
9935       // from the address you might suspect (sizeof(vector) bytes after the
9936       // last requested load), but rather sizeof(vector) - 1 bytes after the
9937       // last requested vector. The point of this is to avoid a page fault if
9938       // the base address happened to be aligned. This works because if the
9939       // base address is aligned, then adding less than a full vector length
9940       // will cause the last vector in the sequence to be (re)loaded.
9941       // Otherwise, the next vector will be fetched as you might suspect was
9942       // necessary.
9943
9944       // We might be able to reuse the permutation generation from
9945       // a different base address offset from this one by an aligned amount.
9946       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
9947       // optimization later.
9948       Intrinsic::ID Intr, IntrLD, IntrPerm;
9949       MVT PermCntlTy, PermTy, LDTy;
9950       if (Subtarget.hasAltivec()) {
9951         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
9952                                  Intrinsic::ppc_altivec_lvsl;
9953         IntrLD = Intrinsic::ppc_altivec_lvx;
9954         IntrPerm = Intrinsic::ppc_altivec_vperm;
9955         PermCntlTy = MVT::v16i8;
9956         PermTy = MVT::v4i32;
9957         LDTy = MVT::v4i32;
9958       } else {
9959         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
9960                                        Intrinsic::ppc_qpx_qvlpcls;
9961         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
9962                                        Intrinsic::ppc_qpx_qvlfs;
9963         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
9964         PermCntlTy = MVT::v4f64;
9965         PermTy = MVT::v4f64;
9966         LDTy = MemVT.getSimpleVT();
9967       }
9968
9969       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
9970
9971       // Create the new MMO for the new base load. It is like the original MMO,
9972       // but represents an area in memory almost twice the vector size centered
9973       // on the original address. If the address is unaligned, we might start
9974       // reading up to (sizeof(vector)-1) bytes below the address of the
9975       // original unaligned load.
9976       MachineFunction &MF = DAG.getMachineFunction();
9977       MachineMemOperand *BaseMMO =
9978         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
9979                                 2*MemVT.getStoreSize()-1);
9980
9981       // Create the new base load.
9982       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, getPointerTy());
9983       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
9984       SDValue BaseLoad =
9985         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
9986                                 DAG.getVTList(PermTy, MVT::Other),
9987                                 BaseLoadOps, LDTy, BaseMMO);
9988
9989       // Note that the value of IncOffset (which is provided to the next
9990       // load's pointer info offset value, and thus used to calculate the
9991       // alignment), and the value of IncValue (which is actually used to
9992       // increment the pointer value) are different! This is because we
9993       // require the next load to appear to be aligned, even though it
9994       // is actually offset from the base pointer by a lesser amount.
9995       int IncOffset = VT.getSizeInBits() / 8;
9996       int IncValue = IncOffset;
9997
9998       // Walk (both up and down) the chain looking for another load at the real
9999       // (aligned) offset (the alignment of the other load does not matter in
10000       // this case). If found, then do not use the offset reduction trick, as
10001       // that will prevent the loads from being later combined (as they would
10002       // otherwise be duplicates).
10003       if (!findConsecutiveLoad(LD, DAG))
10004         --IncValue;
10005
10006       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
10007       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10008
10009       MachineMemOperand *ExtraMMO =
10010         MF.getMachineMemOperand(LD->getMemOperand(),
10011                                 1, 2*MemVT.getStoreSize()-1);
10012       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10013       SDValue ExtraLoad =
10014         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10015                                 DAG.getVTList(PermTy, MVT::Other),
10016                                 ExtraLoadOps, LDTy, ExtraMMO);
10017
10018       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10019         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10020
10021       // Because vperm has a big-endian bias, we must reverse the order
10022       // of the input vectors and complement the permute control vector
10023       // when generating little endian code.  We have already handled the
10024       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10025       // and ExtraLoad here.
10026       SDValue Perm;
10027       if (isLittleEndian)
10028         Perm = BuildIntrinsicOp(IntrPerm,
10029                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10030       else
10031         Perm = BuildIntrinsicOp(IntrPerm,
10032                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10033
10034       if (VT != PermTy)
10035         Perm = Subtarget.hasAltivec() ?
10036                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10037                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10038                                DAG.getTargetConstant(1, MVT::i64));
10039                                // second argument is 1 because this rounding
10040                                // is always exact.
10041
10042       // The output of the permutation is our loaded result, the TokenFactor is
10043       // our new chain.
10044       DCI.CombineTo(N, Perm, TF);
10045       return SDValue(N, 0);
10046     }
10047     }
10048     break;
10049     case ISD::INTRINSIC_WO_CHAIN: {
10050       bool isLittleEndian = Subtarget.isLittleEndian();
10051       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10052       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10053                                            : Intrinsic::ppc_altivec_lvsl);
10054       if ((IID == Intr ||
10055            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10056            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10057         N->getOperand(1)->getOpcode() == ISD::ADD) {
10058         SDValue Add = N->getOperand(1);
10059
10060         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10061                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10062
10063         if (DAG.MaskedValueIsZero(
10064                 Add->getOperand(1),
10065                 APInt::getAllOnesValue(Bits /* alignment */)
10066                     .zext(
10067                         Add.getValueType().getScalarType().getSizeInBits()))) {
10068           SDNode *BasePtr = Add->getOperand(0).getNode();
10069           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10070                                     UE = BasePtr->use_end();
10071                UI != UE; ++UI) {
10072             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10073                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10074               // We've found another LVSL/LVSR, and this address is an aligned
10075               // multiple of that one. The results will be the same, so use the
10076               // one we've just found instead.
10077
10078               return SDValue(*UI, 0);
10079             }
10080           }
10081         }
10082
10083         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10084           SDNode *BasePtr = Add->getOperand(0).getNode();
10085           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10086                UE = BasePtr->use_end(); UI != UE; ++UI) {
10087             if (UI->getOpcode() == ISD::ADD &&
10088                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10089                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10090                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10091                 (1ULL << Bits) == 0) {
10092               SDNode *OtherAdd = *UI;
10093               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10094                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10095                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10096                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10097                   return SDValue(*VI, 0);
10098                 }
10099               }
10100             }
10101           }
10102         }
10103       }
10104     }
10105
10106     break;
10107   case ISD::INTRINSIC_W_CHAIN: {
10108     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10109     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10110       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10111       default:
10112         break;
10113       case Intrinsic::ppc_vsx_lxvw4x:
10114       case Intrinsic::ppc_vsx_lxvd2x:
10115         return expandVSXLoadForLE(N, DCI);
10116       }
10117     }
10118     break;
10119   }
10120   case ISD::INTRINSIC_VOID: {
10121     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10122     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10123       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10124       default:
10125         break;
10126       case Intrinsic::ppc_vsx_stxvw4x:
10127       case Intrinsic::ppc_vsx_stxvd2x:
10128         return expandVSXStoreForLE(N, DCI);
10129       }
10130     }
10131     break;
10132   }
10133   case ISD::BSWAP:
10134     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10135     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10136         N->getOperand(0).hasOneUse() &&
10137         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10138          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10139           N->getValueType(0) == MVT::i64))) {
10140       SDValue Load = N->getOperand(0);
10141       LoadSDNode *LD = cast<LoadSDNode>(Load);
10142       // Create the byte-swapping load.
10143       SDValue Ops[] = {
10144         LD->getChain(),    // Chain
10145         LD->getBasePtr(),  // Ptr
10146         DAG.getValueType(N->getValueType(0)) // VT
10147       };
10148       SDValue BSLoad =
10149         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10150                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10151                                               MVT::i64 : MVT::i32, MVT::Other),
10152                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10153
10154       // If this is an i16 load, insert the truncate.
10155       SDValue ResVal = BSLoad;
10156       if (N->getValueType(0) == MVT::i16)
10157         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10158
10159       // First, combine the bswap away.  This makes the value produced by the
10160       // load dead.
10161       DCI.CombineTo(N, ResVal);
10162
10163       // Next, combine the load away, we give it a bogus result value but a real
10164       // chain result.  The result value is dead because the bswap is dead.
10165       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10166
10167       // Return N so it doesn't get rechecked!
10168       return SDValue(N, 0);
10169     }
10170
10171     break;
10172   case PPCISD::VCMP: {
10173     // If a VCMPo node already exists with exactly the same operands as this
10174     // node, use its result instead of this node (VCMPo computes both a CR6 and
10175     // a normal output).
10176     //
10177     if (!N->getOperand(0).hasOneUse() &&
10178         !N->getOperand(1).hasOneUse() &&
10179         !N->getOperand(2).hasOneUse()) {
10180
10181       // Scan all of the users of the LHS, looking for VCMPo's that match.
10182       SDNode *VCMPoNode = nullptr;
10183
10184       SDNode *LHSN = N->getOperand(0).getNode();
10185       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10186            UI != E; ++UI)
10187         if (UI->getOpcode() == PPCISD::VCMPo &&
10188             UI->getOperand(1) == N->getOperand(1) &&
10189             UI->getOperand(2) == N->getOperand(2) &&
10190             UI->getOperand(0) == N->getOperand(0)) {
10191           VCMPoNode = *UI;
10192           break;
10193         }
10194
10195       // If there is no VCMPo node, or if the flag value has a single use, don't
10196       // transform this.
10197       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10198         break;
10199
10200       // Look at the (necessarily single) use of the flag value.  If it has a
10201       // chain, this transformation is more complex.  Note that multiple things
10202       // could use the value result, which we should ignore.
10203       SDNode *FlagUser = nullptr;
10204       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10205            FlagUser == nullptr; ++UI) {
10206         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10207         SDNode *User = *UI;
10208         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10209           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10210             FlagUser = User;
10211             break;
10212           }
10213         }
10214       }
10215
10216       // If the user is a MFOCRF instruction, we know this is safe.
10217       // Otherwise we give up for right now.
10218       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10219         return SDValue(VCMPoNode, 0);
10220     }
10221     break;
10222   }
10223   case ISD::BRCOND: {
10224     SDValue Cond = N->getOperand(1);
10225     SDValue Target = N->getOperand(2);
10226  
10227     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10228         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10229           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10230
10231       // We now need to make the intrinsic dead (it cannot be instruction
10232       // selected).
10233       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10234       assert(Cond.getNode()->hasOneUse() &&
10235              "Counter decrement has more than one use");
10236
10237       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10238                          N->getOperand(0), Target);
10239     }
10240   }
10241   break;
10242   case ISD::BR_CC: {
10243     // If this is a branch on an altivec predicate comparison, lower this so
10244     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10245     // lowering is done pre-legalize, because the legalizer lowers the predicate
10246     // compare down to code that is difficult to reassemble.
10247     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10248     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10249
10250     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10251     // value. If so, pass-through the AND to get to the intrinsic.
10252     if (LHS.getOpcode() == ISD::AND &&
10253         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10254         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10255           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10256         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10257         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10258           isZero())
10259       LHS = LHS.getOperand(0);
10260
10261     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10262         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10263           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10264         isa<ConstantSDNode>(RHS)) {
10265       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10266              "Counter decrement comparison is not EQ or NE");
10267
10268       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10269       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10270                     (CC == ISD::SETNE && !Val);
10271
10272       // We now need to make the intrinsic dead (it cannot be instruction
10273       // selected).
10274       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10275       assert(LHS.getNode()->hasOneUse() &&
10276              "Counter decrement has more than one use");
10277
10278       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10279                          N->getOperand(0), N->getOperand(4));
10280     }
10281
10282     int CompareOpc;
10283     bool isDot;
10284
10285     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10286         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10287         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10288       assert(isDot && "Can't compare against a vector result!");
10289
10290       // If this is a comparison against something other than 0/1, then we know
10291       // that the condition is never/always true.
10292       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10293       if (Val != 0 && Val != 1) {
10294         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10295           return N->getOperand(0);
10296         // Always !=, turn it into an unconditional branch.
10297         return DAG.getNode(ISD::BR, dl, MVT::Other,
10298                            N->getOperand(0), N->getOperand(4));
10299       }
10300
10301       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10302
10303       // Create the PPCISD altivec 'dot' comparison node.
10304       SDValue Ops[] = {
10305         LHS.getOperand(2),  // LHS of compare
10306         LHS.getOperand(3),  // RHS of compare
10307         DAG.getConstant(CompareOpc, MVT::i32)
10308       };
10309       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10310       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10311
10312       // Unpack the result based on how the target uses it.
10313       PPC::Predicate CompOpc;
10314       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10315       default:  // Can't happen, don't crash on invalid number though.
10316       case 0:   // Branch on the value of the EQ bit of CR6.
10317         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10318         break;
10319       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10320         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10321         break;
10322       case 2:   // Branch on the value of the LT bit of CR6.
10323         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10324         break;
10325       case 3:   // Branch on the inverted value of the LT bit of CR6.
10326         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10327         break;
10328       }
10329
10330       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10331                          DAG.getConstant(CompOpc, MVT::i32),
10332                          DAG.getRegister(PPC::CR6, MVT::i32),
10333                          N->getOperand(4), CompNode.getValue(1));
10334     }
10335     break;
10336   }
10337   }
10338
10339   return SDValue();
10340 }
10341
10342 SDValue
10343 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10344                                   SelectionDAG &DAG,
10345                                   std::vector<SDNode *> *Created) const {
10346   // fold (sdiv X, pow2)
10347   EVT VT = N->getValueType(0);
10348   if (VT == MVT::i64 && !Subtarget.isPPC64())
10349     return SDValue();
10350   if ((VT != MVT::i32 && VT != MVT::i64) ||
10351       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10352     return SDValue();
10353
10354   SDLoc DL(N);
10355   SDValue N0 = N->getOperand(0);
10356
10357   bool IsNegPow2 = (-Divisor).isPowerOf2();
10358   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10359   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
10360
10361   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10362   if (Created)
10363     Created->push_back(Op.getNode());
10364
10365   if (IsNegPow2) {
10366     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
10367     if (Created)
10368       Created->push_back(Op.getNode());
10369   }
10370
10371   return Op;
10372 }
10373
10374 //===----------------------------------------------------------------------===//
10375 // Inline Assembly Support
10376 //===----------------------------------------------------------------------===//
10377
10378 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10379                                                       APInt &KnownZero,
10380                                                       APInt &KnownOne,
10381                                                       const SelectionDAG &DAG,
10382                                                       unsigned Depth) const {
10383   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10384   switch (Op.getOpcode()) {
10385   default: break;
10386   case PPCISD::LBRX: {
10387     // lhbrx is known to have the top bits cleared out.
10388     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10389       KnownZero = 0xFFFF0000;
10390     break;
10391   }
10392   case ISD::INTRINSIC_WO_CHAIN: {
10393     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10394     default: break;
10395     case Intrinsic::ppc_altivec_vcmpbfp_p:
10396     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10397     case Intrinsic::ppc_altivec_vcmpequb_p:
10398     case Intrinsic::ppc_altivec_vcmpequh_p:
10399     case Intrinsic::ppc_altivec_vcmpequw_p:
10400     case Intrinsic::ppc_altivec_vcmpequd_p:
10401     case Intrinsic::ppc_altivec_vcmpgefp_p:
10402     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10403     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10404     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10405     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10406     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10407     case Intrinsic::ppc_altivec_vcmpgtub_p:
10408     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10409     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10410     case Intrinsic::ppc_altivec_vcmpgtud_p:
10411       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10412       break;
10413     }
10414   }
10415   }
10416 }
10417
10418 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10419   switch (Subtarget.getDarwinDirective()) {
10420   default: break;
10421   case PPC::DIR_970:
10422   case PPC::DIR_PWR4:
10423   case PPC::DIR_PWR5:
10424   case PPC::DIR_PWR5X:
10425   case PPC::DIR_PWR6:
10426   case PPC::DIR_PWR6X:
10427   case PPC::DIR_PWR7:
10428   case PPC::DIR_PWR8: {
10429     if (!ML)
10430       break;
10431
10432     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10433
10434     // For small loops (between 5 and 8 instructions), align to a 32-byte
10435     // boundary so that the entire loop fits in one instruction-cache line.
10436     uint64_t LoopSize = 0;
10437     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10438       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10439         LoopSize += TII->GetInstSizeInBytes(J);
10440
10441     if (LoopSize > 16 && LoopSize <= 32)
10442       return 5;
10443
10444     break;
10445   }
10446   }
10447
10448   return TargetLowering::getPrefLoopAlignment(ML);
10449 }
10450
10451 /// getConstraintType - Given a constraint, return the type of
10452 /// constraint it is for this target.
10453 PPCTargetLowering::ConstraintType
10454 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10455   if (Constraint.size() == 1) {
10456     switch (Constraint[0]) {
10457     default: break;
10458     case 'b':
10459     case 'r':
10460     case 'f':
10461     case 'v':
10462     case 'y':
10463       return C_RegisterClass;
10464     case 'Z':
10465       // FIXME: While Z does indicate a memory constraint, it specifically
10466       // indicates an r+r address (used in conjunction with the 'y' modifier
10467       // in the replacement string). Currently, we're forcing the base
10468       // register to be r0 in the asm printer (which is interpreted as zero)
10469       // and forming the complete address in the second register. This is
10470       // suboptimal.
10471       return C_Memory;
10472     }
10473   } else if (Constraint == "wc") { // individual CR bits.
10474     return C_RegisterClass;
10475   } else if (Constraint == "wa" || Constraint == "wd" ||
10476              Constraint == "wf" || Constraint == "ws") {
10477     return C_RegisterClass; // VSX registers.
10478   }
10479   return TargetLowering::getConstraintType(Constraint);
10480 }
10481
10482 /// Examine constraint type and operand type and determine a weight value.
10483 /// This object must already have been set up with the operand type
10484 /// and the current alternative constraint selected.
10485 TargetLowering::ConstraintWeight
10486 PPCTargetLowering::getSingleConstraintMatchWeight(
10487     AsmOperandInfo &info, const char *constraint) const {
10488   ConstraintWeight weight = CW_Invalid;
10489   Value *CallOperandVal = info.CallOperandVal;
10490     // If we don't have a value, we can't do a match,
10491     // but allow it at the lowest weight.
10492   if (!CallOperandVal)
10493     return CW_Default;
10494   Type *type = CallOperandVal->getType();
10495
10496   // Look at the constraint type.
10497   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10498     return CW_Register; // an individual CR bit.
10499   else if ((StringRef(constraint) == "wa" ||
10500             StringRef(constraint) == "wd" ||
10501             StringRef(constraint) == "wf") &&
10502            type->isVectorTy())
10503     return CW_Register;
10504   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10505     return CW_Register;
10506
10507   switch (*constraint) {
10508   default:
10509     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10510     break;
10511   case 'b':
10512     if (type->isIntegerTy())
10513       weight = CW_Register;
10514     break;
10515   case 'f':
10516     if (type->isFloatTy())
10517       weight = CW_Register;
10518     break;
10519   case 'd':
10520     if (type->isDoubleTy())
10521       weight = CW_Register;
10522     break;
10523   case 'v':
10524     if (type->isVectorTy())
10525       weight = CW_Register;
10526     break;
10527   case 'y':
10528     weight = CW_Register;
10529     break;
10530   case 'Z':
10531     weight = CW_Memory;
10532     break;
10533   }
10534   return weight;
10535 }
10536
10537 std::pair<unsigned, const TargetRegisterClass *>
10538 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10539                                                 const std::string &Constraint,
10540                                                 MVT VT) const {
10541   if (Constraint.size() == 1) {
10542     // GCC RS6000 Constraint Letters
10543     switch (Constraint[0]) {
10544     case 'b':   // R1-R31
10545       if (VT == MVT::i64 && Subtarget.isPPC64())
10546         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10547       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10548     case 'r':   // R0-R31
10549       if (VT == MVT::i64 && Subtarget.isPPC64())
10550         return std::make_pair(0U, &PPC::G8RCRegClass);
10551       return std::make_pair(0U, &PPC::GPRCRegClass);
10552     case 'f':
10553       if (VT == MVT::f32 || VT == MVT::i32)
10554         return std::make_pair(0U, &PPC::F4RCRegClass);
10555       if (VT == MVT::f64 || VT == MVT::i64)
10556         return std::make_pair(0U, &PPC::F8RCRegClass);
10557       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10558         return std::make_pair(0U, &PPC::QFRCRegClass);
10559       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10560         return std::make_pair(0U, &PPC::QSRCRegClass);
10561       break;
10562     case 'v':
10563       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10564         return std::make_pair(0U, &PPC::QFRCRegClass);
10565       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10566         return std::make_pair(0U, &PPC::QSRCRegClass);
10567       return std::make_pair(0U, &PPC::VRRCRegClass);
10568     case 'y':   // crrc
10569       return std::make_pair(0U, &PPC::CRRCRegClass);
10570     }
10571   } else if (Constraint == "wc") { // an individual CR bit.
10572     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10573   } else if (Constraint == "wa" || Constraint == "wd" ||
10574              Constraint == "wf") {
10575     return std::make_pair(0U, &PPC::VSRCRegClass);
10576   } else if (Constraint == "ws") {
10577     return std::make_pair(0U, &PPC::VSFRCRegClass);
10578   }
10579
10580   std::pair<unsigned, const TargetRegisterClass *> R =
10581       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10582
10583   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10584   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10585   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10586   // register.
10587   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10588   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10589   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10590       PPC::GPRCRegClass.contains(R.first))
10591     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10592                             PPC::sub_32, &PPC::G8RCRegClass),
10593                           &PPC::G8RCRegClass);
10594
10595   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10596   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10597     R.first = PPC::CR0;
10598     R.second = &PPC::CRRCRegClass;
10599   }
10600
10601   return R;
10602 }
10603
10604
10605 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10606 /// vector.  If it is invalid, don't add anything to Ops.
10607 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10608                                                      std::string &Constraint,
10609                                                      std::vector<SDValue>&Ops,
10610                                                      SelectionDAG &DAG) const {
10611   SDValue Result;
10612
10613   // Only support length 1 constraints.
10614   if (Constraint.length() > 1) return;
10615
10616   char Letter = Constraint[0];
10617   switch (Letter) {
10618   default: break;
10619   case 'I':
10620   case 'J':
10621   case 'K':
10622   case 'L':
10623   case 'M':
10624   case 'N':
10625   case 'O':
10626   case 'P': {
10627     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10628     if (!CST) return; // Must be an immediate to match.
10629     int64_t Value = CST->getSExtValue();
10630     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10631                          // numbers are printed as such.
10632     switch (Letter) {
10633     default: llvm_unreachable("Unknown constraint letter!");
10634     case 'I':  // "I" is a signed 16-bit constant.
10635       if (isInt<16>(Value))
10636         Result = DAG.getTargetConstant(Value, TCVT);
10637       break;
10638     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10639       if (isShiftedUInt<16, 16>(Value))
10640         Result = DAG.getTargetConstant(Value, TCVT);
10641       break;
10642     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10643       if (isShiftedInt<16, 16>(Value))
10644         Result = DAG.getTargetConstant(Value, TCVT);
10645       break;
10646     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10647       if (isUInt<16>(Value))
10648         Result = DAG.getTargetConstant(Value, TCVT);
10649       break;
10650     case 'M':  // "M" is a constant that is greater than 31.
10651       if (Value > 31)
10652         Result = DAG.getTargetConstant(Value, TCVT);
10653       break;
10654     case 'N':  // "N" is a positive constant that is an exact power of two.
10655       if (Value > 0 && isPowerOf2_64(Value))
10656         Result = DAG.getTargetConstant(Value, TCVT);
10657       break;
10658     case 'O':  // "O" is the constant zero.
10659       if (Value == 0)
10660         Result = DAG.getTargetConstant(Value, TCVT);
10661       break;
10662     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10663       if (isInt<16>(-Value))
10664         Result = DAG.getTargetConstant(Value, TCVT);
10665       break;
10666     }
10667     break;
10668   }
10669   }
10670
10671   if (Result.getNode()) {
10672     Ops.push_back(Result);
10673     return;
10674   }
10675
10676   // Handle standard constraint letters.
10677   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10678 }
10679
10680 // isLegalAddressingMode - Return true if the addressing mode represented
10681 // by AM is legal for this target, for a load/store of the specified type.
10682 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10683                                               Type *Ty) const {
10684   // PPC does not allow r+i addressing modes for vectors!
10685   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10686     return false;
10687
10688   // PPC allows a sign-extended 16-bit immediate field.
10689   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10690     return false;
10691
10692   // No global is ever allowed as a base.
10693   if (AM.BaseGV)
10694     return false;
10695
10696   // PPC only support r+r,
10697   switch (AM.Scale) {
10698   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10699     break;
10700   case 1:
10701     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10702       return false;
10703     // Otherwise we have r+r or r+i.
10704     break;
10705   case 2:
10706     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10707       return false;
10708     // Allow 2*r as r+r.
10709     break;
10710   default:
10711     // No other scales are supported.
10712     return false;
10713   }
10714
10715   return true;
10716 }
10717
10718 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10719                                            SelectionDAG &DAG) const {
10720   MachineFunction &MF = DAG.getMachineFunction();
10721   MachineFrameInfo *MFI = MF.getFrameInfo();
10722   MFI->setReturnAddressIsTaken(true);
10723
10724   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10725     return SDValue();
10726
10727   SDLoc dl(Op);
10728   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10729
10730   // Make sure the function does not optimize away the store of the RA to
10731   // the stack.
10732   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10733   FuncInfo->setLRStoreRequired();
10734   bool isPPC64 = Subtarget.isPPC64();
10735
10736   if (Depth > 0) {
10737     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10738     SDValue Offset =
10739         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(),
10740                         isPPC64 ? MVT::i64 : MVT::i32);
10741     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10742                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10743                                    FrameAddr, Offset),
10744                        MachinePointerInfo(), false, false, false, 0);
10745   }
10746
10747   // Just load the return address off the stack.
10748   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10749   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10750                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10751 }
10752
10753 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10754                                           SelectionDAG &DAG) const {
10755   SDLoc dl(Op);
10756   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10757
10758   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10759   bool isPPC64 = PtrVT == MVT::i64;
10760
10761   MachineFunction &MF = DAG.getMachineFunction();
10762   MachineFrameInfo *MFI = MF.getFrameInfo();
10763   MFI->setFrameAddressIsTaken(true);
10764
10765   // Naked functions never have a frame pointer, and so we use r1. For all
10766   // other functions, this decision must be delayed until during PEI.
10767   unsigned FrameReg;
10768   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10769     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10770   else
10771     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10772
10773   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10774                                          PtrVT);
10775   while (Depth--)
10776     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10777                             FrameAddr, MachinePointerInfo(), false, false,
10778                             false, 0);
10779   return FrameAddr;
10780 }
10781
10782 // FIXME? Maybe this could be a TableGen attribute on some registers and
10783 // this table could be generated automatically from RegInfo.
10784 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10785                                               EVT VT) const {
10786   bool isPPC64 = Subtarget.isPPC64();
10787   bool isDarwinABI = Subtarget.isDarwinABI();
10788
10789   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10790       (!isPPC64 && VT != MVT::i32))
10791     report_fatal_error("Invalid register global variable type");
10792
10793   bool is64Bit = isPPC64 && VT == MVT::i64;
10794   unsigned Reg = StringSwitch<unsigned>(RegName)
10795                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10796                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10797                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10798                                   (is64Bit ? PPC::X13 : PPC::R13))
10799                    .Default(0);
10800
10801   if (Reg)
10802     return Reg;
10803   report_fatal_error("Invalid register name global variable");
10804 }
10805
10806 bool
10807 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10808   // The PowerPC target isn't yet aware of offsets.
10809   return false;
10810 }
10811
10812 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10813                                            const CallInst &I,
10814                                            unsigned Intrinsic) const {
10815
10816   switch (Intrinsic) {
10817   case Intrinsic::ppc_qpx_qvlfd:
10818   case Intrinsic::ppc_qpx_qvlfs:
10819   case Intrinsic::ppc_qpx_qvlfcd:
10820   case Intrinsic::ppc_qpx_qvlfcs:
10821   case Intrinsic::ppc_qpx_qvlfiwa:
10822   case Intrinsic::ppc_qpx_qvlfiwz:
10823   case Intrinsic::ppc_altivec_lvx:
10824   case Intrinsic::ppc_altivec_lvxl:
10825   case Intrinsic::ppc_altivec_lvebx:
10826   case Intrinsic::ppc_altivec_lvehx:
10827   case Intrinsic::ppc_altivec_lvewx:
10828   case Intrinsic::ppc_vsx_lxvd2x:
10829   case Intrinsic::ppc_vsx_lxvw4x: {
10830     EVT VT;
10831     switch (Intrinsic) {
10832     case Intrinsic::ppc_altivec_lvebx:
10833       VT = MVT::i8;
10834       break;
10835     case Intrinsic::ppc_altivec_lvehx:
10836       VT = MVT::i16;
10837       break;
10838     case Intrinsic::ppc_altivec_lvewx:
10839       VT = MVT::i32;
10840       break;
10841     case Intrinsic::ppc_vsx_lxvd2x:
10842       VT = MVT::v2f64;
10843       break;
10844     case Intrinsic::ppc_qpx_qvlfd:
10845       VT = MVT::v4f64;
10846       break;
10847     case Intrinsic::ppc_qpx_qvlfs:
10848       VT = MVT::v4f32;
10849       break;
10850     case Intrinsic::ppc_qpx_qvlfcd:
10851       VT = MVT::v2f64;
10852       break;
10853     case Intrinsic::ppc_qpx_qvlfcs:
10854       VT = MVT::v2f32;
10855       break;
10856     default:
10857       VT = MVT::v4i32;
10858       break;
10859     }
10860
10861     Info.opc = ISD::INTRINSIC_W_CHAIN;
10862     Info.memVT = VT;
10863     Info.ptrVal = I.getArgOperand(0);
10864     Info.offset = -VT.getStoreSize()+1;
10865     Info.size = 2*VT.getStoreSize()-1;
10866     Info.align = 1;
10867     Info.vol = false;
10868     Info.readMem = true;
10869     Info.writeMem = false;
10870     return true;
10871   }
10872   case Intrinsic::ppc_qpx_qvlfda:
10873   case Intrinsic::ppc_qpx_qvlfsa:
10874   case Intrinsic::ppc_qpx_qvlfcda:
10875   case Intrinsic::ppc_qpx_qvlfcsa:
10876   case Intrinsic::ppc_qpx_qvlfiwaa:
10877   case Intrinsic::ppc_qpx_qvlfiwza: {
10878     EVT VT;
10879     switch (Intrinsic) {
10880     case Intrinsic::ppc_qpx_qvlfda:
10881       VT = MVT::v4f64;
10882       break;
10883     case Intrinsic::ppc_qpx_qvlfsa:
10884       VT = MVT::v4f32;
10885       break;
10886     case Intrinsic::ppc_qpx_qvlfcda:
10887       VT = MVT::v2f64;
10888       break;
10889     case Intrinsic::ppc_qpx_qvlfcsa:
10890       VT = MVT::v2f32;
10891       break;
10892     default:
10893       VT = MVT::v4i32;
10894       break;
10895     }
10896
10897     Info.opc = ISD::INTRINSIC_W_CHAIN;
10898     Info.memVT = VT;
10899     Info.ptrVal = I.getArgOperand(0);
10900     Info.offset = 0;
10901     Info.size = VT.getStoreSize();
10902     Info.align = 1;
10903     Info.vol = false;
10904     Info.readMem = true;
10905     Info.writeMem = false;
10906     return true;
10907   }
10908   case Intrinsic::ppc_qpx_qvstfd:
10909   case Intrinsic::ppc_qpx_qvstfs:
10910   case Intrinsic::ppc_qpx_qvstfcd:
10911   case Intrinsic::ppc_qpx_qvstfcs:
10912   case Intrinsic::ppc_qpx_qvstfiw:
10913   case Intrinsic::ppc_altivec_stvx:
10914   case Intrinsic::ppc_altivec_stvxl:
10915   case Intrinsic::ppc_altivec_stvebx:
10916   case Intrinsic::ppc_altivec_stvehx:
10917   case Intrinsic::ppc_altivec_stvewx:
10918   case Intrinsic::ppc_vsx_stxvd2x:
10919   case Intrinsic::ppc_vsx_stxvw4x: {
10920     EVT VT;
10921     switch (Intrinsic) {
10922     case Intrinsic::ppc_altivec_stvebx:
10923       VT = MVT::i8;
10924       break;
10925     case Intrinsic::ppc_altivec_stvehx:
10926       VT = MVT::i16;
10927       break;
10928     case Intrinsic::ppc_altivec_stvewx:
10929       VT = MVT::i32;
10930       break;
10931     case Intrinsic::ppc_vsx_stxvd2x:
10932       VT = MVT::v2f64;
10933       break;
10934     case Intrinsic::ppc_qpx_qvstfd:
10935       VT = MVT::v4f64;
10936       break;
10937     case Intrinsic::ppc_qpx_qvstfs:
10938       VT = MVT::v4f32;
10939       break;
10940     case Intrinsic::ppc_qpx_qvstfcd:
10941       VT = MVT::v2f64;
10942       break;
10943     case Intrinsic::ppc_qpx_qvstfcs:
10944       VT = MVT::v2f32;
10945       break;
10946     default:
10947       VT = MVT::v4i32;
10948       break;
10949     }
10950
10951     Info.opc = ISD::INTRINSIC_VOID;
10952     Info.memVT = VT;
10953     Info.ptrVal = I.getArgOperand(1);
10954     Info.offset = -VT.getStoreSize()+1;
10955     Info.size = 2*VT.getStoreSize()-1;
10956     Info.align = 1;
10957     Info.vol = false;
10958     Info.readMem = false;
10959     Info.writeMem = true;
10960     return true;
10961   }
10962   case Intrinsic::ppc_qpx_qvstfda:
10963   case Intrinsic::ppc_qpx_qvstfsa:
10964   case Intrinsic::ppc_qpx_qvstfcda:
10965   case Intrinsic::ppc_qpx_qvstfcsa:
10966   case Intrinsic::ppc_qpx_qvstfiwa: {
10967     EVT VT;
10968     switch (Intrinsic) {
10969     case Intrinsic::ppc_qpx_qvstfda:
10970       VT = MVT::v4f64;
10971       break;
10972     case Intrinsic::ppc_qpx_qvstfsa:
10973       VT = MVT::v4f32;
10974       break;
10975     case Intrinsic::ppc_qpx_qvstfcda:
10976       VT = MVT::v2f64;
10977       break;
10978     case Intrinsic::ppc_qpx_qvstfcsa:
10979       VT = MVT::v2f32;
10980       break;
10981     default:
10982       VT = MVT::v4i32;
10983       break;
10984     }
10985
10986     Info.opc = ISD::INTRINSIC_VOID;
10987     Info.memVT = VT;
10988     Info.ptrVal = I.getArgOperand(1);
10989     Info.offset = 0;
10990     Info.size = VT.getStoreSize();
10991     Info.align = 1;
10992     Info.vol = false;
10993     Info.readMem = false;
10994     Info.writeMem = true;
10995     return true;
10996   }
10997   default:
10998     break;
10999   }
11000
11001   return false;
11002 }
11003
11004 /// getOptimalMemOpType - Returns the target specific optimal type for load
11005 /// and store operations as a result of memset, memcpy, and memmove
11006 /// lowering. If DstAlign is zero that means it's safe to destination
11007 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11008 /// means there isn't a need to check it against alignment requirement,
11009 /// probably because the source does not need to be loaded. If 'IsMemset' is
11010 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11011 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11012 /// source is constant so it does not need to be loaded.
11013 /// It returns EVT::Other if the type should be determined using generic
11014 /// target-independent logic.
11015 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11016                                            unsigned DstAlign, unsigned SrcAlign,
11017                                            bool IsMemset, bool ZeroMemset,
11018                                            bool MemcpyStrSrc,
11019                                            MachineFunction &MF) const {
11020   const Function *F = MF.getFunction();
11021   // When expanding a memset, require at least two QPX instructions to cover
11022   // the cost of loading the value to be stored from the constant pool.
11023   if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11024      (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11025       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11026     return MVT::v4f64;
11027   }
11028
11029   // We should use Altivec/VSX loads and stores when available. For unaligned
11030   // addresses, unaligned VSX loads are only fast starting with the P8.
11031   if (Subtarget.hasAltivec() && Size >= 16 &&
11032       (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11033        ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11034     return MVT::v4i32;
11035
11036   if (Subtarget.isPPC64()) {
11037     return MVT::i64;
11038   }
11039
11040   return MVT::i32;
11041 }
11042
11043 /// \brief Returns true if it is beneficial to convert a load of a constant
11044 /// to just the constant itself.
11045 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11046                                                           Type *Ty) const {
11047   assert(Ty->isIntegerTy());
11048
11049   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11050   if (BitSize == 0 || BitSize > 64)
11051     return false;
11052   return true;
11053 }
11054
11055 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11056   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11057     return false;
11058   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11059   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11060   return NumBits1 == 64 && NumBits2 == 32;
11061 }
11062
11063 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11064   if (!VT1.isInteger() || !VT2.isInteger())
11065     return false;
11066   unsigned NumBits1 = VT1.getSizeInBits();
11067   unsigned NumBits2 = VT2.getSizeInBits();
11068   return NumBits1 == 64 && NumBits2 == 32;
11069 }
11070
11071 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11072   // Generally speaking, zexts are not free, but they are free when they can be
11073   // folded with other operations.
11074   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11075     EVT MemVT = LD->getMemoryVT();
11076     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11077          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11078         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11079          LD->getExtensionType() == ISD::ZEXTLOAD))
11080       return true;
11081   }
11082
11083   // FIXME: Add other cases...
11084   //  - 32-bit shifts with a zext to i64
11085   //  - zext after ctlz, bswap, etc.
11086   //  - zext after and by a constant mask
11087
11088   return TargetLowering::isZExtFree(Val, VT2);
11089 }
11090
11091 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11092   assert(VT.isFloatingPoint());
11093   return true;
11094 }
11095
11096 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11097   return isInt<16>(Imm) || isUInt<16>(Imm);
11098 }
11099
11100 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11101   return isInt<16>(Imm) || isUInt<16>(Imm);
11102 }
11103
11104 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11105                                                        unsigned,
11106                                                        unsigned,
11107                                                        bool *Fast) const {
11108   if (DisablePPCUnaligned)
11109     return false;
11110
11111   // PowerPC supports unaligned memory access for simple non-vector types.
11112   // Although accessing unaligned addresses is not as efficient as accessing
11113   // aligned addresses, it is generally more efficient than manual expansion,
11114   // and generally only traps for software emulation when crossing page
11115   // boundaries.
11116
11117   if (!VT.isSimple())
11118     return false;
11119
11120   if (VT.getSimpleVT().isVector()) {
11121     if (Subtarget.hasVSX()) {
11122       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11123           VT != MVT::v4f32 && VT != MVT::v4i32)
11124         return false;
11125     } else {
11126       return false;
11127     }
11128   }
11129
11130   if (VT == MVT::ppcf128)
11131     return false;
11132
11133   if (Fast)
11134     *Fast = true;
11135
11136   return true;
11137 }
11138
11139 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11140   VT = VT.getScalarType();
11141
11142   if (!VT.isSimple())
11143     return false;
11144
11145   switch (VT.getSimpleVT().SimpleTy) {
11146   case MVT::f32:
11147   case MVT::f64:
11148     return true;
11149   default:
11150     break;
11151   }
11152
11153   return false;
11154 }
11155
11156 const MCPhysReg *
11157 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11158   // LR is a callee-save register, but we must treat it as clobbered by any call
11159   // site. Hence we include LR in the scratch registers, which are in turn added
11160   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11161   // to CTR, which is used by any indirect call.
11162   static const MCPhysReg ScratchRegs[] = {
11163     PPC::X12, PPC::LR8, PPC::CTR8, 0
11164   };
11165
11166   return ScratchRegs;
11167 }
11168
11169 bool
11170 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11171                      EVT VT , unsigned DefinedValues) const {
11172   if (VT == MVT::v2i64)
11173     return false;
11174
11175   if (Subtarget.hasQPX()) {
11176     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11177       return true;
11178   }
11179
11180   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11181 }
11182
11183 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11184   if (DisableILPPref || Subtarget.enableMachineScheduler())
11185     return TargetLowering::getSchedulingPreference(N);
11186
11187   return Sched::ILP;
11188 }
11189
11190 // Create a fast isel object.
11191 FastISel *
11192 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11193                                   const TargetLibraryInfo *LibInfo) const {
11194   return PPC::createFastISel(FuncInfo, LibInfo);
11195 }