]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Use the new insecure-lan-zones option instead of listing each AS112 zone
[FreeBSD/FreeBSD.git] / contrib / llvm / 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
43 using namespace llvm;
44
45 // FIXME: Remove this once soft-float is supported.
46 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
47 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
48
49 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
50 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
51
52 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
53 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
54
55 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
56 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
57
58 // FIXME: Remove this once the bug has been fixed!
59 extern cl::opt<bool> ANDIGlueBug;
60
61 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
62                                      const PPCSubtarget &STI)
63     : TargetLowering(TM), Subtarget(STI) {
64   // Use _setjmp/_longjmp instead of setjmp/longjmp.
65   setUseUnderscoreSetJmp(true);
66   setUseUnderscoreLongJmp(true);
67
68   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
69   // arguments are at least 4/8 bytes aligned.
70   bool isPPC64 = Subtarget.isPPC64();
71   setMinStackArgumentAlignment(isPPC64 ? 8:4);
72
73   // Set up the register classes.
74   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
75   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
76   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
77
78   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
79   for (MVT VT : MVT::integer_valuetypes()) {
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
81     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
82   }
83
84   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
85
86   // PowerPC has pre-inc load and store's.
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
100   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
101
102   if (Subtarget.useCRBits()) {
103     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
104
105     if (isPPC64 || Subtarget.hasFPCVT()) {
106       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
107       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
108                          isPPC64 ? MVT::i64 : MVT::i32);
109       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
110       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
111                          isPPC64 ? MVT::i64 : MVT::i32);
112     } else {
113       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
114       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115     }
116
117     // PowerPC does not support direct load / store of condition registers
118     setOperationAction(ISD::LOAD, MVT::i1, Custom);
119     setOperationAction(ISD::STORE, MVT::i1, Custom);
120
121     // FIXME: Remove this once the ANDI glue bug is fixed:
122     if (ANDIGlueBug)
123       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
124
125     for (MVT VT : MVT::integer_valuetypes()) {
126       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
127       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
128       setTruncStoreAction(VT, MVT::i1, Expand);
129     }
130
131     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
132   }
133
134   // This is used in the ppcf128->int sequence.  Note it has different semantics
135   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
136   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137
138   // We do not currently implement these libm ops for PowerPC.
139   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
140   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
141   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
142   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
143   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
144   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145
146   // PowerPC has no SREM/UREM instructions
147   setOperationAction(ISD::SREM, MVT::i32, Expand);
148   setOperationAction(ISD::UREM, MVT::i32, Expand);
149   setOperationAction(ISD::SREM, MVT::i64, Expand);
150   setOperationAction(ISD::UREM, MVT::i64, Expand);
151
152   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
153   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
157   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
159   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
160   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161
162   // We don't support sin/cos/sqrt/fmod/pow
163   setOperationAction(ISD::FSIN , MVT::f64, Expand);
164   setOperationAction(ISD::FCOS , MVT::f64, Expand);
165   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
166   setOperationAction(ISD::FREM , MVT::f64, Expand);
167   setOperationAction(ISD::FPOW , MVT::f64, Expand);
168   setOperationAction(ISD::FMA  , MVT::f64, Legal);
169   setOperationAction(ISD::FSIN , MVT::f32, Expand);
170   setOperationAction(ISD::FCOS , MVT::f32, Expand);
171   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
172   setOperationAction(ISD::FREM , MVT::f32, Expand);
173   setOperationAction(ISD::FPOW , MVT::f32, Expand);
174   setOperationAction(ISD::FMA  , MVT::f32, Legal);
175
176   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177
178   // If we're enabling GP optimizations, use hardware square root
179   if (!Subtarget.hasFSQRT() &&
180       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
181         Subtarget.hasFRE()))
182     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183
184   if (!Subtarget.hasFSQRT() &&
185       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
186         Subtarget.hasFRES()))
187     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188
189   if (Subtarget.hasFCPSGN()) {
190     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
191     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192   } else {
193     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
195   }
196
197   if (Subtarget.hasFPRND()) {
198     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
199     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
200     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
201     setOperationAction(ISD::FROUND, MVT::f64, Legal);
202
203     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
204     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
205     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
206     setOperationAction(ISD::FROUND, MVT::f32, Legal);
207   }
208
209   // PowerPC does not have BSWAP, CTPOP or CTTZ
210   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
212   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
214   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
216   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
217   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218
219   if (Subtarget.hasPOPCNTD()) {
220     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
221     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
222   } else {
223     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
224     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
225   }
226
227   // PowerPC does not have ROTR
228   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
229   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
230
231   if (!Subtarget.useCRBits()) {
232     // PowerPC does not have Select
233     setOperationAction(ISD::SELECT, MVT::i32, Expand);
234     setOperationAction(ISD::SELECT, MVT::i64, Expand);
235     setOperationAction(ISD::SELECT, MVT::f32, Expand);
236     setOperationAction(ISD::SELECT, MVT::f64, Expand);
237   }
238
239   // PowerPC wants to turn select_cc of FP into fsel when possible.
240   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242
243   // PowerPC wants to optimize integer setcc a bit
244   if (!Subtarget.useCRBits())
245     setOperationAction(ISD::SETCC, MVT::i32, Custom);
246
247   // PowerPC does not have BRCOND which requires SetCC
248   if (!Subtarget.useCRBits())
249     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250
251   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
252
253   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
254   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255
256   // PowerPC does not have [U|S]INT_TO_FP
257   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
258   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259
260   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
262   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
263   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264
265   // We cannot sextinreg(i1).  Expand to shifts.
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267
268   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
269   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
270   // support continuation, user-level threading, and etc.. As a result, no
271   // other SjLj exception interfaces are implemented and please don't build
272   // your own exception handling based on them.
273   // LLVM/Clang supports zero-cost DWARF exception handling.
274   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
275   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276
277   // We want to legalize GlobalAddress and ConstantPool nodes into the
278   // appropriate instructions to materialize the address.
279   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
280   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
281   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
282   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
283   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
284   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
285   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
287   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
288   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
289
290   // TRAP is legal.
291   setOperationAction(ISD::TRAP, MVT::Other, Legal);
292
293   // TRAMPOLINE is custom lowered.
294   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
295   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296
297   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
299
300   if (Subtarget.isSVR4ABI()) {
301     if (isPPC64) {
302       // VAARG always uses double-word chunks, so promote anything smaller.
303       setOperationAction(ISD::VAARG, MVT::i1, Promote);
304       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
305       setOperationAction(ISD::VAARG, MVT::i8, Promote);
306       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
307       setOperationAction(ISD::VAARG, MVT::i16, Promote);
308       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
309       setOperationAction(ISD::VAARG, MVT::i32, Promote);
310       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
311       setOperationAction(ISD::VAARG, MVT::Other, Expand);
312     } else {
313       // VAARG is custom lowered with the 32-bit SVR4 ABI.
314       setOperationAction(ISD::VAARG, MVT::Other, Custom);
315       setOperationAction(ISD::VAARG, MVT::i64, Custom);
316     }
317   } else
318     setOperationAction(ISD::VAARG, MVT::Other, Expand);
319
320   if (Subtarget.isSVR4ABI() && !isPPC64)
321     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
322     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
323   else
324     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
325
326   // Use the default implementation.
327   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
328   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
329   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
331   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
332
333   // We want to custom lower some of our intrinsics.
334   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335
336   // To handle counter-based loop conditions.
337   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338
339   // Comparisons that require checking two conditions.
340   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
341   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
343   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
345   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
347   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
349   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
351   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352
353   if (Subtarget.has64BitSupport()) {
354     // They also have instructions for converting between i64 and fp.
355     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
356     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
357     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
358     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
359     // This is just the low 32 bits of a (signed) fp->i64 conversion.
360     // We cannot do this with Promote because i64 is not a legal type.
361     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362
363     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
364       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365   } else {
366     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
367     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
368   }
369
370   // With the instructions enabled under FPCVT, we can do everything.
371   if (Subtarget.hasFPCVT()) {
372     if (Subtarget.has64BitSupport()) {
373       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
374       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
375       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
376       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
377     }
378
379     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
383   }
384
385   if (Subtarget.use64BitRegs()) {
386     // 64-bit PowerPC implementations can support i64 types directly
387     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
388     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
389     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
390     // 64-bit PowerPC wants to expand i128 shifts itself.
391     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
393     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394   } else {
395     // 32-bit PowerPC wants to expand i64 shifts itself.
396     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
398     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
399   }
400
401   if (Subtarget.hasAltivec()) {
402     // First set operation action for all vector types to expand. Then we
403     // will selectively turn on ones that can be effectively codegen'd.
404     for (MVT VT : MVT::vector_valuetypes()) {
405       // add/sub are legal for all supported vector VT's.
406       setOperationAction(ISD::ADD , VT, Legal);
407       setOperationAction(ISD::SUB , VT, Legal);
408       
409       // Vector instructions introduced in P8
410       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
411         setOperationAction(ISD::CTPOP, VT, Legal);
412         setOperationAction(ISD::CTLZ, VT, Legal);
413       }
414       else {
415         setOperationAction(ISD::CTPOP, VT, Expand);
416         setOperationAction(ISD::CTLZ, VT, Expand);
417       }
418
419       // We promote all shuffles to v16i8.
420       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
421       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
422
423       // We promote all non-typed operations to v4i32.
424       setOperationAction(ISD::AND   , VT, Promote);
425       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
426       setOperationAction(ISD::OR    , VT, Promote);
427       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
428       setOperationAction(ISD::XOR   , VT, Promote);
429       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
430       setOperationAction(ISD::LOAD  , VT, Promote);
431       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
432       setOperationAction(ISD::SELECT, VT, Promote);
433       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
434       setOperationAction(ISD::SELECT_CC, VT, Promote);
435       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
436       setOperationAction(ISD::STORE, VT, Promote);
437       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
438
439       // No other operations are legal.
440       setOperationAction(ISD::MUL , VT, Expand);
441       setOperationAction(ISD::SDIV, VT, Expand);
442       setOperationAction(ISD::SREM, VT, Expand);
443       setOperationAction(ISD::UDIV, VT, Expand);
444       setOperationAction(ISD::UREM, VT, Expand);
445       setOperationAction(ISD::FDIV, VT, Expand);
446       setOperationAction(ISD::FREM, VT, Expand);
447       setOperationAction(ISD::FNEG, VT, Expand);
448       setOperationAction(ISD::FSQRT, VT, Expand);
449       setOperationAction(ISD::FLOG, VT, Expand);
450       setOperationAction(ISD::FLOG10, VT, Expand);
451       setOperationAction(ISD::FLOG2, VT, Expand);
452       setOperationAction(ISD::FEXP, VT, Expand);
453       setOperationAction(ISD::FEXP2, VT, Expand);
454       setOperationAction(ISD::FSIN, VT, Expand);
455       setOperationAction(ISD::FCOS, VT, Expand);
456       setOperationAction(ISD::FABS, VT, Expand);
457       setOperationAction(ISD::FPOWI, VT, Expand);
458       setOperationAction(ISD::FFLOOR, VT, Expand);
459       setOperationAction(ISD::FCEIL,  VT, Expand);
460       setOperationAction(ISD::FTRUNC, VT, Expand);
461       setOperationAction(ISD::FRINT,  VT, Expand);
462       setOperationAction(ISD::FNEARBYINT, VT, Expand);
463       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
464       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
465       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
466       setOperationAction(ISD::MULHU, VT, Expand);
467       setOperationAction(ISD::MULHS, VT, Expand);
468       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
469       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
470       setOperationAction(ISD::UDIVREM, VT, Expand);
471       setOperationAction(ISD::SDIVREM, VT, Expand);
472       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
473       setOperationAction(ISD::FPOW, VT, Expand);
474       setOperationAction(ISD::BSWAP, VT, Expand);
475       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
476       setOperationAction(ISD::CTTZ, VT, Expand);
477       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
478       setOperationAction(ISD::VSELECT, VT, Expand);
479       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
480
481       for (MVT InnerVT : MVT::vector_valuetypes()) {
482         setTruncStoreAction(VT, InnerVT, Expand);
483         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
484         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
485         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
486       }
487     }
488
489     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
490     // with merges, splats, etc.
491     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
492
493     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
494     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
495     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
496     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
497     setOperationAction(ISD::SELECT, MVT::v4i32,
498                        Subtarget.useCRBits() ? Legal : Expand);
499     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
500     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
501     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
502     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
503     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
504     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
505     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
506     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
507     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
508
509     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
510     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
511     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
512     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
513
514     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
515     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
516
517     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
518       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
519       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
520     }
521
522     
523     if (Subtarget.hasP8Altivec()) 
524       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
525     else
526       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527       
528     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
529     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
530
531     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
532     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
533
534     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
535     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
536     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
537     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
538
539     // Altivec does not contain unordered floating-point compare instructions
540     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
541     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
542     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
543     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
544
545     if (Subtarget.hasVSX()) {
546       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
547       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
548
549       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
550       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
551       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
552       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
553       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
554
555       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
556
557       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
558       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
559
560       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
561       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
562
563       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
564       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
565       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
566       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
567       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
568
569       // Share the Altivec comparison restrictions.
570       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
571       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
572       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
573       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
574
575       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
576       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
577
578       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
579
580       if (Subtarget.hasP8Vector())
581         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
582
583       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
584
585       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
586       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
587       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
588
589       if (Subtarget.hasP8Altivec()) {
590         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
591         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
592         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
593
594         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
595       }
596       else {
597         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
598         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
599         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
600
601         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
602
603         // VSX v2i64 only supports non-arithmetic operations.
604         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
605         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
606       }
607
608       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
609       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
610       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
611       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
612
613       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
614
615       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
616       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
617       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
618       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
619
620       // Vector operation legalization checks the result type of
621       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
622       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
623       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
624       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
625       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
626
627       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
628     }
629
630     if (Subtarget.hasP8Altivec()) {
631       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
632       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
633     }
634   }
635
636   if (Subtarget.hasQPX()) {
637     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
638     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
639     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
640     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
641
642     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
643     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
644
645     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
646     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
647
648     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
649     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
650
651     if (!Subtarget.useCRBits())
652       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
653     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
654
655     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
656     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
657     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
658     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
659     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
660     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
661     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
662
663     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
664     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
665
666     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
667     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
668     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
669
670     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
671     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
672     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
673     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
674     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
675     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
676     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
677     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
678     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
679     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
680     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
681
682     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
683     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
684
685     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
686     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
687
688     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
689
690     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
691     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
692     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
693     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
694
695     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
696     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
697
698     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
699     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
700
701     if (!Subtarget.useCRBits())
702       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
703     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
704
705     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
706     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
707     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
708     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
709     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
710     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
711     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
712
713     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
714     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
715
716     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
717     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
718     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
719     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
720     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
721     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
722     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
723     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
724     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
725     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
726     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
727
728     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
729     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
730
731     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
732     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
733
734     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
735
736     setOperationAction(ISD::AND , MVT::v4i1, Legal);
737     setOperationAction(ISD::OR , MVT::v4i1, Legal);
738     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
739
740     if (!Subtarget.useCRBits())
741       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
742     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
743
744     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
745     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
746
747     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
748     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
749     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
750     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
751     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
752     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
753     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
754
755     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
756     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
757
758     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
759
760     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
761     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
762     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
763     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
764
765     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
766     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
767     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
768     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
769
770     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
771     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
772
773     // These need to set FE_INEXACT, and so cannot be vectorized here.
774     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
775     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
776
777     if (TM.Options.UnsafeFPMath) {
778       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
779       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
780
781       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
782       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
783     } else {
784       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
785       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
786
787       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
788       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
789     }
790   }
791
792   if (Subtarget.has64BitSupport())
793     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
794
795   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
796
797   if (!isPPC64) {
798     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
799     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
800   }
801
802   setBooleanContents(ZeroOrOneBooleanContent);
803
804   if (Subtarget.hasAltivec()) {
805     // Altivec instructions set fields to all zeros or all ones.
806     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
807   }
808
809   if (!isPPC64) {
810     // These libcalls are not available in 32-bit.
811     setLibcallName(RTLIB::SHL_I128, nullptr);
812     setLibcallName(RTLIB::SRL_I128, nullptr);
813     setLibcallName(RTLIB::SRA_I128, nullptr);
814   }
815
816   if (isPPC64) {
817     setStackPointerRegisterToSaveRestore(PPC::X1);
818     setExceptionPointerRegister(PPC::X3);
819     setExceptionSelectorRegister(PPC::X4);
820   } else {
821     setStackPointerRegisterToSaveRestore(PPC::R1);
822     setExceptionPointerRegister(PPC::R3);
823     setExceptionSelectorRegister(PPC::R4);
824   }
825
826   // We have target-specific dag combine patterns for the following nodes:
827   setTargetDAGCombine(ISD::SINT_TO_FP);
828   if (Subtarget.hasFPCVT())
829     setTargetDAGCombine(ISD::UINT_TO_FP);
830   setTargetDAGCombine(ISD::LOAD);
831   setTargetDAGCombine(ISD::STORE);
832   setTargetDAGCombine(ISD::BR_CC);
833   if (Subtarget.useCRBits())
834     setTargetDAGCombine(ISD::BRCOND);
835   setTargetDAGCombine(ISD::BSWAP);
836   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
837   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
838   setTargetDAGCombine(ISD::INTRINSIC_VOID);
839
840   setTargetDAGCombine(ISD::SIGN_EXTEND);
841   setTargetDAGCombine(ISD::ZERO_EXTEND);
842   setTargetDAGCombine(ISD::ANY_EXTEND);
843
844   if (Subtarget.useCRBits()) {
845     setTargetDAGCombine(ISD::TRUNCATE);
846     setTargetDAGCombine(ISD::SETCC);
847     setTargetDAGCombine(ISD::SELECT_CC);
848   }
849
850   // Use reciprocal estimates.
851   if (TM.Options.UnsafeFPMath) {
852     setTargetDAGCombine(ISD::FDIV);
853     setTargetDAGCombine(ISD::FSQRT);
854   }
855
856   // Darwin long double math library functions have $LDBL128 appended.
857   if (Subtarget.isDarwin()) {
858     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
859     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
860     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
861     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
862     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
863     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
864     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
865     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
866     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
867     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
868   }
869
870   // With 32 condition bits, we don't need to sink (and duplicate) compares
871   // aggressively in CodeGenPrep.
872   if (Subtarget.useCRBits()) {
873     setHasMultipleConditionRegisters();
874     setJumpIsExpensive();
875   }
876
877   setMinFunctionAlignment(2);
878   if (Subtarget.isDarwin())
879     setPrefFunctionAlignment(4);
880
881   switch (Subtarget.getDarwinDirective()) {
882   default: break;
883   case PPC::DIR_970:
884   case PPC::DIR_A2:
885   case PPC::DIR_E500mc:
886   case PPC::DIR_E5500:
887   case PPC::DIR_PWR4:
888   case PPC::DIR_PWR5:
889   case PPC::DIR_PWR5X:
890   case PPC::DIR_PWR6:
891   case PPC::DIR_PWR6X:
892   case PPC::DIR_PWR7:
893   case PPC::DIR_PWR8:
894     setPrefFunctionAlignment(4);
895     setPrefLoopAlignment(4);
896     break;
897   }
898
899   setInsertFencesForAtomic(true);
900
901   if (Subtarget.enableMachineScheduler())
902     setSchedulingPreference(Sched::Source);
903   else
904     setSchedulingPreference(Sched::Hybrid);
905
906   computeRegisterProperties(STI.getRegisterInfo());
907
908   // The Freescale cores do better with aggressive inlining of memcpy and
909   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
910   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
911       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
912     MaxStoresPerMemset = 32;
913     MaxStoresPerMemsetOptSize = 16;
914     MaxStoresPerMemcpy = 32;
915     MaxStoresPerMemcpyOptSize = 8;
916     MaxStoresPerMemmove = 32;
917     MaxStoresPerMemmoveOptSize = 8;
918   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
919     // The A2 also benefits from (very) aggressive inlining of memcpy and
920     // friends. The overhead of a the function call, even when warm, can be
921     // over one hundred cycles.
922     MaxStoresPerMemset = 128;
923     MaxStoresPerMemcpy = 128;
924     MaxStoresPerMemmove = 128;
925   }
926 }
927
928 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
929 /// the desired ByVal argument alignment.
930 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
931                              unsigned MaxMaxAlign) {
932   if (MaxAlign == MaxMaxAlign)
933     return;
934   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
935     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
936       MaxAlign = 32;
937     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
938       MaxAlign = 16;
939   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
940     unsigned EltAlign = 0;
941     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
942     if (EltAlign > MaxAlign)
943       MaxAlign = EltAlign;
944   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
945     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
946       unsigned EltAlign = 0;
947       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
948       if (EltAlign > MaxAlign)
949         MaxAlign = EltAlign;
950       if (MaxAlign == MaxMaxAlign)
951         break;
952     }
953   }
954 }
955
956 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
957 /// function arguments in the caller parameter area.
958 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
959                                                   const DataLayout &DL) const {
960   // Darwin passes everything on 4 byte boundary.
961   if (Subtarget.isDarwin())
962     return 4;
963
964   // 16byte and wider vectors are passed on 16byte boundary.
965   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
966   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
967   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
968     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
969   return Align;
970 }
971
972 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
973   switch ((PPCISD::NodeType)Opcode) {
974   case PPCISD::FIRST_NUMBER:    break;
975   case PPCISD::FSEL:            return "PPCISD::FSEL";
976   case PPCISD::FCFID:           return "PPCISD::FCFID";
977   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
978   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
979   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
980   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
981   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
982   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
983   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
984   case PPCISD::FRE:             return "PPCISD::FRE";
985   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
986   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
987   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
988   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
989   case PPCISD::VPERM:           return "PPCISD::VPERM";
990   case PPCISD::CMPB:            return "PPCISD::CMPB";
991   case PPCISD::Hi:              return "PPCISD::Hi";
992   case PPCISD::Lo:              return "PPCISD::Lo";
993   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
994   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
995   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
996   case PPCISD::SRL:             return "PPCISD::SRL";
997   case PPCISD::SRA:             return "PPCISD::SRA";
998   case PPCISD::SHL:             return "PPCISD::SHL";
999   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1000   case PPCISD::CALL:            return "PPCISD::CALL";
1001   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1002   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1003   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1004   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1005   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1006   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1007   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1008   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1009   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1010   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1011   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1012   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1013   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1014   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1015   case PPCISD::VCMP:            return "PPCISD::VCMP";
1016   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1017   case PPCISD::LBRX:            return "PPCISD::LBRX";
1018   case PPCISD::STBRX:           return "PPCISD::STBRX";
1019   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1020   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1021   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1022   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1023   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1024   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1025   case PPCISD::BDZ:             return "PPCISD::BDZ";
1026   case PPCISD::MFFS:            return "PPCISD::MFFS";
1027   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1028   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1029   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1030   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1031   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1032   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1033   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1034   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1035   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1036   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1037   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1038   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1039   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1040   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1041   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1042   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1043   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1044   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1045   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1046   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1047   case PPCISD::SC:              return "PPCISD::SC";
1048   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1049   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1050   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1051   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1052   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1053   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1054   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1055   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1056   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1057   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1058   }
1059   return nullptr;
1060 }
1061
1062 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1063                                           EVT VT) const {
1064   if (!VT.isVector())
1065     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1066
1067   if (Subtarget.hasQPX())
1068     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1069
1070   return VT.changeVectorElementTypeToInteger();
1071 }
1072
1073 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1074   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1075   return true;
1076 }
1077
1078 //===----------------------------------------------------------------------===//
1079 // Node matching predicates, for use by the tblgen matching code.
1080 //===----------------------------------------------------------------------===//
1081
1082 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1083 static bool isFloatingPointZero(SDValue Op) {
1084   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1085     return CFP->getValueAPF().isZero();
1086   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1087     // Maybe this has already been legalized into the constant pool?
1088     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1089       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1090         return CFP->getValueAPF().isZero();
1091   }
1092   return false;
1093 }
1094
1095 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1096 /// true if Op is undef or if it matches the specified value.
1097 static bool isConstantOrUndef(int Op, int Val) {
1098   return Op < 0 || Op == Val;
1099 }
1100
1101 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1102 /// VPKUHUM instruction.
1103 /// The ShuffleKind distinguishes between big-endian operations with
1104 /// two different inputs (0), either-endian operations with two identical
1105 /// inputs (1), and little-endian operations with two different inputs (2).
1106 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1107 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1108                                SelectionDAG &DAG) {
1109   bool IsLE = DAG.getDataLayout().isLittleEndian();
1110   if (ShuffleKind == 0) {
1111     if (IsLE)
1112       return false;
1113     for (unsigned i = 0; i != 16; ++i)
1114       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1115         return false;
1116   } else if (ShuffleKind == 2) {
1117     if (!IsLE)
1118       return false;
1119     for (unsigned i = 0; i != 16; ++i)
1120       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1121         return false;
1122   } else if (ShuffleKind == 1) {
1123     unsigned j = IsLE ? 0 : 1;
1124     for (unsigned i = 0; i != 8; ++i)
1125       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1126           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1127         return false;
1128   }
1129   return true;
1130 }
1131
1132 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1133 /// VPKUWUM instruction.
1134 /// The ShuffleKind distinguishes between big-endian operations with
1135 /// two different inputs (0), either-endian operations with two identical
1136 /// inputs (1), and little-endian operations with two different inputs (2).
1137 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1138 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1139                                SelectionDAG &DAG) {
1140   bool IsLE = DAG.getDataLayout().isLittleEndian();
1141   if (ShuffleKind == 0) {
1142     if (IsLE)
1143       return false;
1144     for (unsigned i = 0; i != 16; i += 2)
1145       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1146           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1147         return false;
1148   } else if (ShuffleKind == 2) {
1149     if (!IsLE)
1150       return false;
1151     for (unsigned i = 0; i != 16; i += 2)
1152       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1153           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1154         return false;
1155   } else if (ShuffleKind == 1) {
1156     unsigned j = IsLE ? 0 : 2;
1157     for (unsigned i = 0; i != 8; i += 2)
1158       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1159           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1160           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1161           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1162         return false;
1163   }
1164   return true;
1165 }
1166
1167 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1168 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1169 /// current subtarget.
1170 ///
1171 /// The ShuffleKind distinguishes between big-endian operations with
1172 /// two different inputs (0), either-endian operations with two identical
1173 /// inputs (1), and little-endian operations with two different inputs (2).
1174 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1175 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1176                                SelectionDAG &DAG) {
1177   const PPCSubtarget& Subtarget =
1178     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1179   if (!Subtarget.hasP8Vector())
1180     return false;
1181
1182   bool IsLE = DAG.getDataLayout().isLittleEndian();
1183   if (ShuffleKind == 0) {
1184     if (IsLE)
1185       return false;
1186     for (unsigned i = 0; i != 16; i += 4)
1187       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1188           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1189           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1190           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1191         return false;
1192   } else if (ShuffleKind == 2) {
1193     if (!IsLE)
1194       return false;
1195     for (unsigned i = 0; i != 16; i += 4)
1196       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1197           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1198           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1199           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1200         return false;
1201   } else if (ShuffleKind == 1) {
1202     unsigned j = IsLE ? 0 : 4;
1203     for (unsigned i = 0; i != 8; i += 4)
1204       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1205           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1206           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1207           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1208           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1209           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1210           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1211           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1212         return false;
1213   }
1214   return true;
1215 }
1216
1217 /// isVMerge - Common function, used to match vmrg* shuffles.
1218 ///
1219 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1220                      unsigned LHSStart, unsigned RHSStart) {
1221   if (N->getValueType(0) != MVT::v16i8)
1222     return false;
1223   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1224          "Unsupported merge size!");
1225
1226   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1227     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1228       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1229                              LHSStart+j+i*UnitSize) ||
1230           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1231                              RHSStart+j+i*UnitSize))
1232         return false;
1233     }
1234   return true;
1235 }
1236
1237 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1238 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1239 /// The ShuffleKind distinguishes between big-endian merges with two 
1240 /// different inputs (0), either-endian merges with two identical inputs (1),
1241 /// and little-endian merges with two different inputs (2).  For the latter,
1242 /// the input operands are swapped (see PPCInstrAltivec.td).
1243 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1244                              unsigned ShuffleKind, SelectionDAG &DAG) {
1245   if (DAG.getDataLayout().isLittleEndian()) {
1246     if (ShuffleKind == 1) // unary
1247       return isVMerge(N, UnitSize, 0, 0);
1248     else if (ShuffleKind == 2) // swapped
1249       return isVMerge(N, UnitSize, 0, 16);
1250     else
1251       return false;
1252   } else {
1253     if (ShuffleKind == 1) // unary
1254       return isVMerge(N, UnitSize, 8, 8);
1255     else if (ShuffleKind == 0) // normal
1256       return isVMerge(N, UnitSize, 8, 24);
1257     else
1258       return false;
1259   }
1260 }
1261
1262 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1263 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1264 /// The ShuffleKind distinguishes between big-endian merges with two 
1265 /// different inputs (0), either-endian merges with two identical inputs (1),
1266 /// and little-endian merges with two different inputs (2).  For the latter,
1267 /// the input operands are swapped (see PPCInstrAltivec.td).
1268 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1269                              unsigned ShuffleKind, SelectionDAG &DAG) {
1270   if (DAG.getDataLayout().isLittleEndian()) {
1271     if (ShuffleKind == 1) // unary
1272       return isVMerge(N, UnitSize, 8, 8);
1273     else if (ShuffleKind == 2) // swapped
1274       return isVMerge(N, UnitSize, 8, 24);
1275     else
1276       return false;
1277   } else {
1278     if (ShuffleKind == 1) // unary
1279       return isVMerge(N, UnitSize, 0, 0);
1280     else if (ShuffleKind == 0) // normal
1281       return isVMerge(N, UnitSize, 0, 16);
1282     else
1283       return false;
1284   }
1285 }
1286
1287 /**
1288  * \brief Common function used to match vmrgew and vmrgow shuffles
1289  *
1290  * The indexOffset determines whether to look for even or odd words in
1291  * the shuffle mask. This is based on the of the endianness of the target
1292  * machine.
1293  *   - Little Endian:
1294  *     - Use offset of 0 to check for odd elements
1295  *     - Use offset of 4 to check for even elements
1296  *   - Big Endian:
1297  *     - Use offset of 0 to check for even elements
1298  *     - Use offset of 4 to check for odd elements
1299  * A detailed description of the vector element ordering for little endian and
1300  * big endian can be found at
1301  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1302  * Targeting your applications - what little endian and big endian IBM XL C/C++
1303  * compiler differences mean to you
1304  *
1305  * The mask to the shuffle vector instruction specifies the indices of the
1306  * elements from the two input vectors to place in the result. The elements are
1307  * numbered in array-access order, starting with the first vector. These vectors
1308  * are always of type v16i8, thus each vector will contain 16 elements of size
1309  * 8. More info on the shuffle vector can be found in the
1310  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1311  * Language Reference.
1312  *
1313  * The RHSStartValue indicates whether the same input vectors are used (unary)
1314  * or two different input vectors are used, based on the following:
1315  *   - If the instruction uses the same vector for both inputs, the range of the
1316  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1317  *     be 0.
1318  *   - If the instruction has two different vectors then the range of the
1319  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1320  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1321  *     to 31 specify elements in the second vector).
1322  *
1323  * \param[in] N The shuffle vector SD Node to analyze
1324  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1325  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1326  * vector to the shuffle_vector instruction
1327  * \return true iff this shuffle vector represents an even or odd word merge
1328  */
1329 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1330                      unsigned RHSStartValue) {
1331   if (N->getValueType(0) != MVT::v16i8)
1332     return false;
1333
1334   for (unsigned i = 0; i < 2; ++i)
1335     for (unsigned j = 0; j < 4; ++j)
1336       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1337                              i*RHSStartValue+j+IndexOffset) ||
1338           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1339                              i*RHSStartValue+j+IndexOffset+8))
1340         return false;
1341   return true;
1342 }
1343
1344 /**
1345  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1346  * vmrgow instructions.
1347  *
1348  * \param[in] N The shuffle vector SD Node to analyze
1349  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1350  * \param[in] ShuffleKind Identify the type of merge:
1351  *   - 0 = big-endian merge with two different inputs;
1352  *   - 1 = either-endian merge with two identical inputs;
1353  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1354  *     little-endian merges).
1355  * \param[in] DAG The current SelectionDAG
1356  * \return true iff this shuffle mask 
1357  */
1358 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1359                               unsigned ShuffleKind, SelectionDAG &DAG) {
1360   if (DAG.getDataLayout().isLittleEndian()) {
1361     unsigned indexOffset = CheckEven ? 4 : 0;
1362     if (ShuffleKind == 1) // Unary
1363       return isVMerge(N, indexOffset, 0);
1364     else if (ShuffleKind == 2) // swapped
1365       return isVMerge(N, indexOffset, 16);
1366     else
1367       return false;
1368   }
1369   else {
1370     unsigned indexOffset = CheckEven ? 0 : 4;
1371     if (ShuffleKind == 1) // Unary
1372       return isVMerge(N, indexOffset, 0);
1373     else if (ShuffleKind == 0) // Normal
1374       return isVMerge(N, indexOffset, 16);
1375     else
1376       return false;
1377   }
1378   return false;
1379 }
1380
1381 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1382 /// amount, otherwise return -1.
1383 /// The ShuffleKind distinguishes between big-endian operations with two 
1384 /// different inputs (0), either-endian operations with two identical inputs
1385 /// (1), and little-endian operations with two different inputs (2).  For the
1386 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1387 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1388                              SelectionDAG &DAG) {
1389   if (N->getValueType(0) != MVT::v16i8)
1390     return -1;
1391
1392   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1393
1394   // Find the first non-undef value in the shuffle mask.
1395   unsigned i;
1396   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1397     /*search*/;
1398
1399   if (i == 16) return -1;  // all undef.
1400
1401   // Otherwise, check to see if the rest of the elements are consecutively
1402   // numbered from this value.
1403   unsigned ShiftAmt = SVOp->getMaskElt(i);
1404   if (ShiftAmt < i) return -1;
1405
1406   ShiftAmt -= i;
1407   bool isLE = DAG.getDataLayout().isLittleEndian();
1408
1409   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1410     // Check the rest of the elements to see if they are consecutive.
1411     for (++i; i != 16; ++i)
1412       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1413         return -1;
1414   } else if (ShuffleKind == 1) {
1415     // Check the rest of the elements to see if they are consecutive.
1416     for (++i; i != 16; ++i)
1417       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1418         return -1;
1419   } else
1420     return -1;
1421
1422   if (isLE)
1423     ShiftAmt = 16 - ShiftAmt;
1424
1425   return ShiftAmt;
1426 }
1427
1428 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1429 /// specifies a splat of a single element that is suitable for input to
1430 /// VSPLTB/VSPLTH/VSPLTW.
1431 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1432   assert(N->getValueType(0) == MVT::v16i8 &&
1433          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1434
1435   // The consecutive indices need to specify an element, not part of two
1436   // different elements.  So abandon ship early if this isn't the case.
1437   if (N->getMaskElt(0) % EltSize != 0)
1438     return false;
1439
1440   // This is a splat operation if each element of the permute is the same, and
1441   // if the value doesn't reference the second vector.
1442   unsigned ElementBase = N->getMaskElt(0);
1443
1444   // FIXME: Handle UNDEF elements too!
1445   if (ElementBase >= 16)
1446     return false;
1447
1448   // Check that the indices are consecutive, in the case of a multi-byte element
1449   // splatted with a v16i8 mask.
1450   for (unsigned i = 1; i != EltSize; ++i)
1451     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1452       return false;
1453
1454   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1455     if (N->getMaskElt(i) < 0) continue;
1456     for (unsigned j = 0; j != EltSize; ++j)
1457       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1458         return false;
1459   }
1460   return true;
1461 }
1462
1463 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1464 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1465 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1466                                 SelectionDAG &DAG) {
1467   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1468   assert(isSplatShuffleMask(SVOp, EltSize));
1469   if (DAG.getDataLayout().isLittleEndian())
1470     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1471   else
1472     return SVOp->getMaskElt(0) / EltSize;
1473 }
1474
1475 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1476 /// by using a vspltis[bhw] instruction of the specified element size, return
1477 /// the constant being splatted.  The ByteSize field indicates the number of
1478 /// bytes of each element [124] -> [bhw].
1479 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1480   SDValue OpVal(nullptr, 0);
1481
1482   // If ByteSize of the splat is bigger than the element size of the
1483   // build_vector, then we have a case where we are checking for a splat where
1484   // multiple elements of the buildvector are folded together into a single
1485   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1486   unsigned EltSize = 16/N->getNumOperands();
1487   if (EltSize < ByteSize) {
1488     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1489     SDValue UniquedVals[4];
1490     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1491
1492     // See if all of the elements in the buildvector agree across.
1493     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1494       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1495       // If the element isn't a constant, bail fully out.
1496       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1497
1498
1499       if (!UniquedVals[i&(Multiple-1)].getNode())
1500         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1501       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1502         return SDValue();  // no match.
1503     }
1504
1505     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1506     // either constant or undef values that are identical for each chunk.  See
1507     // if these chunks can form into a larger vspltis*.
1508
1509     // Check to see if all of the leading entries are either 0 or -1.  If
1510     // neither, then this won't fit into the immediate field.
1511     bool LeadingZero = true;
1512     bool LeadingOnes = true;
1513     for (unsigned i = 0; i != Multiple-1; ++i) {
1514       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1515
1516       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1517       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1518     }
1519     // Finally, check the least significant entry.
1520     if (LeadingZero) {
1521       if (!UniquedVals[Multiple-1].getNode())
1522         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1523       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1524       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1525         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1526     }
1527     if (LeadingOnes) {
1528       if (!UniquedVals[Multiple-1].getNode())
1529         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1530       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1531       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1532         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1533     }
1534
1535     return SDValue();
1536   }
1537
1538   // Check to see if this buildvec has a single non-undef value in its elements.
1539   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1540     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1541     if (!OpVal.getNode())
1542       OpVal = N->getOperand(i);
1543     else if (OpVal != N->getOperand(i))
1544       return SDValue();
1545   }
1546
1547   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1548
1549   unsigned ValSizeInBytes = EltSize;
1550   uint64_t Value = 0;
1551   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1552     Value = CN->getZExtValue();
1553   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1554     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1555     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1556   }
1557
1558   // If the splat value is larger than the element value, then we can never do
1559   // this splat.  The only case that we could fit the replicated bits into our
1560   // immediate field for would be zero, and we prefer to use vxor for it.
1561   if (ValSizeInBytes < ByteSize) return SDValue();
1562
1563   // If the element value is larger than the splat value, check if it consists
1564   // of a repeated bit pattern of size ByteSize.
1565   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1566     return SDValue();
1567
1568   // Properly sign extend the value.
1569   int MaskVal = SignExtend32(Value, ByteSize * 8);
1570
1571   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1572   if (MaskVal == 0) return SDValue();
1573
1574   // Finally, if this value fits in a 5 bit sext field, return it
1575   if (SignExtend32<5>(MaskVal) == MaskVal)
1576     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1577   return SDValue();
1578 }
1579
1580 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1581 /// amount, otherwise return -1.
1582 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1583   EVT VT = N->getValueType(0);
1584   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1585     return -1;
1586
1587   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1588
1589   // Find the first non-undef value in the shuffle mask.
1590   unsigned i;
1591   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1592     /*search*/;
1593
1594   if (i == 4) return -1;  // all undef.
1595
1596   // Otherwise, check to see if the rest of the elements are consecutively
1597   // numbered from this value.
1598   unsigned ShiftAmt = SVOp->getMaskElt(i);
1599   if (ShiftAmt < i) return -1;
1600   ShiftAmt -= i;
1601
1602   // Check the rest of the elements to see if they are consecutive.
1603   for (++i; i != 4; ++i)
1604     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1605       return -1;
1606
1607   return ShiftAmt;
1608 }
1609
1610 //===----------------------------------------------------------------------===//
1611 //  Addressing Mode Selection
1612 //===----------------------------------------------------------------------===//
1613
1614 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1615 /// or 64-bit immediate, and if the value can be accurately represented as a
1616 /// sign extension from a 16-bit value.  If so, this returns true and the
1617 /// immediate.
1618 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1619   if (!isa<ConstantSDNode>(N))
1620     return false;
1621
1622   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1623   if (N->getValueType(0) == MVT::i32)
1624     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1625   else
1626     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1627 }
1628 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1629   return isIntS16Immediate(Op.getNode(), Imm);
1630 }
1631
1632
1633 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1634 /// can be represented as an indexed [r+r] operation.  Returns false if it
1635 /// can be more efficiently represented with [r+imm].
1636 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1637                                             SDValue &Index,
1638                                             SelectionDAG &DAG) const {
1639   short imm = 0;
1640   if (N.getOpcode() == ISD::ADD) {
1641     if (isIntS16Immediate(N.getOperand(1), imm))
1642       return false;    // r+i
1643     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1644       return false;    // r+i
1645
1646     Base = N.getOperand(0);
1647     Index = N.getOperand(1);
1648     return true;
1649   } else if (N.getOpcode() == ISD::OR) {
1650     if (isIntS16Immediate(N.getOperand(1), imm))
1651       return false;    // r+i can fold it if we can.
1652
1653     // If this is an or of disjoint bitfields, we can codegen this as an add
1654     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1655     // disjoint.
1656     APInt LHSKnownZero, LHSKnownOne;
1657     APInt RHSKnownZero, RHSKnownOne;
1658     DAG.computeKnownBits(N.getOperand(0),
1659                          LHSKnownZero, LHSKnownOne);
1660
1661     if (LHSKnownZero.getBoolValue()) {
1662       DAG.computeKnownBits(N.getOperand(1),
1663                            RHSKnownZero, RHSKnownOne);
1664       // If all of the bits are known zero on the LHS or RHS, the add won't
1665       // carry.
1666       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1667         Base = N.getOperand(0);
1668         Index = N.getOperand(1);
1669         return true;
1670       }
1671     }
1672   }
1673
1674   return false;
1675 }
1676
1677 // If we happen to be doing an i64 load or store into a stack slot that has
1678 // less than a 4-byte alignment, then the frame-index elimination may need to
1679 // use an indexed load or store instruction (because the offset may not be a
1680 // multiple of 4). The extra register needed to hold the offset comes from the
1681 // register scavenger, and it is possible that the scavenger will need to use
1682 // an emergency spill slot. As a result, we need to make sure that a spill slot
1683 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1684 // stack slot.
1685 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1686   // FIXME: This does not handle the LWA case.
1687   if (VT != MVT::i64)
1688     return;
1689
1690   // NOTE: We'll exclude negative FIs here, which come from argument
1691   // lowering, because there are no known test cases triggering this problem
1692   // using packed structures (or similar). We can remove this exclusion if
1693   // we find such a test case. The reason why this is so test-case driven is
1694   // because this entire 'fixup' is only to prevent crashes (from the
1695   // register scavenger) on not-really-valid inputs. For example, if we have:
1696   //   %a = alloca i1
1697   //   %b = bitcast i1* %a to i64*
1698   //   store i64* a, i64 b
1699   // then the store should really be marked as 'align 1', but is not. If it
1700   // were marked as 'align 1' then the indexed form would have been
1701   // instruction-selected initially, and the problem this 'fixup' is preventing
1702   // won't happen regardless.
1703   if (FrameIdx < 0)
1704     return;
1705
1706   MachineFunction &MF = DAG.getMachineFunction();
1707   MachineFrameInfo *MFI = MF.getFrameInfo();
1708
1709   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1710   if (Align >= 4)
1711     return;
1712
1713   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1714   FuncInfo->setHasNonRISpills();
1715 }
1716
1717 /// Returns true if the address N can be represented by a base register plus
1718 /// a signed 16-bit displacement [r+imm], and if it is not better
1719 /// represented as reg+reg.  If Aligned is true, only accept displacements
1720 /// suitable for STD and friends, i.e. multiples of 4.
1721 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1722                                             SDValue &Base,
1723                                             SelectionDAG &DAG,
1724                                             bool Aligned) const {
1725   // FIXME dl should come from parent load or store, not from address
1726   SDLoc dl(N);
1727   // If this can be more profitably realized as r+r, fail.
1728   if (SelectAddressRegReg(N, Disp, Base, DAG))
1729     return false;
1730
1731   if (N.getOpcode() == ISD::ADD) {
1732     short imm = 0;
1733     if (isIntS16Immediate(N.getOperand(1), imm) &&
1734         (!Aligned || (imm & 3) == 0)) {
1735       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1736       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1737         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1738         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1739       } else {
1740         Base = N.getOperand(0);
1741       }
1742       return true; // [r+i]
1743     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1744       // Match LOAD (ADD (X, Lo(G))).
1745       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1746              && "Cannot handle constant offsets yet!");
1747       Disp = N.getOperand(1).getOperand(0);  // The global address.
1748       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1749              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1750              Disp.getOpcode() == ISD::TargetConstantPool ||
1751              Disp.getOpcode() == ISD::TargetJumpTable);
1752       Base = N.getOperand(0);
1753       return true;  // [&g+r]
1754     }
1755   } else if (N.getOpcode() == ISD::OR) {
1756     short imm = 0;
1757     if (isIntS16Immediate(N.getOperand(1), imm) &&
1758         (!Aligned || (imm & 3) == 0)) {
1759       // If this is an or of disjoint bitfields, we can codegen this as an add
1760       // (for better address arithmetic) if the LHS and RHS of the OR are
1761       // provably disjoint.
1762       APInt LHSKnownZero, LHSKnownOne;
1763       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1764
1765       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1766         // If all of the bits are known zero on the LHS or RHS, the add won't
1767         // carry.
1768         if (FrameIndexSDNode *FI =
1769               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1770           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1771           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1772         } else {
1773           Base = N.getOperand(0);
1774         }
1775         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1776         return true;
1777       }
1778     }
1779   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1780     // Loading from a constant address.
1781
1782     // If this address fits entirely in a 16-bit sext immediate field, codegen
1783     // this as "d, 0"
1784     short Imm;
1785     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1786       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1787       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1788                              CN->getValueType(0));
1789       return true;
1790     }
1791
1792     // Handle 32-bit sext immediates with LIS + addr mode.
1793     if ((CN->getValueType(0) == MVT::i32 ||
1794          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1795         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1796       int Addr = (int)CN->getZExtValue();
1797
1798       // Otherwise, break this down into an LIS + disp.
1799       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1800
1801       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1802                                    MVT::i32);
1803       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1804       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1805       return true;
1806     }
1807   }
1808
1809   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1810   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1811     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1812     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1813   } else
1814     Base = N;
1815   return true;      // [r+0]
1816 }
1817
1818 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1819 /// represented as an indexed [r+r] operation.
1820 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1821                                                 SDValue &Index,
1822                                                 SelectionDAG &DAG) const {
1823   // Check to see if we can easily represent this as an [r+r] address.  This
1824   // will fail if it thinks that the address is more profitably represented as
1825   // reg+imm, e.g. where imm = 0.
1826   if (SelectAddressRegReg(N, Base, Index, DAG))
1827     return true;
1828
1829   // If the operand is an addition, always emit this as [r+r], since this is
1830   // better (for code size, and execution, as the memop does the add for free)
1831   // than emitting an explicit add.
1832   if (N.getOpcode() == ISD::ADD) {
1833     Base = N.getOperand(0);
1834     Index = N.getOperand(1);
1835     return true;
1836   }
1837
1838   // Otherwise, do it the hard way, using R0 as the base register.
1839   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1840                          N.getValueType());
1841   Index = N;
1842   return true;
1843 }
1844
1845 /// getPreIndexedAddressParts - returns true by value, base pointer and
1846 /// offset pointer and addressing mode by reference if the node's address
1847 /// can be legally represented as pre-indexed load / store address.
1848 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1849                                                   SDValue &Offset,
1850                                                   ISD::MemIndexedMode &AM,
1851                                                   SelectionDAG &DAG) const {
1852   if (DisablePPCPreinc) return false;
1853
1854   bool isLoad = true;
1855   SDValue Ptr;
1856   EVT VT;
1857   unsigned Alignment;
1858   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1859     Ptr = LD->getBasePtr();
1860     VT = LD->getMemoryVT();
1861     Alignment = LD->getAlignment();
1862   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1863     Ptr = ST->getBasePtr();
1864     VT  = ST->getMemoryVT();
1865     Alignment = ST->getAlignment();
1866     isLoad = false;
1867   } else
1868     return false;
1869
1870   // PowerPC doesn't have preinc load/store instructions for vectors (except
1871   // for QPX, which does have preinc r+r forms).
1872   if (VT.isVector()) {
1873     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1874       return false;
1875     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1876       AM = ISD::PRE_INC;
1877       return true;
1878     }
1879   }
1880
1881   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1882
1883     // Common code will reject creating a pre-inc form if the base pointer
1884     // is a frame index, or if N is a store and the base pointer is either
1885     // the same as or a predecessor of the value being stored.  Check for
1886     // those situations here, and try with swapped Base/Offset instead.
1887     bool Swap = false;
1888
1889     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1890       Swap = true;
1891     else if (!isLoad) {
1892       SDValue Val = cast<StoreSDNode>(N)->getValue();
1893       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1894         Swap = true;
1895     }
1896
1897     if (Swap)
1898       std::swap(Base, Offset);
1899
1900     AM = ISD::PRE_INC;
1901     return true;
1902   }
1903
1904   // LDU/STU can only handle immediates that are a multiple of 4.
1905   if (VT != MVT::i64) {
1906     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1907       return false;
1908   } else {
1909     // LDU/STU need an address with at least 4-byte alignment.
1910     if (Alignment < 4)
1911       return false;
1912
1913     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1914       return false;
1915   }
1916
1917   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1918     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1919     // sext i32 to i64 when addr mode is r+i.
1920     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1921         LD->getExtensionType() == ISD::SEXTLOAD &&
1922         isa<ConstantSDNode>(Offset))
1923       return false;
1924   }
1925
1926   AM = ISD::PRE_INC;
1927   return true;
1928 }
1929
1930 //===----------------------------------------------------------------------===//
1931 //  LowerOperation implementation
1932 //===----------------------------------------------------------------------===//
1933
1934 /// GetLabelAccessInfo - Return true if we should reference labels using a
1935 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1936 static bool GetLabelAccessInfo(const TargetMachine &TM,
1937                                const PPCSubtarget &Subtarget,
1938                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1939                                const GlobalValue *GV = nullptr) {
1940   HiOpFlags = PPCII::MO_HA;
1941   LoOpFlags = PPCII::MO_LO;
1942
1943   // Don't use the pic base if not in PIC relocation model.
1944   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1945
1946   if (isPIC) {
1947     HiOpFlags |= PPCII::MO_PIC_FLAG;
1948     LoOpFlags |= PPCII::MO_PIC_FLAG;
1949   }
1950
1951   // If this is a reference to a global value that requires a non-lazy-ptr, make
1952   // sure that instruction lowering adds it.
1953   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1954     HiOpFlags |= PPCII::MO_NLP_FLAG;
1955     LoOpFlags |= PPCII::MO_NLP_FLAG;
1956
1957     if (GV->hasHiddenVisibility()) {
1958       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1959       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1960     }
1961   }
1962
1963   return isPIC;
1964 }
1965
1966 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1967                              SelectionDAG &DAG) {
1968   SDLoc DL(HiPart);
1969   EVT PtrVT = HiPart.getValueType();
1970   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1971
1972   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1973   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1974
1975   // With PIC, the first instruction is actually "GR+hi(&G)".
1976   if (isPIC)
1977     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1978                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1979
1980   // Generate non-pic code that has direct accesses to the constant pool.
1981   // The address of the global is just (hi(&g)+lo(&g)).
1982   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1983 }
1984
1985 static void setUsesTOCBasePtr(MachineFunction &MF) {
1986   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1987   FuncInfo->setUsesTOCBasePtr();
1988 }
1989
1990 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1991   setUsesTOCBasePtr(DAG.getMachineFunction());
1992 }
1993
1994 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1995                            SDValue GA) {
1996   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1997   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1998                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1999
2000   SDValue Ops[] = { GA, Reg };
2001   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
2002                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
2003                                  MachinePointerInfo::getGOT(), 0, false, true,
2004                                  false, 0);
2005 }
2006
2007 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2008                                              SelectionDAG &DAG) const {
2009   EVT PtrVT = Op.getValueType();
2010   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2011   const Constant *C = CP->getConstVal();
2012
2013   // 64-bit SVR4 ABI code is always position-independent.
2014   // The actual address of the GlobalValue is stored in the TOC.
2015   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2016     setUsesTOCBasePtr(DAG);
2017     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2018     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2019   }
2020
2021   unsigned MOHiFlag, MOLoFlag;
2022   bool isPIC =
2023       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2024
2025   if (isPIC && Subtarget.isSVR4ABI()) {
2026     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2027                                            PPCII::MO_PIC_FLAG);
2028     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2029   }
2030
2031   SDValue CPIHi =
2032     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2033   SDValue CPILo =
2034     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2035   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
2036 }
2037
2038 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2039   EVT PtrVT = Op.getValueType();
2040   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2041
2042   // 64-bit SVR4 ABI code is always position-independent.
2043   // The actual address of the GlobalValue is stored in the TOC.
2044   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2045     setUsesTOCBasePtr(DAG);
2046     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2047     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2048   }
2049
2050   unsigned MOHiFlag, MOLoFlag;
2051   bool isPIC =
2052       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2053
2054   if (isPIC && Subtarget.isSVR4ABI()) {
2055     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2056                                         PPCII::MO_PIC_FLAG);
2057     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2058   }
2059
2060   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2061   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2062   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
2063 }
2064
2065 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2066                                              SelectionDAG &DAG) const {
2067   EVT PtrVT = Op.getValueType();
2068   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2069   const BlockAddress *BA = BASDN->getBlockAddress();
2070
2071   // 64-bit SVR4 ABI code is always position-independent.
2072   // The actual BlockAddress is stored in the TOC.
2073   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2074     setUsesTOCBasePtr(DAG);
2075     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2076     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2077   }
2078
2079   unsigned MOHiFlag, MOLoFlag;
2080   bool isPIC =
2081       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2082   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2083   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2084   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
2085 }
2086
2087 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2088                                               SelectionDAG &DAG) const {
2089
2090   // FIXME: TLS addresses currently use medium model code sequences,
2091   // which is the most useful form.  Eventually support for small and
2092   // large models could be added if users need it, at the cost of
2093   // additional complexity.
2094   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2095   SDLoc dl(GA);
2096   const GlobalValue *GV = GA->getGlobal();
2097   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2098   bool is64bit = Subtarget.isPPC64();
2099   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2100   PICLevel::Level picLevel = M->getPICLevel();
2101
2102   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2103
2104   if (Model == TLSModel::LocalExec) {
2105     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2106                                                PPCII::MO_TPREL_HA);
2107     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2108                                                PPCII::MO_TPREL_LO);
2109     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2110                                      is64bit ? MVT::i64 : MVT::i32);
2111     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2112     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2113   }
2114
2115   if (Model == TLSModel::InitialExec) {
2116     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2117     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2118                                                 PPCII::MO_TLS);
2119     SDValue GOTPtr;
2120     if (is64bit) {
2121       setUsesTOCBasePtr(DAG);
2122       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2123       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2124                            PtrVT, GOTReg, TGA);
2125     } else
2126       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2127     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2128                                    PtrVT, TGA, GOTPtr);
2129     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2130   }
2131
2132   if (Model == TLSModel::GeneralDynamic) {
2133     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2134     SDValue GOTPtr;
2135     if (is64bit) {
2136       setUsesTOCBasePtr(DAG);
2137       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2138       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2139                                    GOTReg, TGA);
2140     } else {
2141       if (picLevel == PICLevel::Small)
2142         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2143       else
2144         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2145     }
2146     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2147                        GOTPtr, TGA, TGA);
2148   }
2149
2150   if (Model == TLSModel::LocalDynamic) {
2151     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2152     SDValue GOTPtr;
2153     if (is64bit) {
2154       setUsesTOCBasePtr(DAG);
2155       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2156       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2157                            GOTReg, TGA);
2158     } else {
2159       if (picLevel == PICLevel::Small)
2160         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2161       else
2162         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2163     }
2164     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2165                                   PtrVT, GOTPtr, TGA, TGA);
2166     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2167                                       PtrVT, TLSAddr, TGA);
2168     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2169   }
2170
2171   llvm_unreachable("Unknown TLS model!");
2172 }
2173
2174 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2175                                               SelectionDAG &DAG) const {
2176   EVT PtrVT = Op.getValueType();
2177   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2178   SDLoc DL(GSDN);
2179   const GlobalValue *GV = GSDN->getGlobal();
2180
2181   // 64-bit SVR4 ABI code is always position-independent.
2182   // The actual address of the GlobalValue is stored in the TOC.
2183   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2184     setUsesTOCBasePtr(DAG);
2185     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2186     return getTOCEntry(DAG, DL, true, GA);
2187   }
2188
2189   unsigned MOHiFlag, MOLoFlag;
2190   bool isPIC =
2191       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2192
2193   if (isPIC && Subtarget.isSVR4ABI()) {
2194     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2195                                             GSDN->getOffset(),
2196                                             PPCII::MO_PIC_FLAG);
2197     return getTOCEntry(DAG, DL, false, GA);
2198   }
2199
2200   SDValue GAHi =
2201     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2202   SDValue GALo =
2203     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2204
2205   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2206
2207   // If the global reference is actually to a non-lazy-pointer, we have to do an
2208   // extra load to get the address of the global.
2209   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2210     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2211                       false, false, false, 0);
2212   return Ptr;
2213 }
2214
2215 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2216   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2217   SDLoc dl(Op);
2218
2219   if (Op.getValueType() == MVT::v2i64) {
2220     // When the operands themselves are v2i64 values, we need to do something
2221     // special because VSX has no underlying comparison operations for these.
2222     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2223       // Equality can be handled by casting to the legal type for Altivec
2224       // comparisons, everything else needs to be expanded.
2225       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2226         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2227                  DAG.getSetCC(dl, MVT::v4i32,
2228                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2229                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2230                    CC));
2231       }
2232
2233       return SDValue();
2234     }
2235
2236     // We handle most of these in the usual way.
2237     return Op;
2238   }
2239
2240   // If we're comparing for equality to zero, expose the fact that this is
2241   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2242   // fold the new nodes.
2243   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2244     if (C->isNullValue() && CC == ISD::SETEQ) {
2245       EVT VT = Op.getOperand(0).getValueType();
2246       SDValue Zext = Op.getOperand(0);
2247       if (VT.bitsLT(MVT::i32)) {
2248         VT = MVT::i32;
2249         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2250       }
2251       unsigned Log2b = Log2_32(VT.getSizeInBits());
2252       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2253       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2254                                 DAG.getConstant(Log2b, dl, MVT::i32));
2255       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2256     }
2257     // Leave comparisons against 0 and -1 alone for now, since they're usually
2258     // optimized.  FIXME: revisit this when we can custom lower all setcc
2259     // optimizations.
2260     if (C->isAllOnesValue() || C->isNullValue())
2261       return SDValue();
2262   }
2263
2264   // If we have an integer seteq/setne, turn it into a compare against zero
2265   // by xor'ing the rhs with the lhs, which is faster than setting a
2266   // condition register, reading it back out, and masking the correct bit.  The
2267   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2268   // the result to other bit-twiddling opportunities.
2269   EVT LHSVT = Op.getOperand(0).getValueType();
2270   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2271     EVT VT = Op.getValueType();
2272     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2273                                 Op.getOperand(1));
2274     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2275   }
2276   return SDValue();
2277 }
2278
2279 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2280                                       const PPCSubtarget &Subtarget) const {
2281   SDNode *Node = Op.getNode();
2282   EVT VT = Node->getValueType(0);
2283   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2284   SDValue InChain = Node->getOperand(0);
2285   SDValue VAListPtr = Node->getOperand(1);
2286   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2287   SDLoc dl(Node);
2288
2289   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2290
2291   // gpr_index
2292   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2293                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2294                                     false, false, false, 0);
2295   InChain = GprIndex.getValue(1);
2296
2297   if (VT == MVT::i64) {
2298     // Check if GprIndex is even
2299     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2300                                  DAG.getConstant(1, dl, MVT::i32));
2301     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2302                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2303     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2304                                           DAG.getConstant(1, dl, MVT::i32));
2305     // Align GprIndex to be even if it isn't
2306     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2307                            GprIndex);
2308   }
2309
2310   // fpr index is 1 byte after gpr
2311   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2312                                DAG.getConstant(1, dl, MVT::i32));
2313
2314   // fpr
2315   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2316                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2317                                     false, false, false, 0);
2318   InChain = FprIndex.getValue(1);
2319
2320   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2321                                        DAG.getConstant(8, dl, MVT::i32));
2322
2323   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2324                                         DAG.getConstant(4, dl, MVT::i32));
2325
2326   // areas
2327   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2328                                      MachinePointerInfo(), false, false,
2329                                      false, 0);
2330   InChain = OverflowArea.getValue(1);
2331
2332   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2333                                     MachinePointerInfo(), false, false,
2334                                     false, 0);
2335   InChain = RegSaveArea.getValue(1);
2336
2337   // select overflow_area if index > 8
2338   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2339                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2340
2341   // adjustment constant gpr_index * 4/8
2342   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2343                                     VT.isInteger() ? GprIndex : FprIndex,
2344                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2345                                                     MVT::i32));
2346
2347   // OurReg = RegSaveArea + RegConstant
2348   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2349                                RegConstant);
2350
2351   // Floating types are 32 bytes into RegSaveArea
2352   if (VT.isFloatingPoint())
2353     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2354                          DAG.getConstant(32, dl, MVT::i32));
2355
2356   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2357   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2358                                    VT.isInteger() ? GprIndex : FprIndex,
2359                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2360                                                    MVT::i32));
2361
2362   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2363                               VT.isInteger() ? VAListPtr : FprPtr,
2364                               MachinePointerInfo(SV),
2365                               MVT::i8, false, false, 0);
2366
2367   // determine if we should load from reg_save_area or overflow_area
2368   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2369
2370   // increase overflow_area by 4/8 if gpr/fpr > 8
2371   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2372                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2373                                           dl, MVT::i32));
2374
2375   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2376                              OverflowAreaPlusN);
2377
2378   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2379                               OverflowAreaPtr,
2380                               MachinePointerInfo(),
2381                               MVT::i32, false, false, 0);
2382
2383   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2384                      false, false, false, 0);
2385 }
2386
2387 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2388                                        const PPCSubtarget &Subtarget) const {
2389   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2390
2391   // We have to copy the entire va_list struct:
2392   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2393   return DAG.getMemcpy(Op.getOperand(0), Op,
2394                        Op.getOperand(1), Op.getOperand(2),
2395                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2396                        false, MachinePointerInfo(), MachinePointerInfo());
2397 }
2398
2399 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2400                                                   SelectionDAG &DAG) const {
2401   return Op.getOperand(0);
2402 }
2403
2404 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2405                                                 SelectionDAG &DAG) const {
2406   SDValue Chain = Op.getOperand(0);
2407   SDValue Trmp = Op.getOperand(1); // trampoline
2408   SDValue FPtr = Op.getOperand(2); // nested function
2409   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2410   SDLoc dl(Op);
2411
2412   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2413   bool isPPC64 = (PtrVT == MVT::i64);
2414   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2415
2416   TargetLowering::ArgListTy Args;
2417   TargetLowering::ArgListEntry Entry;
2418
2419   Entry.Ty = IntPtrTy;
2420   Entry.Node = Trmp; Args.push_back(Entry);
2421
2422   // TrampSize == (isPPC64 ? 48 : 40);
2423   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2424                                isPPC64 ? MVT::i64 : MVT::i32);
2425   Args.push_back(Entry);
2426
2427   Entry.Node = FPtr; Args.push_back(Entry);
2428   Entry.Node = Nest; Args.push_back(Entry);
2429
2430   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2431   TargetLowering::CallLoweringInfo CLI(DAG);
2432   CLI.setDebugLoc(dl).setChain(Chain)
2433     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2434                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2435                std::move(Args), 0);
2436
2437   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2438   return CallResult.second;
2439 }
2440
2441 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2442                                         const PPCSubtarget &Subtarget) const {
2443   MachineFunction &MF = DAG.getMachineFunction();
2444   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2445
2446   SDLoc dl(Op);
2447
2448   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2449     // vastart just stores the address of the VarArgsFrameIndex slot into the
2450     // memory location argument.
2451     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2452     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2453     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2454     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2455                         MachinePointerInfo(SV),
2456                         false, false, 0);
2457   }
2458
2459   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2460   // We suppose the given va_list is already allocated.
2461   //
2462   // typedef struct {
2463   //  char gpr;     /* index into the array of 8 GPRs
2464   //                 * stored in the register save area
2465   //                 * gpr=0 corresponds to r3,
2466   //                 * gpr=1 to r4, etc.
2467   //                 */
2468   //  char fpr;     /* index into the array of 8 FPRs
2469   //                 * stored in the register save area
2470   //                 * fpr=0 corresponds to f1,
2471   //                 * fpr=1 to f2, etc.
2472   //                 */
2473   //  char *overflow_arg_area;
2474   //                /* location on stack that holds
2475   //                 * the next overflow argument
2476   //                 */
2477   //  char *reg_save_area;
2478   //               /* where r3:r10 and f1:f8 (if saved)
2479   //                * are stored
2480   //                */
2481   // } va_list[1];
2482
2483
2484   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2485   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2486
2487   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2488
2489   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2490                                             PtrVT);
2491   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2492                                  PtrVT);
2493
2494   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2495   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2496
2497   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2498   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2499
2500   uint64_t FPROffset = 1;
2501   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2502
2503   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2504
2505   // Store first byte : number of int regs
2506   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2507                                          Op.getOperand(1),
2508                                          MachinePointerInfo(SV),
2509                                          MVT::i8, false, false, 0);
2510   uint64_t nextOffset = FPROffset;
2511   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2512                                   ConstFPROffset);
2513
2514   // Store second byte : number of float regs
2515   SDValue secondStore =
2516     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2517                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2518                       false, false, 0);
2519   nextOffset += StackOffset;
2520   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2521
2522   // Store second word : arguments given on stack
2523   SDValue thirdStore =
2524     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2525                  MachinePointerInfo(SV, nextOffset),
2526                  false, false, 0);
2527   nextOffset += FrameOffset;
2528   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2529
2530   // Store third word : arguments given in registers
2531   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2532                       MachinePointerInfo(SV, nextOffset),
2533                       false, false, 0);
2534
2535 }
2536
2537 #include "PPCGenCallingConv.inc"
2538
2539 // Function whose sole purpose is to kill compiler warnings 
2540 // stemming from unused functions included from PPCGenCallingConv.inc.
2541 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2542   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2543 }
2544
2545 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2546                                       CCValAssign::LocInfo &LocInfo,
2547                                       ISD::ArgFlagsTy &ArgFlags,
2548                                       CCState &State) {
2549   return true;
2550 }
2551
2552 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2553                                              MVT &LocVT,
2554                                              CCValAssign::LocInfo &LocInfo,
2555                                              ISD::ArgFlagsTy &ArgFlags,
2556                                              CCState &State) {
2557   static const MCPhysReg ArgRegs[] = {
2558     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2559     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2560   };
2561   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2562
2563   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2564
2565   // Skip one register if the first unallocated register has an even register
2566   // number and there are still argument registers available which have not been
2567   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2568   // need to skip a register if RegNum is odd.
2569   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2570     State.AllocateReg(ArgRegs[RegNum]);
2571   }
2572
2573   // Always return false here, as this function only makes sure that the first
2574   // unallocated register has an odd register number and does not actually
2575   // allocate a register for the current argument.
2576   return false;
2577 }
2578
2579 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2580                                                MVT &LocVT,
2581                                                CCValAssign::LocInfo &LocInfo,
2582                                                ISD::ArgFlagsTy &ArgFlags,
2583                                                CCState &State) {
2584   static const MCPhysReg ArgRegs[] = {
2585     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2586     PPC::F8
2587   };
2588
2589   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2590
2591   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2592
2593   // If there is only one Floating-point register left we need to put both f64
2594   // values of a split ppc_fp128 value on the stack.
2595   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2596     State.AllocateReg(ArgRegs[RegNum]);
2597   }
2598
2599   // Always return false here, as this function only makes sure that the two f64
2600   // values a ppc_fp128 value is split into are both passed in registers or both
2601   // passed on the stack and does not actually allocate a register for the
2602   // current argument.
2603   return false;
2604 }
2605
2606 /// FPR - The set of FP registers that should be allocated for arguments,
2607 /// on Darwin.
2608 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2609                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2610                                 PPC::F11, PPC::F12, PPC::F13};
2611
2612 /// QFPR - The set of QPX registers that should be allocated for arguments.
2613 static const MCPhysReg QFPR[] = {
2614     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2615     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2616
2617 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2618 /// the stack.
2619 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2620                                        unsigned PtrByteSize) {
2621   unsigned ArgSize = ArgVT.getStoreSize();
2622   if (Flags.isByVal())
2623     ArgSize = Flags.getByValSize();
2624
2625   // Round up to multiples of the pointer size, except for array members,
2626   // which are always packed.
2627   if (!Flags.isInConsecutiveRegs())
2628     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2629
2630   return ArgSize;
2631 }
2632
2633 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2634 /// on the stack.
2635 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2636                                             ISD::ArgFlagsTy Flags,
2637                                             unsigned PtrByteSize) {
2638   unsigned Align = PtrByteSize;
2639
2640   // Altivec parameters are padded to a 16 byte boundary.
2641   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2642       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2643       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2644       ArgVT == MVT::v1i128)
2645     Align = 16;
2646   // QPX vector types stored in double-precision are padded to a 32 byte
2647   // boundary.
2648   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2649     Align = 32;
2650
2651   // ByVal parameters are aligned as requested.
2652   if (Flags.isByVal()) {
2653     unsigned BVAlign = Flags.getByValAlign();
2654     if (BVAlign > PtrByteSize) {
2655       if (BVAlign % PtrByteSize != 0)
2656           llvm_unreachable(
2657             "ByVal alignment is not a multiple of the pointer size");
2658
2659       Align = BVAlign;
2660     }
2661   }
2662
2663   // Array members are always packed to their original alignment.
2664   if (Flags.isInConsecutiveRegs()) {
2665     // If the array member was split into multiple registers, the first
2666     // needs to be aligned to the size of the full type.  (Except for
2667     // ppcf128, which is only aligned as its f64 components.)
2668     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2669       Align = OrigVT.getStoreSize();
2670     else
2671       Align = ArgVT.getStoreSize();
2672   }
2673
2674   return Align;
2675 }
2676
2677 /// CalculateStackSlotUsed - Return whether this argument will use its
2678 /// stack slot (instead of being passed in registers).  ArgOffset,
2679 /// AvailableFPRs, and AvailableVRs must hold the current argument
2680 /// position, and will be updated to account for this argument.
2681 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2682                                    ISD::ArgFlagsTy Flags,
2683                                    unsigned PtrByteSize,
2684                                    unsigned LinkageSize,
2685                                    unsigned ParamAreaSize,
2686                                    unsigned &ArgOffset,
2687                                    unsigned &AvailableFPRs,
2688                                    unsigned &AvailableVRs, bool HasQPX) {
2689   bool UseMemory = false;
2690
2691   // Respect alignment of argument on the stack.
2692   unsigned Align =
2693     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2694   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2695   // If there's no space left in the argument save area, we must
2696   // use memory (this check also catches zero-sized arguments).
2697   if (ArgOffset >= LinkageSize + ParamAreaSize)
2698     UseMemory = true;
2699
2700   // Allocate argument on the stack.
2701   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2702   if (Flags.isInConsecutiveRegsLast())
2703     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2704   // If we overran the argument save area, we must use memory
2705   // (this check catches arguments passed partially in memory)
2706   if (ArgOffset > LinkageSize + ParamAreaSize)
2707     UseMemory = true;
2708
2709   // However, if the argument is actually passed in an FPR or a VR,
2710   // we don't use memory after all.
2711   if (!Flags.isByVal()) {
2712     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2713         // QPX registers overlap with the scalar FP registers.
2714         (HasQPX && (ArgVT == MVT::v4f32 ||
2715                     ArgVT == MVT::v4f64 ||
2716                     ArgVT == MVT::v4i1)))
2717       if (AvailableFPRs > 0) {
2718         --AvailableFPRs;
2719         return false;
2720       }
2721     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2722         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2723         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2724         ArgVT == MVT::v1i128)
2725       if (AvailableVRs > 0) {
2726         --AvailableVRs;
2727         return false;
2728       }
2729   }
2730
2731   return UseMemory;
2732 }
2733
2734 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2735 /// ensure minimum alignment required for target.
2736 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2737                                      unsigned NumBytes) {
2738   unsigned TargetAlign = Lowering->getStackAlignment();
2739   unsigned AlignMask = TargetAlign - 1;
2740   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2741   return NumBytes;
2742 }
2743
2744 SDValue
2745 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2746                                         CallingConv::ID CallConv, bool isVarArg,
2747                                         const SmallVectorImpl<ISD::InputArg>
2748                                           &Ins,
2749                                         SDLoc dl, SelectionDAG &DAG,
2750                                         SmallVectorImpl<SDValue> &InVals)
2751                                           const {
2752   if (Subtarget.isSVR4ABI()) {
2753     if (Subtarget.isPPC64())
2754       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2755                                          dl, DAG, InVals);
2756     else
2757       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2758                                          dl, DAG, InVals);
2759   } else {
2760     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2761                                        dl, DAG, InVals);
2762   }
2763 }
2764
2765 SDValue
2766 PPCTargetLowering::LowerFormalArguments_32SVR4(
2767                                       SDValue Chain,
2768                                       CallingConv::ID CallConv, bool isVarArg,
2769                                       const SmallVectorImpl<ISD::InputArg>
2770                                         &Ins,
2771                                       SDLoc dl, SelectionDAG &DAG,
2772                                       SmallVectorImpl<SDValue> &InVals) const {
2773
2774   // 32-bit SVR4 ABI Stack Frame Layout:
2775   //              +-----------------------------------+
2776   //        +-->  |            Back chain             |
2777   //        |     +-----------------------------------+
2778   //        |     | Floating-point register save area |
2779   //        |     +-----------------------------------+
2780   //        |     |    General register save area     |
2781   //        |     +-----------------------------------+
2782   //        |     |          CR save word             |
2783   //        |     +-----------------------------------+
2784   //        |     |         VRSAVE save word          |
2785   //        |     +-----------------------------------+
2786   //        |     |         Alignment padding         |
2787   //        |     +-----------------------------------+
2788   //        |     |     Vector register save area     |
2789   //        |     +-----------------------------------+
2790   //        |     |       Local variable space        |
2791   //        |     +-----------------------------------+
2792   //        |     |        Parameter list area        |
2793   //        |     +-----------------------------------+
2794   //        |     |           LR save word            |
2795   //        |     +-----------------------------------+
2796   // SP-->  +---  |            Back chain             |
2797   //              +-----------------------------------+
2798   //
2799   // Specifications:
2800   //   System V Application Binary Interface PowerPC Processor Supplement
2801   //   AltiVec Technology Programming Interface Manual
2802
2803   MachineFunction &MF = DAG.getMachineFunction();
2804   MachineFrameInfo *MFI = MF.getFrameInfo();
2805   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2806
2807   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2808   // Potential tail calls could cause overwriting of argument stack slots.
2809   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2810                        (CallConv == CallingConv::Fast));
2811   unsigned PtrByteSize = 4;
2812
2813   // Assign locations to all of the incoming arguments.
2814   SmallVector<CCValAssign, 16> ArgLocs;
2815   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2816                  *DAG.getContext());
2817
2818   // Reserve space for the linkage area on the stack.
2819   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2820   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2821
2822   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2823
2824   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2825     CCValAssign &VA = ArgLocs[i];
2826
2827     // Arguments stored in registers.
2828     if (VA.isRegLoc()) {
2829       const TargetRegisterClass *RC;
2830       EVT ValVT = VA.getValVT();
2831
2832       switch (ValVT.getSimpleVT().SimpleTy) {
2833         default:
2834           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2835         case MVT::i1:
2836         case MVT::i32:
2837           RC = &PPC::GPRCRegClass;
2838           break;
2839         case MVT::f32:
2840           if (Subtarget.hasP8Vector())
2841             RC = &PPC::VSSRCRegClass;
2842           else
2843             RC = &PPC::F4RCRegClass;
2844           break;
2845         case MVT::f64:
2846           if (Subtarget.hasVSX())
2847             RC = &PPC::VSFRCRegClass;
2848           else
2849             RC = &PPC::F8RCRegClass;
2850           break;
2851         case MVT::v16i8:
2852         case MVT::v8i16:
2853         case MVT::v4i32:
2854           RC = &PPC::VRRCRegClass;
2855           break;
2856         case MVT::v4f32:
2857           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2858           break;
2859         case MVT::v2f64:
2860         case MVT::v2i64:
2861           RC = &PPC::VSHRCRegClass;
2862           break;
2863         case MVT::v4f64:
2864           RC = &PPC::QFRCRegClass;
2865           break;
2866         case MVT::v4i1:
2867           RC = &PPC::QBRCRegClass;
2868           break;
2869       }
2870
2871       // Transform the arguments stored in physical registers into virtual ones.
2872       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2873       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2874                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2875
2876       if (ValVT == MVT::i1)
2877         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2878
2879       InVals.push_back(ArgValue);
2880     } else {
2881       // Argument stored in memory.
2882       assert(VA.isMemLoc());
2883
2884       unsigned ArgSize = VA.getLocVT().getStoreSize();
2885       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2886                                       isImmutable);
2887
2888       // Create load nodes to retrieve arguments from the stack.
2889       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2890       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2891                                    MachinePointerInfo(),
2892                                    false, false, false, 0));
2893     }
2894   }
2895
2896   // Assign locations to all of the incoming aggregate by value arguments.
2897   // Aggregates passed by value are stored in the local variable space of the
2898   // caller's stack frame, right above the parameter list area.
2899   SmallVector<CCValAssign, 16> ByValArgLocs;
2900   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2901                       ByValArgLocs, *DAG.getContext());
2902
2903   // Reserve stack space for the allocations in CCInfo.
2904   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2905
2906   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2907
2908   // Area that is at least reserved in the caller of this function.
2909   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2910   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2911
2912   // Set the size that is at least reserved in caller of this function.  Tail
2913   // call optimized function's reserved stack space needs to be aligned so that
2914   // taking the difference between two stack areas will result in an aligned
2915   // stack.
2916   MinReservedArea =
2917       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2918   FuncInfo->setMinReservedArea(MinReservedArea);
2919
2920   SmallVector<SDValue, 8> MemOps;
2921
2922   // If the function takes variable number of arguments, make a frame index for
2923   // the start of the first vararg value... for expansion of llvm.va_start.
2924   if (isVarArg) {
2925     static const MCPhysReg GPArgRegs[] = {
2926       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2927       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2928     };
2929     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2930
2931     static const MCPhysReg FPArgRegs[] = {
2932       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2933       PPC::F8
2934     };
2935     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2936     if (DisablePPCFloatInVariadic)
2937       NumFPArgRegs = 0;
2938
2939     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2940     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2941
2942     // Make room for NumGPArgRegs and NumFPArgRegs.
2943     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2944                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2945
2946     FuncInfo->setVarArgsStackOffset(
2947       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2948                              CCInfo.getNextStackOffset(), true));
2949
2950     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2951     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2952
2953     // The fixed integer arguments of a variadic function are stored to the
2954     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2955     // the result of va_next.
2956     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2957       // Get an existing live-in vreg, or add a new one.
2958       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2959       if (!VReg)
2960         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2961
2962       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2963       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2964                                    MachinePointerInfo(), false, false, 0);
2965       MemOps.push_back(Store);
2966       // Increment the address by four for the next argument to store
2967       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2968       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2969     }
2970
2971     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2972     // is set.
2973     // The double arguments are stored to the VarArgsFrameIndex
2974     // on the stack.
2975     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2976       // Get an existing live-in vreg, or add a new one.
2977       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2978       if (!VReg)
2979         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2980
2981       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2982       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2983                                    MachinePointerInfo(), false, false, 0);
2984       MemOps.push_back(Store);
2985       // Increment the address by eight for the next argument to store
2986       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2987                                          PtrVT);
2988       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2989     }
2990   }
2991
2992   if (!MemOps.empty())
2993     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2994
2995   return Chain;
2996 }
2997
2998 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2999 // value to MVT::i64 and then truncate to the correct register size.
3000 SDValue
3001 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
3002                                      SelectionDAG &DAG, SDValue ArgVal,
3003                                      SDLoc dl) const {
3004   if (Flags.isSExt())
3005     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3006                          DAG.getValueType(ObjectVT));
3007   else if (Flags.isZExt())
3008     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3009                          DAG.getValueType(ObjectVT));
3010
3011   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3012 }
3013
3014 SDValue
3015 PPCTargetLowering::LowerFormalArguments_64SVR4(
3016                                       SDValue Chain,
3017                                       CallingConv::ID CallConv, bool isVarArg,
3018                                       const SmallVectorImpl<ISD::InputArg>
3019                                         &Ins,
3020                                       SDLoc dl, SelectionDAG &DAG,
3021                                       SmallVectorImpl<SDValue> &InVals) const {
3022   // TODO: add description of PPC stack frame format, or at least some docs.
3023   //
3024   bool isELFv2ABI = Subtarget.isELFv2ABI();
3025   bool isLittleEndian = Subtarget.isLittleEndian();
3026   MachineFunction &MF = DAG.getMachineFunction();
3027   MachineFrameInfo *MFI = MF.getFrameInfo();
3028   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3029
3030   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3031          "fastcc not supported on varargs functions");
3032
3033   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3034   // Potential tail calls could cause overwriting of argument stack slots.
3035   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3036                        (CallConv == CallingConv::Fast));
3037   unsigned PtrByteSize = 8;
3038   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3039
3040   static const MCPhysReg GPR[] = {
3041     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3042     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3043   };
3044   static const MCPhysReg VR[] = {
3045     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3046     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3047   };
3048   static const MCPhysReg VSRH[] = {
3049     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3050     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3051   };
3052
3053   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3054   const unsigned Num_FPR_Regs = 13;
3055   const unsigned Num_VR_Regs  = array_lengthof(VR);
3056   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3057
3058   // Do a first pass over the arguments to determine whether the ABI
3059   // guarantees that our caller has allocated the parameter save area
3060   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3061   // in the ELFv2 ABI, it is true if this is a vararg function or if
3062   // any parameter is located in a stack slot.
3063
3064   bool HasParameterArea = !isELFv2ABI || isVarArg;
3065   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3066   unsigned NumBytes = LinkageSize;
3067   unsigned AvailableFPRs = Num_FPR_Regs;
3068   unsigned AvailableVRs = Num_VR_Regs;
3069   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3070     if (Ins[i].Flags.isNest())
3071       continue;
3072
3073     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3074                                PtrByteSize, LinkageSize, ParamAreaSize,
3075                                NumBytes, AvailableFPRs, AvailableVRs,
3076                                Subtarget.hasQPX()))
3077       HasParameterArea = true;
3078   }
3079
3080   // Add DAG nodes to load the arguments or copy them out of registers.  On
3081   // entry to a function on PPC, the arguments start after the linkage area,
3082   // although the first ones are often in registers.
3083
3084   unsigned ArgOffset = LinkageSize;
3085   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3086   unsigned &QFPR_idx = FPR_idx;
3087   SmallVector<SDValue, 8> MemOps;
3088   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3089   unsigned CurArgIdx = 0;
3090   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3091     SDValue ArgVal;
3092     bool needsLoad = false;
3093     EVT ObjectVT = Ins[ArgNo].VT;
3094     EVT OrigVT = Ins[ArgNo].ArgVT;
3095     unsigned ObjSize = ObjectVT.getStoreSize();
3096     unsigned ArgSize = ObjSize;
3097     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3098     if (Ins[ArgNo].isOrigArg()) {
3099       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3100       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3101     }
3102     // We re-align the argument offset for each argument, except when using the
3103     // fast calling convention, when we need to make sure we do that only when
3104     // we'll actually use a stack slot.
3105     unsigned CurArgOffset, Align;
3106     auto ComputeArgOffset = [&]() {
3107       /* Respect alignment of argument on the stack.  */
3108       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3109       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3110       CurArgOffset = ArgOffset;
3111     };
3112
3113     if (CallConv != CallingConv::Fast) {
3114       ComputeArgOffset();
3115
3116       /* Compute GPR index associated with argument offset.  */
3117       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3118       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3119     }
3120
3121     // FIXME the codegen can be much improved in some cases.
3122     // We do not have to keep everything in memory.
3123     if (Flags.isByVal()) {
3124       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3125
3126       if (CallConv == CallingConv::Fast)
3127         ComputeArgOffset();
3128
3129       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3130       ObjSize = Flags.getByValSize();
3131       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3132       // Empty aggregate parameters do not take up registers.  Examples:
3133       //   struct { } a;
3134       //   union  { } b;
3135       //   int c[0];
3136       // etc.  However, we have to provide a place-holder in InVals, so
3137       // pretend we have an 8-byte item at the current address for that
3138       // purpose.
3139       if (!ObjSize) {
3140         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3141         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3142         InVals.push_back(FIN);
3143         continue;
3144       }
3145
3146       // Create a stack object covering all stack doublewords occupied
3147       // by the argument.  If the argument is (fully or partially) on
3148       // the stack, or if the argument is fully in registers but the
3149       // caller has allocated the parameter save anyway, we can refer
3150       // directly to the caller's stack frame.  Otherwise, create a
3151       // local copy in our own frame.
3152       int FI;
3153       if (HasParameterArea ||
3154           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3155         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3156       else
3157         FI = MFI->CreateStackObject(ArgSize, Align, false);
3158       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3159
3160       // Handle aggregates smaller than 8 bytes.
3161       if (ObjSize < PtrByteSize) {
3162         // The value of the object is its address, which differs from the
3163         // address of the enclosing doubleword on big-endian systems.
3164         SDValue Arg = FIN;
3165         if (!isLittleEndian) {
3166           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3167           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3168         }
3169         InVals.push_back(Arg);
3170
3171         if (GPR_idx != Num_GPR_Regs) {
3172           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3173           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3174           SDValue Store;
3175
3176           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3177             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3178                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3179             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3180                                       MachinePointerInfo(FuncArg),
3181                                       ObjType, false, false, 0);
3182           } else {
3183             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3184             // store the whole register as-is to the parameter save area
3185             // slot.
3186             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3187                                  MachinePointerInfo(FuncArg),
3188                                  false, false, 0);
3189           }
3190
3191           MemOps.push_back(Store);
3192         }
3193         // Whether we copied from a register or not, advance the offset
3194         // into the parameter save area by a full doubleword.
3195         ArgOffset += PtrByteSize;
3196         continue;
3197       }
3198
3199       // The value of the object is its address, which is the address of
3200       // its first stack doubleword.
3201       InVals.push_back(FIN);
3202
3203       // Store whatever pieces of the object are in registers to memory.
3204       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3205         if (GPR_idx == Num_GPR_Regs)
3206           break;
3207
3208         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3209         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3210         SDValue Addr = FIN;
3211         if (j) {
3212           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3213           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3214         }
3215         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3216                                      MachinePointerInfo(FuncArg, j),
3217                                      false, false, 0);
3218         MemOps.push_back(Store);
3219         ++GPR_idx;
3220       }
3221       ArgOffset += ArgSize;
3222       continue;
3223     }
3224
3225     switch (ObjectVT.getSimpleVT().SimpleTy) {
3226     default: llvm_unreachable("Unhandled argument type!");
3227     case MVT::i1:
3228     case MVT::i32:
3229     case MVT::i64:
3230       if (Flags.isNest()) {
3231         // The 'nest' parameter, if any, is passed in R11.
3232         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3233         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3234
3235         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3236           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3237
3238         break;
3239       }
3240
3241       // These can be scalar arguments or elements of an integer array type
3242       // passed directly.  Clang may use those instead of "byval" aggregate
3243       // types to avoid forcing arguments to memory unnecessarily.
3244       if (GPR_idx != Num_GPR_Regs) {
3245         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3246         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3247
3248         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3249           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3250           // value to MVT::i64 and then truncate to the correct register size.
3251           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3252       } else {
3253         if (CallConv == CallingConv::Fast)
3254           ComputeArgOffset();
3255
3256         needsLoad = true;
3257         ArgSize = PtrByteSize;
3258       }
3259       if (CallConv != CallingConv::Fast || needsLoad)
3260         ArgOffset += 8;
3261       break;
3262
3263     case MVT::f32:
3264     case MVT::f64:
3265       // These can be scalar arguments or elements of a float array type
3266       // passed directly.  The latter are used to implement ELFv2 homogenous
3267       // float aggregates.
3268       if (FPR_idx != Num_FPR_Regs) {
3269         unsigned VReg;
3270
3271         if (ObjectVT == MVT::f32)
3272           VReg = MF.addLiveIn(FPR[FPR_idx],
3273                               Subtarget.hasP8Vector()
3274                                   ? &PPC::VSSRCRegClass
3275                                   : &PPC::F4RCRegClass);
3276         else
3277           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3278                                                 ? &PPC::VSFRCRegClass
3279                                                 : &PPC::F8RCRegClass);
3280
3281         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3282         ++FPR_idx;
3283       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3284         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3285         // once we support fp <-> gpr moves.
3286
3287         // This can only ever happen in the presence of f32 array types,
3288         // since otherwise we never run out of FPRs before running out
3289         // of GPRs.
3290         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3291         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3292
3293         if (ObjectVT == MVT::f32) {
3294           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3295             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3296                                  DAG.getConstant(32, dl, MVT::i32));
3297           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3298         }
3299
3300         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3301       } else {
3302         if (CallConv == CallingConv::Fast)
3303           ComputeArgOffset();
3304
3305         needsLoad = true;
3306       }
3307
3308       // When passing an array of floats, the array occupies consecutive
3309       // space in the argument area; only round up to the next doubleword
3310       // at the end of the array.  Otherwise, each float takes 8 bytes.
3311       if (CallConv != CallingConv::Fast || needsLoad) {
3312         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3313         ArgOffset += ArgSize;
3314         if (Flags.isInConsecutiveRegsLast())
3315           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3316       }
3317       break;
3318     case MVT::v4f32:
3319     case MVT::v4i32:
3320     case MVT::v8i16:
3321     case MVT::v16i8:
3322     case MVT::v2f64:
3323     case MVT::v2i64:
3324     case MVT::v1i128:
3325       if (!Subtarget.hasQPX()) {
3326       // These can be scalar arguments or elements of a vector array type
3327       // passed directly.  The latter are used to implement ELFv2 homogenous
3328       // vector aggregates.
3329       if (VR_idx != Num_VR_Regs) {
3330         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3331                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3332                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3333         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3334         ++VR_idx;
3335       } else {
3336         if (CallConv == CallingConv::Fast)
3337           ComputeArgOffset();
3338
3339         needsLoad = true;
3340       }
3341       if (CallConv != CallingConv::Fast || needsLoad)
3342         ArgOffset += 16;
3343       break;
3344       } // not QPX
3345
3346       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3347              "Invalid QPX parameter type");
3348       /* fall through */
3349
3350     case MVT::v4f64:
3351     case MVT::v4i1:
3352       // QPX vectors are treated like their scalar floating-point subregisters
3353       // (except that they're larger).
3354       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3355       if (QFPR_idx != Num_QFPR_Regs) {
3356         const TargetRegisterClass *RC;
3357         switch (ObjectVT.getSimpleVT().SimpleTy) {
3358         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3359         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3360         default:         RC = &PPC::QBRCRegClass; break;
3361         }
3362
3363         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3364         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3365         ++QFPR_idx;
3366       } else {
3367         if (CallConv == CallingConv::Fast)
3368           ComputeArgOffset();
3369         needsLoad = true;
3370       }
3371       if (CallConv != CallingConv::Fast || needsLoad)
3372         ArgOffset += Sz;
3373       break;
3374     }
3375
3376     // We need to load the argument to a virtual register if we determined
3377     // above that we ran out of physical registers of the appropriate type.
3378     if (needsLoad) {
3379       if (ObjSize < ArgSize && !isLittleEndian)
3380         CurArgOffset += ArgSize - ObjSize;
3381       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3382       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3383       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3384                            false, false, false, 0);
3385     }
3386
3387     InVals.push_back(ArgVal);
3388   }
3389
3390   // Area that is at least reserved in the caller of this function.
3391   unsigned MinReservedArea;
3392   if (HasParameterArea)
3393     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3394   else
3395     MinReservedArea = LinkageSize;
3396
3397   // Set the size that is at least reserved in caller of this function.  Tail
3398   // call optimized functions' reserved stack space needs to be aligned so that
3399   // taking the difference between two stack areas will result in an aligned
3400   // stack.
3401   MinReservedArea =
3402       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3403   FuncInfo->setMinReservedArea(MinReservedArea);
3404
3405   // If the function takes variable number of arguments, make a frame index for
3406   // the start of the first vararg value... for expansion of llvm.va_start.
3407   if (isVarArg) {
3408     int Depth = ArgOffset;
3409
3410     FuncInfo->setVarArgsFrameIndex(
3411       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3412     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3413
3414     // If this function is vararg, store any remaining integer argument regs
3415     // to their spots on the stack so that they may be loaded by deferencing the
3416     // result of va_next.
3417     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3418          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3419       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3420       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3421       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3422                                    MachinePointerInfo(), false, false, 0);
3423       MemOps.push_back(Store);
3424       // Increment the address by four for the next argument to store
3425       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3426       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3427     }
3428   }
3429
3430   if (!MemOps.empty())
3431     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3432
3433   return Chain;
3434 }
3435
3436 SDValue
3437 PPCTargetLowering::LowerFormalArguments_Darwin(
3438                                       SDValue Chain,
3439                                       CallingConv::ID CallConv, bool isVarArg,
3440                                       const SmallVectorImpl<ISD::InputArg>
3441                                         &Ins,
3442                                       SDLoc dl, SelectionDAG &DAG,
3443                                       SmallVectorImpl<SDValue> &InVals) const {
3444   // TODO: add description of PPC stack frame format, or at least some docs.
3445   //
3446   MachineFunction &MF = DAG.getMachineFunction();
3447   MachineFrameInfo *MFI = MF.getFrameInfo();
3448   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3449
3450   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3451   bool isPPC64 = PtrVT == MVT::i64;
3452   // Potential tail calls could cause overwriting of argument stack slots.
3453   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3454                        (CallConv == CallingConv::Fast));
3455   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3456   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3457   unsigned ArgOffset = LinkageSize;
3458   // Area that is at least reserved in caller of this function.
3459   unsigned MinReservedArea = ArgOffset;
3460
3461   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3462     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3463     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3464   };
3465   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3466     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3467     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3468   };
3469   static const MCPhysReg VR[] = {
3470     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3471     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3472   };
3473
3474   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3475   const unsigned Num_FPR_Regs = 13;
3476   const unsigned Num_VR_Regs  = array_lengthof( VR);
3477
3478   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3479
3480   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3481
3482   // In 32-bit non-varargs functions, the stack space for vectors is after the
3483   // stack space for non-vectors.  We do not use this space unless we have
3484   // too many vectors to fit in registers, something that only occurs in
3485   // constructed examples:), but we have to walk the arglist to figure
3486   // that out...for the pathological case, compute VecArgOffset as the
3487   // start of the vector parameter area.  Computing VecArgOffset is the
3488   // entire point of the following loop.
3489   unsigned VecArgOffset = ArgOffset;
3490   if (!isVarArg && !isPPC64) {
3491     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3492          ++ArgNo) {
3493       EVT ObjectVT = Ins[ArgNo].VT;
3494       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3495
3496       if (Flags.isByVal()) {
3497         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3498         unsigned ObjSize = Flags.getByValSize();
3499         unsigned ArgSize =
3500                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3501         VecArgOffset += ArgSize;
3502         continue;
3503       }
3504
3505       switch(ObjectVT.getSimpleVT().SimpleTy) {
3506       default: llvm_unreachable("Unhandled argument type!");
3507       case MVT::i1:
3508       case MVT::i32:
3509       case MVT::f32:
3510         VecArgOffset += 4;
3511         break;
3512       case MVT::i64:  // PPC64
3513       case MVT::f64:
3514         // FIXME: We are guaranteed to be !isPPC64 at this point.
3515         // Does MVT::i64 apply?
3516         VecArgOffset += 8;
3517         break;
3518       case MVT::v4f32:
3519       case MVT::v4i32:
3520       case MVT::v8i16:
3521       case MVT::v16i8:
3522         // Nothing to do, we're only looking at Nonvector args here.
3523         break;
3524       }
3525     }
3526   }
3527   // We've found where the vector parameter area in memory is.  Skip the
3528   // first 12 parameters; these don't use that memory.
3529   VecArgOffset = ((VecArgOffset+15)/16)*16;
3530   VecArgOffset += 12*16;
3531
3532   // Add DAG nodes to load the arguments or copy them out of registers.  On
3533   // entry to a function on PPC, the arguments start after the linkage area,
3534   // although the first ones are often in registers.
3535
3536   SmallVector<SDValue, 8> MemOps;
3537   unsigned nAltivecParamsAtEnd = 0;
3538   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3539   unsigned CurArgIdx = 0;
3540   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3541     SDValue ArgVal;
3542     bool needsLoad = false;
3543     EVT ObjectVT = Ins[ArgNo].VT;
3544     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3545     unsigned ArgSize = ObjSize;
3546     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3547     if (Ins[ArgNo].isOrigArg()) {
3548       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3549       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3550     }
3551     unsigned CurArgOffset = ArgOffset;
3552
3553     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3554     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3555         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3556       if (isVarArg || isPPC64) {
3557         MinReservedArea = ((MinReservedArea+15)/16)*16;
3558         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3559                                                   Flags,
3560                                                   PtrByteSize);
3561       } else  nAltivecParamsAtEnd++;
3562     } else
3563       // Calculate min reserved area.
3564       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3565                                                 Flags,
3566                                                 PtrByteSize);
3567
3568     // FIXME the codegen can be much improved in some cases.
3569     // We do not have to keep everything in memory.
3570     if (Flags.isByVal()) {
3571       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3572
3573       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3574       ObjSize = Flags.getByValSize();
3575       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3576       // Objects of size 1 and 2 are right justified, everything else is
3577       // left justified.  This means the memory address is adjusted forwards.
3578       if (ObjSize==1 || ObjSize==2) {
3579         CurArgOffset = CurArgOffset + (4 - ObjSize);
3580       }
3581       // The value of the object is its address.
3582       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3583       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3584       InVals.push_back(FIN);
3585       if (ObjSize==1 || ObjSize==2) {
3586         if (GPR_idx != Num_GPR_Regs) {
3587           unsigned VReg;
3588           if (isPPC64)
3589             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3590           else
3591             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3592           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3593           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3594           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3595                                             MachinePointerInfo(FuncArg),
3596                                             ObjType, false, false, 0);
3597           MemOps.push_back(Store);
3598           ++GPR_idx;
3599         }
3600
3601         ArgOffset += PtrByteSize;
3602
3603         continue;
3604       }
3605       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3606         // Store whatever pieces of the object are in registers
3607         // to memory.  ArgOffset will be the address of the beginning
3608         // of the object.
3609         if (GPR_idx != Num_GPR_Regs) {
3610           unsigned VReg;
3611           if (isPPC64)
3612             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3613           else
3614             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3615           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3616           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3617           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3618           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3619                                        MachinePointerInfo(FuncArg, j),
3620                                        false, false, 0);
3621           MemOps.push_back(Store);
3622           ++GPR_idx;
3623           ArgOffset += PtrByteSize;
3624         } else {
3625           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3626           break;
3627         }
3628       }
3629       continue;
3630     }
3631
3632     switch (ObjectVT.getSimpleVT().SimpleTy) {
3633     default: llvm_unreachable("Unhandled argument type!");
3634     case MVT::i1:
3635     case MVT::i32:
3636       if (!isPPC64) {
3637         if (GPR_idx != Num_GPR_Regs) {
3638           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3639           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3640
3641           if (ObjectVT == MVT::i1)
3642             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3643
3644           ++GPR_idx;
3645         } else {
3646           needsLoad = true;
3647           ArgSize = PtrByteSize;
3648         }
3649         // All int arguments reserve stack space in the Darwin ABI.
3650         ArgOffset += PtrByteSize;
3651         break;
3652       }
3653       // FALLTHROUGH
3654     case MVT::i64:  // PPC64
3655       if (GPR_idx != Num_GPR_Regs) {
3656         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3657         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3658
3659         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3660           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3661           // value to MVT::i64 and then truncate to the correct register size.
3662           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3663
3664         ++GPR_idx;
3665       } else {
3666         needsLoad = true;
3667         ArgSize = PtrByteSize;
3668       }
3669       // All int arguments reserve stack space in the Darwin ABI.
3670       ArgOffset += 8;
3671       break;
3672
3673     case MVT::f32:
3674     case MVT::f64:
3675       // Every 4 bytes of argument space consumes one of the GPRs available for
3676       // argument passing.
3677       if (GPR_idx != Num_GPR_Regs) {
3678         ++GPR_idx;
3679         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3680           ++GPR_idx;
3681       }
3682       if (FPR_idx != Num_FPR_Regs) {
3683         unsigned VReg;
3684
3685         if (ObjectVT == MVT::f32)
3686           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3687         else
3688           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3689
3690         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3691         ++FPR_idx;
3692       } else {
3693         needsLoad = true;
3694       }
3695
3696       // All FP arguments reserve stack space in the Darwin ABI.
3697       ArgOffset += isPPC64 ? 8 : ObjSize;
3698       break;
3699     case MVT::v4f32:
3700     case MVT::v4i32:
3701     case MVT::v8i16:
3702     case MVT::v16i8:
3703       // Note that vector arguments in registers don't reserve stack space,
3704       // except in varargs functions.
3705       if (VR_idx != Num_VR_Regs) {
3706         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3707         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3708         if (isVarArg) {
3709           while ((ArgOffset % 16) != 0) {
3710             ArgOffset += PtrByteSize;
3711             if (GPR_idx != Num_GPR_Regs)
3712               GPR_idx++;
3713           }
3714           ArgOffset += 16;
3715           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3716         }
3717         ++VR_idx;
3718       } else {
3719         if (!isVarArg && !isPPC64) {
3720           // Vectors go after all the nonvectors.
3721           CurArgOffset = VecArgOffset;
3722           VecArgOffset += 16;
3723         } else {
3724           // Vectors are aligned.
3725           ArgOffset = ((ArgOffset+15)/16)*16;
3726           CurArgOffset = ArgOffset;
3727           ArgOffset += 16;
3728         }
3729         needsLoad = true;
3730       }
3731       break;
3732     }
3733
3734     // We need to load the argument to a virtual register if we determined above
3735     // that we ran out of physical registers of the appropriate type.
3736     if (needsLoad) {
3737       int FI = MFI->CreateFixedObject(ObjSize,
3738                                       CurArgOffset + (ArgSize - ObjSize),
3739                                       isImmutable);
3740       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3741       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3742                            false, false, false, 0);
3743     }
3744
3745     InVals.push_back(ArgVal);
3746   }
3747
3748   // Allow for Altivec parameters at the end, if needed.
3749   if (nAltivecParamsAtEnd) {
3750     MinReservedArea = ((MinReservedArea+15)/16)*16;
3751     MinReservedArea += 16*nAltivecParamsAtEnd;
3752   }
3753
3754   // Area that is at least reserved in the caller of this function.
3755   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3756
3757   // Set the size that is at least reserved in caller of this function.  Tail
3758   // call optimized functions' reserved stack space needs to be aligned so that
3759   // taking the difference between two stack areas will result in an aligned
3760   // stack.
3761   MinReservedArea =
3762       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3763   FuncInfo->setMinReservedArea(MinReservedArea);
3764
3765   // If the function takes variable number of arguments, make a frame index for
3766   // the start of the first vararg value... for expansion of llvm.va_start.
3767   if (isVarArg) {
3768     int Depth = ArgOffset;
3769
3770     FuncInfo->setVarArgsFrameIndex(
3771       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3772                              Depth, true));
3773     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3774
3775     // If this function is vararg, store any remaining integer argument regs
3776     // to their spots on the stack so that they may be loaded by deferencing the
3777     // result of va_next.
3778     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3779       unsigned VReg;
3780
3781       if (isPPC64)
3782         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3783       else
3784         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3785
3786       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3787       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3788                                    MachinePointerInfo(), false, false, 0);
3789       MemOps.push_back(Store);
3790       // Increment the address by four for the next argument to store
3791       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3792       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3793     }
3794   }
3795
3796   if (!MemOps.empty())
3797     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3798
3799   return Chain;
3800 }
3801
3802 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3803 /// adjusted to accommodate the arguments for the tailcall.
3804 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3805                                    unsigned ParamSize) {
3806
3807   if (!isTailCall) return 0;
3808
3809   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3810   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3811   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3812   // Remember only if the new adjustement is bigger.
3813   if (SPDiff < FI->getTailCallSPDelta())
3814     FI->setTailCallSPDelta(SPDiff);
3815
3816   return SPDiff;
3817 }
3818
3819 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3820 /// for tail call optimization. Targets which want to do tail call
3821 /// optimization should implement this function.
3822 bool
3823 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3824                                                      CallingConv::ID CalleeCC,
3825                                                      bool isVarArg,
3826                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3827                                                      SelectionDAG& DAG) const {
3828   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3829     return false;
3830
3831   // Variable argument functions are not supported.
3832   if (isVarArg)
3833     return false;
3834
3835   MachineFunction &MF = DAG.getMachineFunction();
3836   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3837   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3838     // Functions containing by val parameters are not supported.
3839     for (unsigned i = 0; i != Ins.size(); i++) {
3840        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3841        if (Flags.isByVal()) return false;
3842     }
3843
3844     // Non-PIC/GOT tail calls are supported.
3845     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3846       return true;
3847
3848     // At the moment we can only do local tail calls (in same module, hidden
3849     // or protected) if we are generating PIC.
3850     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3851       return G->getGlobal()->hasHiddenVisibility()
3852           || G->getGlobal()->hasProtectedVisibility();
3853   }
3854
3855   return false;
3856 }
3857
3858 /// isCallCompatibleAddress - Return the immediate to use if the specified
3859 /// 32-bit value is representable in the immediate field of a BxA instruction.
3860 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3861   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3862   if (!C) return nullptr;
3863
3864   int Addr = C->getZExtValue();
3865   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3866       SignExtend32<26>(Addr) != Addr)
3867     return nullptr;  // Top 6 bits have to be sext of immediate.
3868
3869   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3870                          DAG.getTargetLoweringInfo().getPointerTy(
3871                              DAG.getDataLayout())).getNode();
3872 }
3873
3874 namespace {
3875
3876 struct TailCallArgumentInfo {
3877   SDValue Arg;
3878   SDValue FrameIdxOp;
3879   int       FrameIdx;
3880
3881   TailCallArgumentInfo() : FrameIdx(0) {}
3882 };
3883
3884 }
3885
3886 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3887 static void
3888 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3889                                            SDValue Chain,
3890                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3891                    SmallVectorImpl<SDValue> &MemOpChains,
3892                    SDLoc dl) {
3893   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3894     SDValue Arg = TailCallArgs[i].Arg;
3895     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3896     int FI = TailCallArgs[i].FrameIdx;
3897     // Store relative to framepointer.
3898     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3899                                        MachinePointerInfo::getFixedStack(FI),
3900                                        false, false, 0));
3901   }
3902 }
3903
3904 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3905 /// the appropriate stack slot for the tail call optimized function call.
3906 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3907                                                MachineFunction &MF,
3908                                                SDValue Chain,
3909                                                SDValue OldRetAddr,
3910                                                SDValue OldFP,
3911                                                int SPDiff,
3912                                                bool isPPC64,
3913                                                bool isDarwinABI,
3914                                                SDLoc dl) {
3915   if (SPDiff) {
3916     // Calculate the new stack slot for the return address.
3917     int SlotSize = isPPC64 ? 8 : 4;
3918     const PPCFrameLowering *FL =
3919         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3920     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3921     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3922                                                           NewRetAddrLoc, true);
3923     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3924     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3925     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3926                          MachinePointerInfo::getFixedStack(NewRetAddr),
3927                          false, false, 0);
3928
3929     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3930     // slot as the FP is never overwritten.
3931     if (isDarwinABI) {
3932       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3933       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3934                                                           true);
3935       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3936       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3937                            MachinePointerInfo::getFixedStack(NewFPIdx),
3938                            false, false, 0);
3939     }
3940   }
3941   return Chain;
3942 }
3943
3944 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3945 /// the position of the argument.
3946 static void
3947 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3948                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3949                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3950   int Offset = ArgOffset + SPDiff;
3951   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3952   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3953   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3954   SDValue FIN = DAG.getFrameIndex(FI, VT);
3955   TailCallArgumentInfo Info;
3956   Info.Arg = Arg;
3957   Info.FrameIdxOp = FIN;
3958   Info.FrameIdx = FI;
3959   TailCallArguments.push_back(Info);
3960 }
3961
3962 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3963 /// stack slot. Returns the chain as result and the loaded frame pointers in
3964 /// LROpOut/FPOpout. Used when tail calling.
3965 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3966                                                         int SPDiff,
3967                                                         SDValue Chain,
3968                                                         SDValue &LROpOut,
3969                                                         SDValue &FPOpOut,
3970                                                         bool isDarwinABI,
3971                                                         SDLoc dl) const {
3972   if (SPDiff) {
3973     // Load the LR and FP stack slot for later adjusting.
3974     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3975     LROpOut = getReturnAddrFrameIndex(DAG);
3976     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3977                           false, false, false, 0);
3978     Chain = SDValue(LROpOut.getNode(), 1);
3979
3980     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3981     // slot as the FP is never overwritten.
3982     if (isDarwinABI) {
3983       FPOpOut = getFramePointerFrameIndex(DAG);
3984       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3985                             false, false, false, 0);
3986       Chain = SDValue(FPOpOut.getNode(), 1);
3987     }
3988   }
3989   return Chain;
3990 }
3991
3992 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3993 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3994 /// specified by the specific parameter attribute. The copy will be passed as
3995 /// a byval function parameter.
3996 /// Sometimes what we are copying is the end of a larger object, the part that
3997 /// does not fit in registers.
3998 static SDValue
3999 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
4000                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
4001                           SDLoc dl) {
4002   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4003   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4004                        false, false, false, MachinePointerInfo(),
4005                        MachinePointerInfo());
4006 }
4007
4008 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4009 /// tail calls.
4010 static void
4011 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
4012                  SDValue Arg, SDValue PtrOff, int SPDiff,
4013                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
4014                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4015                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
4016                  SDLoc dl) {
4017   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4018   if (!isTailCall) {
4019     if (isVector) {
4020       SDValue StackPtr;
4021       if (isPPC64)
4022         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4023       else
4024         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4025       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4026                            DAG.getConstant(ArgOffset, dl, PtrVT));
4027     }
4028     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4029                                        MachinePointerInfo(), false, false, 0));
4030   // Calculate and remember argument location.
4031   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4032                                   TailCallArguments);
4033 }
4034
4035 static
4036 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4037                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
4038                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
4039                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4040   MachineFunction &MF = DAG.getMachineFunction();
4041
4042   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4043   // might overwrite each other in case of tail call optimization.
4044   SmallVector<SDValue, 8> MemOpChains2;
4045   // Do not flag preceding copytoreg stuff together with the following stuff.
4046   InFlag = SDValue();
4047   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4048                                     MemOpChains2, dl);
4049   if (!MemOpChains2.empty())
4050     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4051
4052   // Store the return address to the appropriate stack slot.
4053   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
4054                                         isPPC64, isDarwinABI, dl);
4055
4056   // Emit callseq_end just before tailcall node.
4057   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4058                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4059   InFlag = Chain.getValue(1);
4060 }
4061
4062 // Is this global address that of a function that can be called by name? (as
4063 // opposed to something that must hold a descriptor for an indirect call).
4064 static bool isFunctionGlobalAddress(SDValue Callee) {
4065   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4066     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4067         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4068       return false;
4069
4070     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
4071   }
4072
4073   return false;
4074 }
4075
4076 static
4077 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
4078                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
4079                      bool isTailCall, bool IsPatchPoint, bool hasNest,
4080                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
4081                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4082                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4083
4084   bool isPPC64 = Subtarget.isPPC64();
4085   bool isSVR4ABI = Subtarget.isSVR4ABI();
4086   bool isELFv2ABI = Subtarget.isELFv2ABI();
4087
4088   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4089   NodeTys.push_back(MVT::Other);   // Returns a chain
4090   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4091
4092   unsigned CallOpc = PPCISD::CALL;
4093
4094   bool needIndirectCall = true;
4095   if (!isSVR4ABI || !isPPC64)
4096     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4097       // If this is an absolute destination address, use the munged value.
4098       Callee = SDValue(Dest, 0);
4099       needIndirectCall = false;
4100     }
4101
4102   if (isFunctionGlobalAddress(Callee)) {
4103     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4104     // A call to a TLS address is actually an indirect call to a
4105     // thread-specific pointer.
4106     unsigned OpFlags = 0;
4107     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4108          (Subtarget.getTargetTriple().isMacOSX() &&
4109           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
4110          !G->getGlobal()->isStrongDefinitionForLinker()) ||
4111         (Subtarget.isTargetELF() && !isPPC64 &&
4112          !G->getGlobal()->hasLocalLinkage() &&
4113          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4114       // PC-relative references to external symbols should go through $stub,
4115       // unless we're building with the leopard linker or later, which
4116       // automatically synthesizes these stubs.
4117       OpFlags = PPCII::MO_PLT_OR_STUB;
4118     }
4119
4120     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4121     // every direct call is) turn it into a TargetGlobalAddress /
4122     // TargetExternalSymbol node so that legalize doesn't hack it.
4123     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4124                                         Callee.getValueType(), 0, OpFlags);
4125     needIndirectCall = false;
4126   }
4127
4128   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4129     unsigned char OpFlags = 0;
4130
4131     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4132          (Subtarget.getTargetTriple().isMacOSX() &&
4133           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4134         (Subtarget.isTargetELF() && !isPPC64 &&
4135          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4136       // PC-relative references to external symbols should go through $stub,
4137       // unless we're building with the leopard linker or later, which
4138       // automatically synthesizes these stubs.
4139       OpFlags = PPCII::MO_PLT_OR_STUB;
4140     }
4141
4142     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4143                                          OpFlags);
4144     needIndirectCall = false;
4145   }
4146
4147   if (IsPatchPoint) {
4148     // We'll form an invalid direct call when lowering a patchpoint; the full
4149     // sequence for an indirect call is complicated, and many of the
4150     // instructions introduced might have side effects (and, thus, can't be
4151     // removed later). The call itself will be removed as soon as the
4152     // argument/return lowering is complete, so the fact that it has the wrong
4153     // kind of operands should not really matter.
4154     needIndirectCall = false;
4155   }
4156
4157   if (needIndirectCall) {
4158     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4159     // to do the call, we can't use PPCISD::CALL.
4160     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4161
4162     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4163       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4164       // entry point, but to the function descriptor (the function entry point
4165       // address is part of the function descriptor though).
4166       // The function descriptor is a three doubleword structure with the
4167       // following fields: function entry point, TOC base address and
4168       // environment pointer.
4169       // Thus for a call through a function pointer, the following actions need
4170       // to be performed:
4171       //   1. Save the TOC of the caller in the TOC save area of its stack
4172       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4173       //   2. Load the address of the function entry point from the function
4174       //      descriptor.
4175       //   3. Load the TOC of the callee from the function descriptor into r2.
4176       //   4. Load the environment pointer from the function descriptor into
4177       //      r11.
4178       //   5. Branch to the function entry point address.
4179       //   6. On return of the callee, the TOC of the caller needs to be
4180       //      restored (this is done in FinishCall()).
4181       //
4182       // The loads are scheduled at the beginning of the call sequence, and the
4183       // register copies are flagged together to ensure that no other
4184       // operations can be scheduled in between. E.g. without flagging the
4185       // copies together, a TOC access in the caller could be scheduled between
4186       // the assignment of the callee TOC and the branch to the callee, which
4187       // results in the TOC access going through the TOC of the callee instead
4188       // of going through the TOC of the caller, which leads to incorrect code.
4189
4190       // Load the address of the function entry point from the function
4191       // descriptor.
4192       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4193       if (LDChain.getValueType() == MVT::Glue)
4194         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4195
4196       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4197
4198       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4199       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4200                                         false, false, LoadsInv, 8);
4201
4202       // Load environment pointer into r11.
4203       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4204       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4205       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4206                                        MPI.getWithOffset(16), false, false,
4207                                        LoadsInv, 8);
4208
4209       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4210       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4211       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4212                                    MPI.getWithOffset(8), false, false,
4213                                    LoadsInv, 8);
4214
4215       setUsesTOCBasePtr(DAG);
4216       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4217                                         InFlag);
4218       Chain = TOCVal.getValue(0);
4219       InFlag = TOCVal.getValue(1);
4220
4221       // If the function call has an explicit 'nest' parameter, it takes the
4222       // place of the environment pointer.
4223       if (!hasNest) {
4224         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4225                                           InFlag);
4226
4227         Chain = EnvVal.getValue(0);
4228         InFlag = EnvVal.getValue(1);
4229       }
4230
4231       MTCTROps[0] = Chain;
4232       MTCTROps[1] = LoadFuncPtr;
4233       MTCTROps[2] = InFlag;
4234     }
4235
4236     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4237                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4238     InFlag = Chain.getValue(1);
4239
4240     NodeTys.clear();
4241     NodeTys.push_back(MVT::Other);
4242     NodeTys.push_back(MVT::Glue);
4243     Ops.push_back(Chain);
4244     CallOpc = PPCISD::BCTRL;
4245     Callee.setNode(nullptr);
4246     // Add use of X11 (holding environment pointer)
4247     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4248       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4249     // Add CTR register as callee so a bctr can be emitted later.
4250     if (isTailCall)
4251       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4252   }
4253
4254   // If this is a direct call, pass the chain and the callee.
4255   if (Callee.getNode()) {
4256     Ops.push_back(Chain);
4257     Ops.push_back(Callee);
4258   }
4259   // If this is a tail call add stack pointer delta.
4260   if (isTailCall)
4261     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4262
4263   // Add argument registers to the end of the list so that they are known live
4264   // into the call.
4265   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4266     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4267                                   RegsToPass[i].second.getValueType()));
4268
4269   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4270   // into the call.
4271   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4272     setUsesTOCBasePtr(DAG);
4273     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4274   }
4275
4276   return CallOpc;
4277 }
4278
4279 static
4280 bool isLocalCall(const SDValue &Callee)
4281 {
4282   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4283     return G->getGlobal()->isStrongDefinitionForLinker();
4284   return false;
4285 }
4286
4287 SDValue
4288 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4289                                    CallingConv::ID CallConv, bool isVarArg,
4290                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4291                                    SDLoc dl, SelectionDAG &DAG,
4292                                    SmallVectorImpl<SDValue> &InVals) const {
4293
4294   SmallVector<CCValAssign, 16> RVLocs;
4295   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4296                     *DAG.getContext());
4297   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4298
4299   // Copy all of the result registers out of their specified physreg.
4300   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4301     CCValAssign &VA = RVLocs[i];
4302     assert(VA.isRegLoc() && "Can only return in registers!");
4303
4304     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4305                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4306     Chain = Val.getValue(1);
4307     InFlag = Val.getValue(2);
4308
4309     switch (VA.getLocInfo()) {
4310     default: llvm_unreachable("Unknown loc info!");
4311     case CCValAssign::Full: break;
4312     case CCValAssign::AExt:
4313       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4314       break;
4315     case CCValAssign::ZExt:
4316       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4317                         DAG.getValueType(VA.getValVT()));
4318       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4319       break;
4320     case CCValAssign::SExt:
4321       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4322                         DAG.getValueType(VA.getValVT()));
4323       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4324       break;
4325     }
4326
4327     InVals.push_back(Val);
4328   }
4329
4330   return Chain;
4331 }
4332
4333 SDValue
4334 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4335                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4336                               bool hasNest, SelectionDAG &DAG,
4337                               SmallVector<std::pair<unsigned, SDValue>, 8>
4338                                 &RegsToPass,
4339                               SDValue InFlag, SDValue Chain,
4340                               SDValue CallSeqStart, SDValue &Callee,
4341                               int SPDiff, unsigned NumBytes,
4342                               const SmallVectorImpl<ISD::InputArg> &Ins,
4343                               SmallVectorImpl<SDValue> &InVals,
4344                               ImmutableCallSite *CS) const {
4345
4346   std::vector<EVT> NodeTys;
4347   SmallVector<SDValue, 8> Ops;
4348   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4349                                  SPDiff, isTailCall, IsPatchPoint, hasNest,
4350                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4351
4352   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4353   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4354     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4355
4356   // When performing tail call optimization the callee pops its arguments off
4357   // the stack. Account for this here so these bytes can be pushed back on in
4358   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4359   int BytesCalleePops =
4360     (CallConv == CallingConv::Fast &&
4361      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4362
4363   // Add a register mask operand representing the call-preserved registers.
4364   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4365   const uint32_t *Mask =
4366       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4367   assert(Mask && "Missing call preserved mask for calling convention");
4368   Ops.push_back(DAG.getRegisterMask(Mask));
4369
4370   if (InFlag.getNode())
4371     Ops.push_back(InFlag);
4372
4373   // Emit tail call.
4374   if (isTailCall) {
4375     assert(((Callee.getOpcode() == ISD::Register &&
4376              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4377             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4378             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4379             isa<ConstantSDNode>(Callee)) &&
4380     "Expecting an global address, external symbol, absolute value or register");
4381
4382     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4383     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4384   }
4385
4386   // Add a NOP immediately after the branch instruction when using the 64-bit
4387   // SVR4 ABI. At link time, if caller and callee are in a different module and
4388   // thus have a different TOC, the call will be replaced with a call to a stub
4389   // function which saves the current TOC, loads the TOC of the callee and
4390   // branches to the callee. The NOP will be replaced with a load instruction
4391   // which restores the TOC of the caller from the TOC save slot of the current
4392   // stack frame. If caller and callee belong to the same module (and have the
4393   // same TOC), the NOP will remain unchanged.
4394
4395   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4396       !IsPatchPoint) {
4397     if (CallOpc == PPCISD::BCTRL) {
4398       // This is a call through a function pointer.
4399       // Restore the caller TOC from the save area into R2.
4400       // See PrepareCall() for more information about calls through function
4401       // pointers in the 64-bit SVR4 ABI.
4402       // We are using a target-specific load with r2 hard coded, because the
4403       // result of a target-independent load would never go directly into r2,
4404       // since r2 is a reserved register (which prevents the register allocator
4405       // from allocating it), resulting in an additional register being
4406       // allocated and an unnecessary move instruction being generated.
4407       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4408
4409       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4410       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4411       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4412       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4413       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4414
4415       // The address needs to go after the chain input but before the flag (or
4416       // any other variadic arguments).
4417       Ops.insert(std::next(Ops.begin()), AddTOC);
4418     } else if ((CallOpc == PPCISD::CALL) &&
4419                (!isLocalCall(Callee) ||
4420                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4421       // Otherwise insert NOP for non-local calls.
4422       CallOpc = PPCISD::CALL_NOP;
4423   }
4424
4425   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4426   InFlag = Chain.getValue(1);
4427
4428   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4429                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4430                              InFlag, dl);
4431   if (!Ins.empty())
4432     InFlag = Chain.getValue(1);
4433
4434   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4435                          Ins, dl, DAG, InVals);
4436 }
4437
4438 SDValue
4439 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4440                              SmallVectorImpl<SDValue> &InVals) const {
4441   SelectionDAG &DAG                     = CLI.DAG;
4442   SDLoc &dl                             = CLI.DL;
4443   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4444   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4445   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4446   SDValue Chain                         = CLI.Chain;
4447   SDValue Callee                        = CLI.Callee;
4448   bool &isTailCall                      = CLI.IsTailCall;
4449   CallingConv::ID CallConv              = CLI.CallConv;
4450   bool isVarArg                         = CLI.IsVarArg;
4451   bool IsPatchPoint                     = CLI.IsPatchPoint;
4452   ImmutableCallSite *CS                 = CLI.CS;
4453
4454   if (isTailCall)
4455     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4456                                                    Ins, DAG);
4457
4458   if (!isTailCall && CS && CS->isMustTailCall())
4459     report_fatal_error("failed to perform tail call elimination on a call "
4460                        "site marked musttail");
4461
4462   if (Subtarget.isSVR4ABI()) {
4463     if (Subtarget.isPPC64())
4464       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4465                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4466                               dl, DAG, InVals, CS);
4467     else
4468       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4469                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4470                               dl, DAG, InVals, CS);
4471   }
4472
4473   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4474                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4475                           dl, DAG, InVals, CS);
4476 }
4477
4478 SDValue
4479 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4480                                     CallingConv::ID CallConv, bool isVarArg,
4481                                     bool isTailCall, bool IsPatchPoint,
4482                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4483                                     const SmallVectorImpl<SDValue> &OutVals,
4484                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4485                                     SDLoc dl, SelectionDAG &DAG,
4486                                     SmallVectorImpl<SDValue> &InVals,
4487                                     ImmutableCallSite *CS) const {
4488   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4489   // of the 32-bit SVR4 ABI stack frame layout.
4490
4491   assert((CallConv == CallingConv::C ||
4492           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4493
4494   unsigned PtrByteSize = 4;
4495
4496   MachineFunction &MF = DAG.getMachineFunction();
4497
4498   // Mark this function as potentially containing a function that contains a
4499   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4500   // and restoring the callers stack pointer in this functions epilog. This is
4501   // done because by tail calling the called function might overwrite the value
4502   // in this function's (MF) stack pointer stack slot 0(SP).
4503   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4504       CallConv == CallingConv::Fast)
4505     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4506
4507   // Count how many bytes are to be pushed on the stack, including the linkage
4508   // area, parameter list area and the part of the local variable space which
4509   // contains copies of aggregates which are passed by value.
4510
4511   // Assign locations to all of the outgoing arguments.
4512   SmallVector<CCValAssign, 16> ArgLocs;
4513   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4514                  *DAG.getContext());
4515
4516   // Reserve space for the linkage area on the stack.
4517   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4518                        PtrByteSize);
4519
4520   if (isVarArg) {
4521     // Handle fixed and variable vector arguments differently.
4522     // Fixed vector arguments go into registers as long as registers are
4523     // available. Variable vector arguments always go into memory.
4524     unsigned NumArgs = Outs.size();
4525
4526     for (unsigned i = 0; i != NumArgs; ++i) {
4527       MVT ArgVT = Outs[i].VT;
4528       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4529       bool Result;
4530
4531       if (Outs[i].IsFixed) {
4532         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4533                                CCInfo);
4534       } else {
4535         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4536                                       ArgFlags, CCInfo);
4537       }
4538
4539       if (Result) {
4540 #ifndef NDEBUG
4541         errs() << "Call operand #" << i << " has unhandled type "
4542              << EVT(ArgVT).getEVTString() << "\n";
4543 #endif
4544         llvm_unreachable(nullptr);
4545       }
4546     }
4547   } else {
4548     // All arguments are treated the same.
4549     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4550   }
4551
4552   // Assign locations to all of the outgoing aggregate by value arguments.
4553   SmallVector<CCValAssign, 16> ByValArgLocs;
4554   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4555                       ByValArgLocs, *DAG.getContext());
4556
4557   // Reserve stack space for the allocations in CCInfo.
4558   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4559
4560   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4561
4562   // Size of the linkage area, parameter list area and the part of the local
4563   // space variable where copies of aggregates which are passed by value are
4564   // stored.
4565   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4566
4567   // Calculate by how many bytes the stack has to be adjusted in case of tail
4568   // call optimization.
4569   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4570
4571   // Adjust the stack pointer for the new arguments...
4572   // These operations are automatically eliminated by the prolog/epilog pass
4573   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4574                                dl);
4575   SDValue CallSeqStart = Chain;
4576
4577   // Load the return address and frame pointer so it can be moved somewhere else
4578   // later.
4579   SDValue LROp, FPOp;
4580   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4581                                        dl);
4582
4583   // Set up a copy of the stack pointer for use loading and storing any
4584   // arguments that may not fit in the registers available for argument
4585   // passing.
4586   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4587
4588   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4589   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4590   SmallVector<SDValue, 8> MemOpChains;
4591
4592   bool seenFloatArg = false;
4593   // Walk the register/memloc assignments, inserting copies/loads.
4594   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4595        i != e;
4596        ++i) {
4597     CCValAssign &VA = ArgLocs[i];
4598     SDValue Arg = OutVals[i];
4599     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4600
4601     if (Flags.isByVal()) {
4602       // Argument is an aggregate which is passed by value, thus we need to
4603       // create a copy of it in the local variable space of the current stack
4604       // frame (which is the stack frame of the caller) and pass the address of
4605       // this copy to the callee.
4606       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4607       CCValAssign &ByValVA = ByValArgLocs[j++];
4608       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4609
4610       // Memory reserved in the local variable space of the callers stack frame.
4611       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4612
4613       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4614       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4615                            StackPtr, PtrOff);
4616
4617       // Create a copy of the argument in the local area of the current
4618       // stack frame.
4619       SDValue MemcpyCall =
4620         CreateCopyOfByValArgument(Arg, PtrOff,
4621                                   CallSeqStart.getNode()->getOperand(0),
4622                                   Flags, DAG, dl);
4623
4624       // This must go outside the CALLSEQ_START..END.
4625       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4626                            CallSeqStart.getNode()->getOperand(1),
4627                            SDLoc(MemcpyCall));
4628       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4629                              NewCallSeqStart.getNode());
4630       Chain = CallSeqStart = NewCallSeqStart;
4631
4632       // Pass the address of the aggregate copy on the stack either in a
4633       // physical register or in the parameter list area of the current stack
4634       // frame to the callee.
4635       Arg = PtrOff;
4636     }
4637
4638     if (VA.isRegLoc()) {
4639       if (Arg.getValueType() == MVT::i1)
4640         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4641
4642       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4643       // Put argument in a physical register.
4644       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4645     } else {
4646       // Put argument in the parameter list area of the current stack frame.
4647       assert(VA.isMemLoc());
4648       unsigned LocMemOffset = VA.getLocMemOffset();
4649
4650       if (!isTailCall) {
4651         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4652         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4653                              StackPtr, PtrOff);
4654
4655         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4656                                            MachinePointerInfo(),
4657                                            false, false, 0));
4658       } else {
4659         // Calculate and remember argument location.
4660         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4661                                  TailCallArguments);
4662       }
4663     }
4664   }
4665
4666   if (!MemOpChains.empty())
4667     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4668
4669   // Build a sequence of copy-to-reg nodes chained together with token chain
4670   // and flag operands which copy the outgoing args into the appropriate regs.
4671   SDValue InFlag;
4672   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4673     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4674                              RegsToPass[i].second, InFlag);
4675     InFlag = Chain.getValue(1);
4676   }
4677
4678   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4679   // registers.
4680   if (isVarArg) {
4681     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4682     SDValue Ops[] = { Chain, InFlag };
4683
4684     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4685                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4686
4687     InFlag = Chain.getValue(1);
4688   }
4689
4690   if (isTailCall)
4691     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4692                     false, TailCallArguments);
4693
4694   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
4695                     /* unused except on PPC64 ELFv1 */ false, DAG,
4696                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4697                     NumBytes, Ins, InVals, CS);
4698 }
4699
4700 // Copy an argument into memory, being careful to do this outside the
4701 // call sequence for the call to which the argument belongs.
4702 SDValue
4703 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4704                                               SDValue CallSeqStart,
4705                                               ISD::ArgFlagsTy Flags,
4706                                               SelectionDAG &DAG,
4707                                               SDLoc dl) const {
4708   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4709                         CallSeqStart.getNode()->getOperand(0),
4710                         Flags, DAG, dl);
4711   // The MEMCPY must go outside the CALLSEQ_START..END.
4712   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4713                              CallSeqStart.getNode()->getOperand(1),
4714                              SDLoc(MemcpyCall));
4715   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4716                          NewCallSeqStart.getNode());
4717   return NewCallSeqStart;
4718 }
4719
4720 SDValue
4721 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4722                                     CallingConv::ID CallConv, bool isVarArg,
4723                                     bool isTailCall, bool IsPatchPoint,
4724                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4725                                     const SmallVectorImpl<SDValue> &OutVals,
4726                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4727                                     SDLoc dl, SelectionDAG &DAG,
4728                                     SmallVectorImpl<SDValue> &InVals,
4729                                     ImmutableCallSite *CS) const {
4730
4731   bool isELFv2ABI = Subtarget.isELFv2ABI();
4732   bool isLittleEndian = Subtarget.isLittleEndian();
4733   unsigned NumOps = Outs.size();
4734   bool hasNest = false;
4735
4736   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4737   unsigned PtrByteSize = 8;
4738
4739   MachineFunction &MF = DAG.getMachineFunction();
4740
4741   // Mark this function as potentially containing a function that contains a
4742   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4743   // and restoring the callers stack pointer in this functions epilog. This is
4744   // done because by tail calling the called function might overwrite the value
4745   // in this function's (MF) stack pointer stack slot 0(SP).
4746   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4747       CallConv == CallingConv::Fast)
4748     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4749
4750   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4751          "fastcc not supported on varargs functions");
4752
4753   // Count how many bytes are to be pushed on the stack, including the linkage
4754   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4755   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4756   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4757   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4758   unsigned NumBytes = LinkageSize;
4759   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4760   unsigned &QFPR_idx = FPR_idx;
4761
4762   static const MCPhysReg GPR[] = {
4763     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4764     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4765   };
4766   static const MCPhysReg VR[] = {
4767     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4768     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4769   };
4770   static const MCPhysReg VSRH[] = {
4771     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4772     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4773   };
4774
4775   const unsigned NumGPRs = array_lengthof(GPR);
4776   const unsigned NumFPRs = 13;
4777   const unsigned NumVRs  = array_lengthof(VR);
4778   const unsigned NumQFPRs = NumFPRs;
4779
4780   // When using the fast calling convention, we don't provide backing for
4781   // arguments that will be in registers.
4782   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4783
4784   // Add up all the space actually used.
4785   for (unsigned i = 0; i != NumOps; ++i) {
4786     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4787     EVT ArgVT = Outs[i].VT;
4788     EVT OrigVT = Outs[i].ArgVT;
4789
4790     if (Flags.isNest())
4791       continue;
4792
4793     if (CallConv == CallingConv::Fast) {
4794       if (Flags.isByVal())
4795         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4796       else
4797         switch (ArgVT.getSimpleVT().SimpleTy) {
4798         default: llvm_unreachable("Unexpected ValueType for argument!");
4799         case MVT::i1:
4800         case MVT::i32:
4801         case MVT::i64:
4802           if (++NumGPRsUsed <= NumGPRs)
4803             continue;
4804           break;
4805         case MVT::v4i32:
4806         case MVT::v8i16:
4807         case MVT::v16i8:
4808         case MVT::v2f64:
4809         case MVT::v2i64:
4810         case MVT::v1i128:
4811           if (++NumVRsUsed <= NumVRs)
4812             continue;
4813           break;
4814         case MVT::v4f32:
4815           // When using QPX, this is handled like a FP register, otherwise, it
4816           // is an Altivec register.
4817           if (Subtarget.hasQPX()) {
4818             if (++NumFPRsUsed <= NumFPRs)
4819               continue;
4820           } else {
4821             if (++NumVRsUsed <= NumVRs)
4822               continue;
4823           }
4824           break;
4825         case MVT::f32:
4826         case MVT::f64:
4827         case MVT::v4f64: // QPX
4828         case MVT::v4i1:  // QPX
4829           if (++NumFPRsUsed <= NumFPRs)
4830             continue;
4831           break;
4832         }
4833     }
4834
4835     /* Respect alignment of argument on the stack.  */
4836     unsigned Align =
4837       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4838     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4839
4840     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4841     if (Flags.isInConsecutiveRegsLast())
4842       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4843   }
4844
4845   unsigned NumBytesActuallyUsed = NumBytes;
4846
4847   // The prolog code of the callee may store up to 8 GPR argument registers to
4848   // the stack, allowing va_start to index over them in memory if its varargs.
4849   // Because we cannot tell if this is needed on the caller side, we have to
4850   // conservatively assume that it is needed.  As such, make sure we have at
4851   // least enough stack space for the caller to store the 8 GPRs.
4852   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4853   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4854
4855   // Tail call needs the stack to be aligned.
4856   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4857       CallConv == CallingConv::Fast)
4858     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4859
4860   // Calculate by how many bytes the stack has to be adjusted in case of tail
4861   // call optimization.
4862   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4863
4864   // To protect arguments on the stack from being clobbered in a tail call,
4865   // force all the loads to happen before doing any other lowering.
4866   if (isTailCall)
4867     Chain = DAG.getStackArgumentTokenFactor(Chain);
4868
4869   // Adjust the stack pointer for the new arguments...
4870   // These operations are automatically eliminated by the prolog/epilog pass
4871   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4872                                dl);
4873   SDValue CallSeqStart = Chain;
4874
4875   // Load the return address and frame pointer so it can be move somewhere else
4876   // later.
4877   SDValue LROp, FPOp;
4878   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4879                                        dl);
4880
4881   // Set up a copy of the stack pointer for use loading and storing any
4882   // arguments that may not fit in the registers available for argument
4883   // passing.
4884   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4885
4886   // Figure out which arguments are going to go in registers, and which in
4887   // memory.  Also, if this is a vararg function, floating point operations
4888   // must be stored to our stack, and loaded into integer regs as well, if
4889   // any integer regs are available for argument passing.
4890   unsigned ArgOffset = LinkageSize;
4891
4892   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4893   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4894
4895   SmallVector<SDValue, 8> MemOpChains;
4896   for (unsigned i = 0; i != NumOps; ++i) {
4897     SDValue Arg = OutVals[i];
4898     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4899     EVT ArgVT = Outs[i].VT;
4900     EVT OrigVT = Outs[i].ArgVT;
4901
4902     // PtrOff will be used to store the current argument to the stack if a
4903     // register cannot be found for it.
4904     SDValue PtrOff;
4905
4906     // We re-align the argument offset for each argument, except when using the
4907     // fast calling convention, when we need to make sure we do that only when
4908     // we'll actually use a stack slot.
4909     auto ComputePtrOff = [&]() {
4910       /* Respect alignment of argument on the stack.  */
4911       unsigned Align =
4912         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4913       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4914
4915       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4916
4917       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4918     };
4919
4920     if (CallConv != CallingConv::Fast) {
4921       ComputePtrOff();
4922
4923       /* Compute GPR index associated with argument offset.  */
4924       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4925       GPR_idx = std::min(GPR_idx, NumGPRs);
4926     }
4927
4928     // Promote integers to 64-bit values.
4929     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4930       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4931       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4932       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4933     }
4934
4935     // FIXME memcpy is used way more than necessary.  Correctness first.
4936     // Note: "by value" is code for passing a structure by value, not
4937     // basic types.
4938     if (Flags.isByVal()) {
4939       // Note: Size includes alignment padding, so
4940       //   struct x { short a; char b; }
4941       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4942       // These are the proper values we need for right-justifying the
4943       // aggregate in a parameter register.
4944       unsigned Size = Flags.getByValSize();
4945
4946       // An empty aggregate parameter takes up no storage and no
4947       // registers.
4948       if (Size == 0)
4949         continue;
4950
4951       if (CallConv == CallingConv::Fast)
4952         ComputePtrOff();
4953
4954       // All aggregates smaller than 8 bytes must be passed right-justified.
4955       if (Size==1 || Size==2 || Size==4) {
4956         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4957         if (GPR_idx != NumGPRs) {
4958           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4959                                         MachinePointerInfo(), VT,
4960                                         false, false, false, 0);
4961           MemOpChains.push_back(Load.getValue(1));
4962           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4963
4964           ArgOffset += PtrByteSize;
4965           continue;
4966         }
4967       }
4968
4969       if (GPR_idx == NumGPRs && Size < 8) {
4970         SDValue AddPtr = PtrOff;
4971         if (!isLittleEndian) {
4972           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4973                                           PtrOff.getValueType());
4974           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4975         }
4976         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4977                                                           CallSeqStart,
4978                                                           Flags, DAG, dl);
4979         ArgOffset += PtrByteSize;
4980         continue;
4981       }
4982       // Copy entire object into memory.  There are cases where gcc-generated
4983       // code assumes it is there, even if it could be put entirely into
4984       // registers.  (This is not what the doc says.)
4985
4986       // FIXME: The above statement is likely due to a misunderstanding of the
4987       // documents.  All arguments must be copied into the parameter area BY
4988       // THE CALLEE in the event that the callee takes the address of any
4989       // formal argument.  That has not yet been implemented.  However, it is
4990       // reasonable to use the stack area as a staging area for the register
4991       // load.
4992
4993       // Skip this for small aggregates, as we will use the same slot for a
4994       // right-justified copy, below.
4995       if (Size >= 8)
4996         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4997                                                           CallSeqStart,
4998                                                           Flags, DAG, dl);
4999
5000       // When a register is available, pass a small aggregate right-justified.
5001       if (Size < 8 && GPR_idx != NumGPRs) {
5002         // The easiest way to get this right-justified in a register
5003         // is to copy the structure into the rightmost portion of a
5004         // local variable slot, then load the whole slot into the
5005         // register.
5006         // FIXME: The memcpy seems to produce pretty awful code for
5007         // small aggregates, particularly for packed ones.
5008         // FIXME: It would be preferable to use the slot in the
5009         // parameter save area instead of a new local variable.
5010         SDValue AddPtr = PtrOff;
5011         if (!isLittleEndian) {
5012           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5013           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5014         }
5015         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5016                                                           CallSeqStart,
5017                                                           Flags, DAG, dl);
5018
5019         // Load the slot into the register.
5020         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
5021                                    MachinePointerInfo(),
5022                                    false, false, false, 0);
5023         MemOpChains.push_back(Load.getValue(1));
5024         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5025
5026         // Done with this argument.
5027         ArgOffset += PtrByteSize;
5028         continue;
5029       }
5030
5031       // For aggregates larger than PtrByteSize, copy the pieces of the
5032       // object that fit into registers from the parameter save area.
5033       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5034         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5035         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5036         if (GPR_idx != NumGPRs) {
5037           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5038                                      MachinePointerInfo(),
5039                                      false, false, false, 0);
5040           MemOpChains.push_back(Load.getValue(1));
5041           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5042           ArgOffset += PtrByteSize;
5043         } else {
5044           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5045           break;
5046         }
5047       }
5048       continue;
5049     }
5050
5051     switch (Arg.getSimpleValueType().SimpleTy) {
5052     default: llvm_unreachable("Unexpected ValueType for argument!");
5053     case MVT::i1:
5054     case MVT::i32:
5055     case MVT::i64:
5056       if (Flags.isNest()) {
5057         // The 'nest' parameter, if any, is passed in R11.
5058         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5059         hasNest = true;
5060         break;
5061       }
5062
5063       // These can be scalar arguments or elements of an integer array type
5064       // passed directly.  Clang may use those instead of "byval" aggregate
5065       // types to avoid forcing arguments to memory unnecessarily.
5066       if (GPR_idx != NumGPRs) {
5067         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5068       } else {
5069         if (CallConv == CallingConv::Fast)
5070           ComputePtrOff();
5071
5072         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5073                          true, isTailCall, false, MemOpChains,
5074                          TailCallArguments, dl);
5075         if (CallConv == CallingConv::Fast)
5076           ArgOffset += PtrByteSize;
5077       }
5078       if (CallConv != CallingConv::Fast)
5079         ArgOffset += PtrByteSize;
5080       break;
5081     case MVT::f32:
5082     case MVT::f64: {
5083       // These can be scalar arguments or elements of a float array type
5084       // passed directly.  The latter are used to implement ELFv2 homogenous
5085       // float aggregates.
5086
5087       // Named arguments go into FPRs first, and once they overflow, the
5088       // remaining arguments go into GPRs and then the parameter save area.
5089       // Unnamed arguments for vararg functions always go to GPRs and
5090       // then the parameter save area.  For now, put all arguments to vararg
5091       // routines always in both locations (FPR *and* GPR or stack slot).
5092       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5093       bool NeededLoad = false;
5094
5095       // First load the argument into the next available FPR.
5096       if (FPR_idx != NumFPRs)
5097         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5098
5099       // Next, load the argument into GPR or stack slot if needed.
5100       if (!NeedGPROrStack)
5101         ;
5102       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5103         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5104         // once we support fp <-> gpr moves.
5105
5106         // In the non-vararg case, this can only ever happen in the
5107         // presence of f32 array types, since otherwise we never run
5108         // out of FPRs before running out of GPRs.
5109         SDValue ArgVal;
5110
5111         // Double values are always passed in a single GPR.
5112         if (Arg.getValueType() != MVT::f32) {
5113           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5114
5115         // Non-array float values are extended and passed in a GPR.
5116         } else if (!Flags.isInConsecutiveRegs()) {
5117           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5118           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5119
5120         // If we have an array of floats, we collect every odd element
5121         // together with its predecessor into one GPR.
5122         } else if (ArgOffset % PtrByteSize != 0) {
5123           SDValue Lo, Hi;
5124           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5125           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5126           if (!isLittleEndian)
5127             std::swap(Lo, Hi);
5128           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5129
5130         // The final element, if even, goes into the first half of a GPR.
5131         } else if (Flags.isInConsecutiveRegsLast()) {
5132           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5133           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5134           if (!isLittleEndian)
5135             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5136                                  DAG.getConstant(32, dl, MVT::i32));
5137
5138         // Non-final even elements are skipped; they will be handled
5139         // together the with subsequent argument on the next go-around.
5140         } else
5141           ArgVal = SDValue();
5142
5143         if (ArgVal.getNode())
5144           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5145       } else {
5146         if (CallConv == CallingConv::Fast)
5147           ComputePtrOff();
5148
5149         // Single-precision floating-point values are mapped to the
5150         // second (rightmost) word of the stack doubleword.
5151         if (Arg.getValueType() == MVT::f32 &&
5152             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5153           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5154           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5155         }
5156
5157         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5158                          true, isTailCall, false, MemOpChains,
5159                          TailCallArguments, dl);
5160
5161         NeededLoad = true;
5162       }
5163       // When passing an array of floats, the array occupies consecutive
5164       // space in the argument area; only round up to the next doubleword
5165       // at the end of the array.  Otherwise, each float takes 8 bytes.
5166       if (CallConv != CallingConv::Fast || NeededLoad) {
5167         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5168                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5169         if (Flags.isInConsecutiveRegsLast())
5170           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5171       }
5172       break;
5173     }
5174     case MVT::v4f32:
5175     case MVT::v4i32:
5176     case MVT::v8i16:
5177     case MVT::v16i8:
5178     case MVT::v2f64:
5179     case MVT::v2i64:
5180     case MVT::v1i128:
5181       if (!Subtarget.hasQPX()) {
5182       // These can be scalar arguments or elements of a vector array type
5183       // passed directly.  The latter are used to implement ELFv2 homogenous
5184       // vector aggregates.
5185
5186       // For a varargs call, named arguments go into VRs or on the stack as
5187       // usual; unnamed arguments always go to the stack or the corresponding
5188       // GPRs when within range.  For now, we always put the value in both
5189       // locations (or even all three).
5190       if (isVarArg) {
5191         // We could elide this store in the case where the object fits
5192         // entirely in R registers.  Maybe later.
5193         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5194                                      MachinePointerInfo(), false, false, 0);
5195         MemOpChains.push_back(Store);
5196         if (VR_idx != NumVRs) {
5197           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5198                                      MachinePointerInfo(),
5199                                      false, false, false, 0);
5200           MemOpChains.push_back(Load.getValue(1));
5201
5202           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5203                            Arg.getSimpleValueType() == MVT::v2i64) ?
5204                           VSRH[VR_idx] : VR[VR_idx];
5205           ++VR_idx;
5206
5207           RegsToPass.push_back(std::make_pair(VReg, Load));
5208         }
5209         ArgOffset += 16;
5210         for (unsigned i=0; i<16; i+=PtrByteSize) {
5211           if (GPR_idx == NumGPRs)
5212             break;
5213           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5214                                    DAG.getConstant(i, dl, PtrVT));
5215           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5216                                      false, false, false, 0);
5217           MemOpChains.push_back(Load.getValue(1));
5218           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5219         }
5220         break;
5221       }
5222
5223       // Non-varargs Altivec params go into VRs or on the stack.
5224       if (VR_idx != NumVRs) {
5225         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5226                          Arg.getSimpleValueType() == MVT::v2i64) ?
5227                         VSRH[VR_idx] : VR[VR_idx];
5228         ++VR_idx;
5229
5230         RegsToPass.push_back(std::make_pair(VReg, Arg));
5231       } else {
5232         if (CallConv == CallingConv::Fast)
5233           ComputePtrOff();
5234
5235         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5236                          true, isTailCall, true, MemOpChains,
5237                          TailCallArguments, dl);
5238         if (CallConv == CallingConv::Fast)
5239           ArgOffset += 16;
5240       }
5241
5242       if (CallConv != CallingConv::Fast)
5243         ArgOffset += 16;
5244       break;
5245       } // not QPX
5246
5247       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5248              "Invalid QPX parameter type");
5249
5250       /* fall through */
5251     case MVT::v4f64:
5252     case MVT::v4i1: {
5253       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5254       if (isVarArg) {
5255         // We could elide this store in the case where the object fits
5256         // entirely in R registers.  Maybe later.
5257         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5258                                      MachinePointerInfo(), false, false, 0);
5259         MemOpChains.push_back(Store);
5260         if (QFPR_idx != NumQFPRs) {
5261           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5262                                      Store, PtrOff, MachinePointerInfo(),
5263                                      false, false, false, 0);
5264           MemOpChains.push_back(Load.getValue(1));
5265           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5266         }
5267         ArgOffset += (IsF32 ? 16 : 32);
5268         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5269           if (GPR_idx == NumGPRs)
5270             break;
5271           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5272                                    DAG.getConstant(i, dl, PtrVT));
5273           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5274                                      false, false, false, 0);
5275           MemOpChains.push_back(Load.getValue(1));
5276           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5277         }
5278         break;
5279       }
5280
5281       // Non-varargs QPX params go into registers or on the stack.
5282       if (QFPR_idx != NumQFPRs) {
5283         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5284       } else {
5285         if (CallConv == CallingConv::Fast)
5286           ComputePtrOff();
5287
5288         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5289                          true, isTailCall, true, MemOpChains,
5290                          TailCallArguments, dl);
5291         if (CallConv == CallingConv::Fast)
5292           ArgOffset += (IsF32 ? 16 : 32);
5293       }
5294
5295       if (CallConv != CallingConv::Fast)
5296         ArgOffset += (IsF32 ? 16 : 32);
5297       break;
5298       }
5299     }
5300   }
5301
5302   assert(NumBytesActuallyUsed == ArgOffset);
5303   (void)NumBytesActuallyUsed;
5304
5305   if (!MemOpChains.empty())
5306     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5307
5308   // Check if this is an indirect call (MTCTR/BCTRL).
5309   // See PrepareCall() for more information about calls through function
5310   // pointers in the 64-bit SVR4 ABI.
5311   if (!isTailCall && !IsPatchPoint &&
5312       !isFunctionGlobalAddress(Callee) &&
5313       !isa<ExternalSymbolSDNode>(Callee)) {
5314     // Load r2 into a virtual register and store it to the TOC save area.
5315     setUsesTOCBasePtr(DAG);
5316     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5317     // TOC save area offset.
5318     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5319     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5320     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5321     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5322                          MachinePointerInfo::getStack(TOCSaveOffset),
5323                          false, false, 0);
5324     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5325     // This does not mean the MTCTR instruction must use R12; it's easier
5326     // to model this as an extra parameter, so do that.
5327     if (isELFv2ABI && !IsPatchPoint)
5328       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5329   }
5330
5331   // Build a sequence of copy-to-reg nodes chained together with token chain
5332   // and flag operands which copy the outgoing args into the appropriate regs.
5333   SDValue InFlag;
5334   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5335     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5336                              RegsToPass[i].second, InFlag);
5337     InFlag = Chain.getValue(1);
5338   }
5339
5340   if (isTailCall)
5341     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5342                     FPOp, true, TailCallArguments);
5343
5344   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5345                     hasNest, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5346                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
5347 }
5348
5349 SDValue
5350 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5351                                     CallingConv::ID CallConv, bool isVarArg,
5352                                     bool isTailCall, bool IsPatchPoint,
5353                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5354                                     const SmallVectorImpl<SDValue> &OutVals,
5355                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5356                                     SDLoc dl, SelectionDAG &DAG,
5357                                     SmallVectorImpl<SDValue> &InVals,
5358                                     ImmutableCallSite *CS) const {
5359
5360   unsigned NumOps = Outs.size();
5361
5362   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5363   bool isPPC64 = PtrVT == MVT::i64;
5364   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5365
5366   MachineFunction &MF = DAG.getMachineFunction();
5367
5368   // Mark this function as potentially containing a function that contains a
5369   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5370   // and restoring the callers stack pointer in this functions epilog. This is
5371   // done because by tail calling the called function might overwrite the value
5372   // in this function's (MF) stack pointer stack slot 0(SP).
5373   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5374       CallConv == CallingConv::Fast)
5375     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5376
5377   // Count how many bytes are to be pushed on the stack, including the linkage
5378   // area, and parameter passing area.  We start with 24/48 bytes, which is
5379   // prereserved space for [SP][CR][LR][3 x unused].
5380   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5381   unsigned NumBytes = LinkageSize;
5382
5383   // Add up all the space actually used.
5384   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5385   // they all go in registers, but we must reserve stack space for them for
5386   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5387   // assigned stack space in order, with padding so Altivec parameters are
5388   // 16-byte aligned.
5389   unsigned nAltivecParamsAtEnd = 0;
5390   for (unsigned i = 0; i != NumOps; ++i) {
5391     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5392     EVT ArgVT = Outs[i].VT;
5393     // Varargs Altivec parameters are padded to a 16 byte boundary.
5394     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5395         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5396         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5397       if (!isVarArg && !isPPC64) {
5398         // Non-varargs Altivec parameters go after all the non-Altivec
5399         // parameters; handle those later so we know how much padding we need.
5400         nAltivecParamsAtEnd++;
5401         continue;
5402       }
5403       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5404       NumBytes = ((NumBytes+15)/16)*16;
5405     }
5406     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5407   }
5408
5409   // Allow for Altivec parameters at the end, if needed.
5410   if (nAltivecParamsAtEnd) {
5411     NumBytes = ((NumBytes+15)/16)*16;
5412     NumBytes += 16*nAltivecParamsAtEnd;
5413   }
5414
5415   // The prolog code of the callee may store up to 8 GPR argument registers to
5416   // the stack, allowing va_start to index over them in memory if its varargs.
5417   // Because we cannot tell if this is needed on the caller side, we have to
5418   // conservatively assume that it is needed.  As such, make sure we have at
5419   // least enough stack space for the caller to store the 8 GPRs.
5420   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5421
5422   // Tail call needs the stack to be aligned.
5423   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5424       CallConv == CallingConv::Fast)
5425     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5426
5427   // Calculate by how many bytes the stack has to be adjusted in case of tail
5428   // call optimization.
5429   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5430
5431   // To protect arguments on the stack from being clobbered in a tail call,
5432   // force all the loads to happen before doing any other lowering.
5433   if (isTailCall)
5434     Chain = DAG.getStackArgumentTokenFactor(Chain);
5435
5436   // Adjust the stack pointer for the new arguments...
5437   // These operations are automatically eliminated by the prolog/epilog pass
5438   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5439                                dl);
5440   SDValue CallSeqStart = Chain;
5441
5442   // Load the return address and frame pointer so it can be move somewhere else
5443   // later.
5444   SDValue LROp, FPOp;
5445   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5446                                        dl);
5447
5448   // Set up a copy of the stack pointer for use loading and storing any
5449   // arguments that may not fit in the registers available for argument
5450   // passing.
5451   SDValue StackPtr;
5452   if (isPPC64)
5453     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5454   else
5455     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5456
5457   // Figure out which arguments are going to go in registers, and which in
5458   // memory.  Also, if this is a vararg function, floating point operations
5459   // must be stored to our stack, and loaded into integer regs as well, if
5460   // any integer regs are available for argument passing.
5461   unsigned ArgOffset = LinkageSize;
5462   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5463
5464   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5465     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5466     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5467   };
5468   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5469     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5470     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5471   };
5472   static const MCPhysReg VR[] = {
5473     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5474     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5475   };
5476   const unsigned NumGPRs = array_lengthof(GPR_32);
5477   const unsigned NumFPRs = 13;
5478   const unsigned NumVRs  = array_lengthof(VR);
5479
5480   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5481
5482   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5483   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5484
5485   SmallVector<SDValue, 8> MemOpChains;
5486   for (unsigned i = 0; i != NumOps; ++i) {
5487     SDValue Arg = OutVals[i];
5488     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5489
5490     // PtrOff will be used to store the current argument to the stack if a
5491     // register cannot be found for it.
5492     SDValue PtrOff;
5493
5494     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5495
5496     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5497
5498     // On PPC64, promote integers to 64-bit values.
5499     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5500       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5501       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5502       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5503     }
5504
5505     // FIXME memcpy is used way more than necessary.  Correctness first.
5506     // Note: "by value" is code for passing a structure by value, not
5507     // basic types.
5508     if (Flags.isByVal()) {
5509       unsigned Size = Flags.getByValSize();
5510       // Very small objects are passed right-justified.  Everything else is
5511       // passed left-justified.
5512       if (Size==1 || Size==2) {
5513         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5514         if (GPR_idx != NumGPRs) {
5515           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5516                                         MachinePointerInfo(), VT,
5517                                         false, false, false, 0);
5518           MemOpChains.push_back(Load.getValue(1));
5519           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5520
5521           ArgOffset += PtrByteSize;
5522         } else {
5523           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5524                                           PtrOff.getValueType());
5525           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5526           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5527                                                             CallSeqStart,
5528                                                             Flags, DAG, dl);
5529           ArgOffset += PtrByteSize;
5530         }
5531         continue;
5532       }
5533       // Copy entire object into memory.  There are cases where gcc-generated
5534       // code assumes it is there, even if it could be put entirely into
5535       // registers.  (This is not what the doc says.)
5536       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5537                                                         CallSeqStart,
5538                                                         Flags, DAG, dl);
5539
5540       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5541       // copy the pieces of the object that fit into registers from the
5542       // parameter save area.
5543       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5544         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5545         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5546         if (GPR_idx != NumGPRs) {
5547           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5548                                      MachinePointerInfo(),
5549                                      false, false, false, 0);
5550           MemOpChains.push_back(Load.getValue(1));
5551           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5552           ArgOffset += PtrByteSize;
5553         } else {
5554           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5555           break;
5556         }
5557       }
5558       continue;
5559     }
5560
5561     switch (Arg.getSimpleValueType().SimpleTy) {
5562     default: llvm_unreachable("Unexpected ValueType for argument!");
5563     case MVT::i1:
5564     case MVT::i32:
5565     case MVT::i64:
5566       if (GPR_idx != NumGPRs) {
5567         if (Arg.getValueType() == MVT::i1)
5568           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5569
5570         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5571       } else {
5572         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5573                          isPPC64, isTailCall, false, MemOpChains,
5574                          TailCallArguments, dl);
5575       }
5576       ArgOffset += PtrByteSize;
5577       break;
5578     case MVT::f32:
5579     case MVT::f64:
5580       if (FPR_idx != NumFPRs) {
5581         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5582
5583         if (isVarArg) {
5584           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5585                                        MachinePointerInfo(), false, false, 0);
5586           MemOpChains.push_back(Store);
5587
5588           // Float varargs are always shadowed in available integer registers
5589           if (GPR_idx != NumGPRs) {
5590             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5591                                        MachinePointerInfo(), false, false,
5592                                        false, 0);
5593             MemOpChains.push_back(Load.getValue(1));
5594             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5595           }
5596           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5597             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5598             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5599             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5600                                        MachinePointerInfo(),
5601                                        false, false, false, 0);
5602             MemOpChains.push_back(Load.getValue(1));
5603             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5604           }
5605         } else {
5606           // If we have any FPRs remaining, we may also have GPRs remaining.
5607           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5608           // GPRs.
5609           if (GPR_idx != NumGPRs)
5610             ++GPR_idx;
5611           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5612               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5613             ++GPR_idx;
5614         }
5615       } else
5616         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5617                          isPPC64, isTailCall, false, MemOpChains,
5618                          TailCallArguments, dl);
5619       if (isPPC64)
5620         ArgOffset += 8;
5621       else
5622         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5623       break;
5624     case MVT::v4f32:
5625     case MVT::v4i32:
5626     case MVT::v8i16:
5627     case MVT::v16i8:
5628       if (isVarArg) {
5629         // These go aligned on the stack, or in the corresponding R registers
5630         // when within range.  The Darwin PPC ABI doc claims they also go in
5631         // V registers; in fact gcc does this only for arguments that are
5632         // prototyped, not for those that match the ...  We do it for all
5633         // arguments, seems to work.
5634         while (ArgOffset % 16 !=0) {
5635           ArgOffset += PtrByteSize;
5636           if (GPR_idx != NumGPRs)
5637             GPR_idx++;
5638         }
5639         // We could elide this store in the case where the object fits
5640         // entirely in R registers.  Maybe later.
5641         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5642                              DAG.getConstant(ArgOffset, dl, PtrVT));
5643         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5644                                      MachinePointerInfo(), false, false, 0);
5645         MemOpChains.push_back(Store);
5646         if (VR_idx != NumVRs) {
5647           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5648                                      MachinePointerInfo(),
5649                                      false, false, false, 0);
5650           MemOpChains.push_back(Load.getValue(1));
5651           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5652         }
5653         ArgOffset += 16;
5654         for (unsigned i=0; i<16; i+=PtrByteSize) {
5655           if (GPR_idx == NumGPRs)
5656             break;
5657           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5658                                    DAG.getConstant(i, dl, PtrVT));
5659           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5660                                      false, false, false, 0);
5661           MemOpChains.push_back(Load.getValue(1));
5662           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5663         }
5664         break;
5665       }
5666
5667       // Non-varargs Altivec params generally go in registers, but have
5668       // stack space allocated at the end.
5669       if (VR_idx != NumVRs) {
5670         // Doesn't have GPR space allocated.
5671         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5672       } else if (nAltivecParamsAtEnd==0) {
5673         // We are emitting Altivec params in order.
5674         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5675                          isPPC64, isTailCall, true, MemOpChains,
5676                          TailCallArguments, dl);
5677         ArgOffset += 16;
5678       }
5679       break;
5680     }
5681   }
5682   // If all Altivec parameters fit in registers, as they usually do,
5683   // they get stack space following the non-Altivec parameters.  We
5684   // don't track this here because nobody below needs it.
5685   // If there are more Altivec parameters than fit in registers emit
5686   // the stores here.
5687   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5688     unsigned j = 0;
5689     // Offset is aligned; skip 1st 12 params which go in V registers.
5690     ArgOffset = ((ArgOffset+15)/16)*16;
5691     ArgOffset += 12*16;
5692     for (unsigned i = 0; i != NumOps; ++i) {
5693       SDValue Arg = OutVals[i];
5694       EVT ArgType = Outs[i].VT;
5695       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5696           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5697         if (++j > NumVRs) {
5698           SDValue PtrOff;
5699           // We are emitting Altivec params in order.
5700           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5701                            isPPC64, isTailCall, true, MemOpChains,
5702                            TailCallArguments, dl);
5703           ArgOffset += 16;
5704         }
5705       }
5706     }
5707   }
5708
5709   if (!MemOpChains.empty())
5710     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5711
5712   // On Darwin, R12 must contain the address of an indirect callee.  This does
5713   // not mean the MTCTR instruction must use R12; it's easier to model this as
5714   // an extra parameter, so do that.
5715   if (!isTailCall &&
5716       !isFunctionGlobalAddress(Callee) &&
5717       !isa<ExternalSymbolSDNode>(Callee) &&
5718       !isBLACompatibleAddress(Callee, DAG))
5719     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5720                                                    PPC::R12), Callee));
5721
5722   // Build a sequence of copy-to-reg nodes chained together with token chain
5723   // and flag operands which copy the outgoing args into the appropriate regs.
5724   SDValue InFlag;
5725   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5726     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5727                              RegsToPass[i].second, InFlag);
5728     InFlag = Chain.getValue(1);
5729   }
5730
5731   if (isTailCall)
5732     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5733                     FPOp, true, TailCallArguments);
5734
5735   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5736                     /* unused except on PPC64 ELFv1 */ false, DAG,
5737                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5738                     NumBytes, Ins, InVals, CS);
5739 }
5740
5741 bool
5742 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5743                                   MachineFunction &MF, bool isVarArg,
5744                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5745                                   LLVMContext &Context) const {
5746   SmallVector<CCValAssign, 16> RVLocs;
5747   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5748   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5749 }
5750
5751 SDValue
5752 PPCTargetLowering::LowerReturn(SDValue Chain,
5753                                CallingConv::ID CallConv, bool isVarArg,
5754                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5755                                const SmallVectorImpl<SDValue> &OutVals,
5756                                SDLoc dl, SelectionDAG &DAG) const {
5757
5758   SmallVector<CCValAssign, 16> RVLocs;
5759   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5760                  *DAG.getContext());
5761   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5762
5763   SDValue Flag;
5764   SmallVector<SDValue, 4> RetOps(1, Chain);
5765
5766   // Copy the result values into the output registers.
5767   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5768     CCValAssign &VA = RVLocs[i];
5769     assert(VA.isRegLoc() && "Can only return in registers!");
5770
5771     SDValue Arg = OutVals[i];
5772
5773     switch (VA.getLocInfo()) {
5774     default: llvm_unreachable("Unknown loc info!");
5775     case CCValAssign::Full: break;
5776     case CCValAssign::AExt:
5777       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5778       break;
5779     case CCValAssign::ZExt:
5780       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5781       break;
5782     case CCValAssign::SExt:
5783       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5784       break;
5785     }
5786
5787     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5788     Flag = Chain.getValue(1);
5789     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5790   }
5791
5792   RetOps[0] = Chain;  // Update chain.
5793
5794   // Add the flag if we have it.
5795   if (Flag.getNode())
5796     RetOps.push_back(Flag);
5797
5798   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5799 }
5800
5801 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5802                                    const PPCSubtarget &Subtarget) const {
5803   // When we pop the dynamic allocation we need to restore the SP link.
5804   SDLoc dl(Op);
5805
5806   // Get the corect type for pointers.
5807   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5808
5809   // Construct the stack pointer operand.
5810   bool isPPC64 = Subtarget.isPPC64();
5811   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5812   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5813
5814   // Get the operands for the STACKRESTORE.
5815   SDValue Chain = Op.getOperand(0);
5816   SDValue SaveSP = Op.getOperand(1);
5817
5818   // Load the old link SP.
5819   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5820                                    MachinePointerInfo(),
5821                                    false, false, false, 0);
5822
5823   // Restore the stack pointer.
5824   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5825
5826   // Store the old link SP.
5827   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5828                       false, false, 0);
5829 }
5830
5831
5832
5833 SDValue
5834 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5835   MachineFunction &MF = DAG.getMachineFunction();
5836   bool isPPC64 = Subtarget.isPPC64();
5837   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5838
5839   // Get current frame pointer save index.  The users of this index will be
5840   // primarily DYNALLOC instructions.
5841   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5842   int RASI = FI->getReturnAddrSaveIndex();
5843
5844   // If the frame pointer save index hasn't been defined yet.
5845   if (!RASI) {
5846     // Find out what the fix offset of the frame pointer save area.
5847     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5848     // Allocate the frame index for frame pointer save area.
5849     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5850     // Save the result.
5851     FI->setReturnAddrSaveIndex(RASI);
5852   }
5853   return DAG.getFrameIndex(RASI, PtrVT);
5854 }
5855
5856 SDValue
5857 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5858   MachineFunction &MF = DAG.getMachineFunction();
5859   bool isPPC64 = Subtarget.isPPC64();
5860   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5861
5862   // Get current frame pointer save index.  The users of this index will be
5863   // primarily DYNALLOC instructions.
5864   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5865   int FPSI = FI->getFramePointerSaveIndex();
5866
5867   // If the frame pointer save index hasn't been defined yet.
5868   if (!FPSI) {
5869     // Find out what the fix offset of the frame pointer save area.
5870     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5871     // Allocate the frame index for frame pointer save area.
5872     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5873     // Save the result.
5874     FI->setFramePointerSaveIndex(FPSI);
5875   }
5876   return DAG.getFrameIndex(FPSI, PtrVT);
5877 }
5878
5879 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5880                                          SelectionDAG &DAG,
5881                                          const PPCSubtarget &Subtarget) const {
5882   // Get the inputs.
5883   SDValue Chain = Op.getOperand(0);
5884   SDValue Size  = Op.getOperand(1);
5885   SDLoc dl(Op);
5886
5887   // Get the corect type for pointers.
5888   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5889   // Negate the size.
5890   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5891                                 DAG.getConstant(0, dl, PtrVT), Size);
5892   // Construct a node for the frame pointer save index.
5893   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5894   // Build a DYNALLOC node.
5895   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5896   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5897   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5898 }
5899
5900 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5901                                                SelectionDAG &DAG) const {
5902   SDLoc DL(Op);
5903   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5904                      DAG.getVTList(MVT::i32, MVT::Other),
5905                      Op.getOperand(0), Op.getOperand(1));
5906 }
5907
5908 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5909                                                 SelectionDAG &DAG) const {
5910   SDLoc DL(Op);
5911   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5912                      Op.getOperand(0), Op.getOperand(1));
5913 }
5914
5915 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5916   if (Op.getValueType().isVector())
5917     return LowerVectorLoad(Op, DAG);
5918
5919   assert(Op.getValueType() == MVT::i1 &&
5920          "Custom lowering only for i1 loads");
5921
5922   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5923
5924   SDLoc dl(Op);
5925   LoadSDNode *LD = cast<LoadSDNode>(Op);
5926
5927   SDValue Chain = LD->getChain();
5928   SDValue BasePtr = LD->getBasePtr();
5929   MachineMemOperand *MMO = LD->getMemOperand();
5930
5931   SDValue NewLD =
5932       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
5933                      BasePtr, MVT::i8, MMO);
5934   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5935
5936   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5937   return DAG.getMergeValues(Ops, dl);
5938 }
5939
5940 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5941   if (Op.getOperand(1).getValueType().isVector())
5942     return LowerVectorStore(Op, DAG);
5943
5944   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5945          "Custom lowering only for i1 stores");
5946
5947   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5948
5949   SDLoc dl(Op);
5950   StoreSDNode *ST = cast<StoreSDNode>(Op);
5951
5952   SDValue Chain = ST->getChain();
5953   SDValue BasePtr = ST->getBasePtr();
5954   SDValue Value = ST->getValue();
5955   MachineMemOperand *MMO = ST->getMemOperand();
5956
5957   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
5958                       Value);
5959   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5960 }
5961
5962 // FIXME: Remove this once the ANDI glue bug is fixed:
5963 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5964   assert(Op.getValueType() == MVT::i1 &&
5965          "Custom lowering only for i1 results");
5966
5967   SDLoc DL(Op);
5968   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5969                      Op.getOperand(0));
5970 }
5971
5972 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5973 /// possible.
5974 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5975   // Not FP? Not a fsel.
5976   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5977       !Op.getOperand(2).getValueType().isFloatingPoint())
5978     return Op;
5979
5980   // We might be able to do better than this under some circumstances, but in
5981   // general, fsel-based lowering of select is a finite-math-only optimization.
5982   // For more information, see section F.3 of the 2.06 ISA specification.
5983   if (!DAG.getTarget().Options.NoInfsFPMath ||
5984       !DAG.getTarget().Options.NoNaNsFPMath)
5985     return Op;
5986
5987   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5988
5989   EVT ResVT = Op.getValueType();
5990   EVT CmpVT = Op.getOperand(0).getValueType();
5991   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5992   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5993   SDLoc dl(Op);
5994
5995   // If the RHS of the comparison is a 0.0, we don't need to do the
5996   // subtraction at all.
5997   SDValue Sel1;
5998   if (isFloatingPointZero(RHS))
5999     switch (CC) {
6000     default: break;       // SETUO etc aren't handled by fsel.
6001     case ISD::SETNE:
6002       std::swap(TV, FV);
6003     case ISD::SETEQ:
6004       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6005         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6006       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6007       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6008         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6009       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6010                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6011     case ISD::SETULT:
6012     case ISD::SETLT:
6013       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6014     case ISD::SETOGE:
6015     case ISD::SETGE:
6016       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6017         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6018       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6019     case ISD::SETUGT:
6020     case ISD::SETGT:
6021       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6022     case ISD::SETOLE:
6023     case ISD::SETLE:
6024       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6025         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6026       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6027                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6028     }
6029
6030   SDValue Cmp;
6031   switch (CC) {
6032   default: break;       // SETUO etc aren't handled by fsel.
6033   case ISD::SETNE:
6034     std::swap(TV, FV);
6035   case ISD::SETEQ:
6036     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
6037     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6038       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6039     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6040     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6041       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6042     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6043                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6044   case ISD::SETULT:
6045   case ISD::SETLT:
6046     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
6047     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6048       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6049     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6050   case ISD::SETOGE:
6051   case ISD::SETGE:
6052     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
6053     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6054       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6055     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6056   case ISD::SETUGT:
6057   case ISD::SETGT:
6058     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
6059     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6060       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6061     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6062   case ISD::SETOLE:
6063   case ISD::SETLE:
6064     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
6065     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6066       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6067     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6068   }
6069   return Op;
6070 }
6071
6072 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6073                                                SelectionDAG &DAG,
6074                                                SDLoc dl) const {
6075   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6076   SDValue Src = Op.getOperand(0);
6077   if (Src.getValueType() == MVT::f32)
6078     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6079
6080   SDValue Tmp;
6081   switch (Op.getSimpleValueType().SimpleTy) {
6082   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6083   case MVT::i32:
6084     Tmp = DAG.getNode(
6085         Op.getOpcode() == ISD::FP_TO_SINT
6086             ? PPCISD::FCTIWZ
6087             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6088         dl, MVT::f64, Src);
6089     break;
6090   case MVT::i64:
6091     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6092            "i64 FP_TO_UINT is supported only with FPCVT");
6093     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6094                                                         PPCISD::FCTIDUZ,
6095                       dl, MVT::f64, Src);
6096     break;
6097   }
6098
6099   // Convert the FP value to an int value through memory.
6100   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6101     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6102   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6103   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6104   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
6105
6106   // Emit a store to the stack slot.
6107   SDValue Chain;
6108   if (i32Stack) {
6109     MachineFunction &MF = DAG.getMachineFunction();
6110     MachineMemOperand *MMO =
6111       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6112     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6113     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6114               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6115   } else
6116     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
6117                          MPI, false, false, 0);
6118
6119   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6120   // add in a bias.
6121   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6122     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6123                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6124     MPI = MPI.getWithOffset(4);
6125   }
6126
6127   RLI.Chain = Chain;
6128   RLI.Ptr = FIPtr;
6129   RLI.MPI = MPI;
6130 }
6131
6132 /// \brief Custom lowers floating point to integer conversions to use
6133 /// the direct move instructions available in ISA 2.07 to avoid the
6134 /// need for load/store combinations.
6135 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6136                                                     SelectionDAG &DAG,
6137                                                     SDLoc dl) const {
6138   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6139   SDValue Src = Op.getOperand(0);
6140
6141   if (Src.getValueType() == MVT::f32)
6142     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6143
6144   SDValue Tmp;
6145   switch (Op.getSimpleValueType().SimpleTy) {
6146   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6147   case MVT::i32:
6148     Tmp = DAG.getNode(
6149         Op.getOpcode() == ISD::FP_TO_SINT
6150             ? PPCISD::FCTIWZ
6151             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6152         dl, MVT::f64, Src);
6153     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6154     break;
6155   case MVT::i64:
6156     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6157            "i64 FP_TO_UINT is supported only with FPCVT");
6158     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6159                                                         PPCISD::FCTIDUZ,
6160                       dl, MVT::f64, Src);
6161     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6162     break;
6163   }
6164   return Tmp;
6165 }
6166
6167 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6168                                           SDLoc dl) const {
6169   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6170     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6171
6172   ReuseLoadInfo RLI;
6173   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6174
6175   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6176                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6177                      RLI.Ranges);
6178 }
6179
6180 // We're trying to insert a regular store, S, and then a load, L. If the
6181 // incoming value, O, is a load, we might just be able to have our load use the
6182 // address used by O. However, we don't know if anything else will store to
6183 // that address before we can load from it. To prevent this situation, we need
6184 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6185 // the same chain operand as O, we create a token factor from the chain results
6186 // of O and L, and we replace all uses of O's chain result with that token
6187 // factor (see spliceIntoChain below for this last part).
6188 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6189                                             ReuseLoadInfo &RLI,
6190                                             SelectionDAG &DAG,
6191                                             ISD::LoadExtType ET) const {
6192   SDLoc dl(Op);
6193   if (ET == ISD::NON_EXTLOAD &&
6194       (Op.getOpcode() == ISD::FP_TO_UINT ||
6195        Op.getOpcode() == ISD::FP_TO_SINT) &&
6196       isOperationLegalOrCustom(Op.getOpcode(),
6197                                Op.getOperand(0).getValueType())) {
6198
6199     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6200     return true;
6201   }
6202
6203   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6204   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6205       LD->isNonTemporal())
6206     return false;
6207   if (LD->getMemoryVT() != MemVT)
6208     return false;
6209
6210   RLI.Ptr = LD->getBasePtr();
6211   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6212     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6213            "Non-pre-inc AM on PPC?");
6214     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6215                           LD->getOffset());
6216   }
6217
6218   RLI.Chain = LD->getChain();
6219   RLI.MPI = LD->getPointerInfo();
6220   RLI.IsInvariant = LD->isInvariant();
6221   RLI.Alignment = LD->getAlignment();
6222   RLI.AAInfo = LD->getAAInfo();
6223   RLI.Ranges = LD->getRanges();
6224
6225   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6226   return true;
6227 }
6228
6229 // Given the head of the old chain, ResChain, insert a token factor containing
6230 // it and NewResChain, and make users of ResChain now be users of that token
6231 // factor.
6232 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6233                                         SDValue NewResChain,
6234                                         SelectionDAG &DAG) const {
6235   if (!ResChain)
6236     return;
6237
6238   SDLoc dl(NewResChain);
6239
6240   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6241                            NewResChain, DAG.getUNDEF(MVT::Other));
6242   assert(TF.getNode() != NewResChain.getNode() &&
6243          "A new TF really is required here");
6244
6245   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6246   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6247 }
6248
6249 /// \brief Custom lowers integer to floating point conversions to use
6250 /// the direct move instructions available in ISA 2.07 to avoid the
6251 /// need for load/store combinations.
6252 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6253                                                     SelectionDAG &DAG,
6254                                                     SDLoc dl) const {
6255   assert((Op.getValueType() == MVT::f32 ||
6256           Op.getValueType() == MVT::f64) &&
6257          "Invalid floating point type as target of conversion");
6258   assert(Subtarget.hasFPCVT() &&
6259          "Int to FP conversions with direct moves require FPCVT");
6260   SDValue FP;
6261   SDValue Src = Op.getOperand(0);
6262   bool SinglePrec = Op.getValueType() == MVT::f32;
6263   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6264   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6265   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6266                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6267
6268   if (WordInt) {
6269     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6270                      dl, MVT::f64, Src);
6271     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6272   }
6273   else {
6274     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6275     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6276   }
6277
6278   return FP;
6279 }
6280
6281 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6282                                           SelectionDAG &DAG) const {
6283   SDLoc dl(Op);
6284
6285   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6286     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6287       return SDValue();
6288
6289     SDValue Value = Op.getOperand(0);
6290     // The values are now known to be -1 (false) or 1 (true). To convert this
6291     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6292     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6293     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6294   
6295     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6296     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6297                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6298   
6299     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6300
6301     if (Op.getValueType() != MVT::v4f64)
6302       Value = DAG.getNode(ISD::FP_ROUND, dl,
6303                           Op.getValueType(), Value,
6304                           DAG.getIntPtrConstant(1, dl));
6305     return Value;
6306   }
6307
6308   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6309   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6310     return SDValue();
6311
6312   if (Op.getOperand(0).getValueType() == MVT::i1)
6313     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6314                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6315                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6316
6317   // If we have direct moves, we can do all the conversion, skip the store/load
6318   // however, without FPCVT we can't do most conversions.
6319   if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6320     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6321
6322   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6323          "UINT_TO_FP is supported only with FPCVT");
6324
6325   // If we have FCFIDS, then use it when converting to single-precision.
6326   // Otherwise, convert to double-precision and then round.
6327   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6328                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6329                                                             : PPCISD::FCFIDS)
6330                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6331                                                             : PPCISD::FCFID);
6332   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6333                   ? MVT::f32
6334                   : MVT::f64;
6335
6336   if (Op.getOperand(0).getValueType() == MVT::i64) {
6337     SDValue SINT = Op.getOperand(0);
6338     // When converting to single-precision, we actually need to convert
6339     // to double-precision first and then round to single-precision.
6340     // To avoid double-rounding effects during that operation, we have
6341     // to prepare the input operand.  Bits that might be truncated when
6342     // converting to double-precision are replaced by a bit that won't
6343     // be lost at this stage, but is below the single-precision rounding
6344     // position.
6345     //
6346     // However, if -enable-unsafe-fp-math is in effect, accept double
6347     // rounding to avoid the extra overhead.
6348     if (Op.getValueType() == MVT::f32 &&
6349         !Subtarget.hasFPCVT() &&
6350         !DAG.getTarget().Options.UnsafeFPMath) {
6351
6352       // Twiddle input to make sure the low 11 bits are zero.  (If this
6353       // is the case, we are guaranteed the value will fit into the 53 bit
6354       // mantissa of an IEEE double-precision value without rounding.)
6355       // If any of those low 11 bits were not zero originally, make sure
6356       // bit 12 (value 2048) is set instead, so that the final rounding
6357       // to single-precision gets the correct result.
6358       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6359                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6360       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6361                           Round, DAG.getConstant(2047, dl, MVT::i64));
6362       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6363       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6364                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6365
6366       // However, we cannot use that value unconditionally: if the magnitude
6367       // of the input value is small, the bit-twiddling we did above might
6368       // end up visibly changing the output.  Fortunately, in that case, we
6369       // don't need to twiddle bits since the original input will convert
6370       // exactly to double-precision floating-point already.  Therefore,
6371       // construct a conditional to use the original value if the top 11
6372       // bits are all sign-bit copies, and use the rounded value computed
6373       // above otherwise.
6374       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6375                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6376       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6377                          Cond, DAG.getConstant(1, dl, MVT::i64));
6378       Cond = DAG.getSetCC(dl, MVT::i32,
6379                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6380
6381       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6382     }
6383
6384     ReuseLoadInfo RLI;
6385     SDValue Bits;
6386
6387     MachineFunction &MF = DAG.getMachineFunction();
6388     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6389       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6390                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6391                          RLI.Ranges);
6392       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6393     } else if (Subtarget.hasLFIWAX() &&
6394                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6395       MachineMemOperand *MMO =
6396         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6397                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6398       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6399       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6400                                      DAG.getVTList(MVT::f64, MVT::Other),
6401                                      Ops, MVT::i32, MMO);
6402       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6403     } else if (Subtarget.hasFPCVT() &&
6404                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6405       MachineMemOperand *MMO =
6406         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6407                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6408       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6409       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6410                                      DAG.getVTList(MVT::f64, MVT::Other),
6411                                      Ops, MVT::i32, MMO);
6412       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6413     } else if (((Subtarget.hasLFIWAX() &&
6414                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6415                 (Subtarget.hasFPCVT() &&
6416                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6417                SINT.getOperand(0).getValueType() == MVT::i32) {
6418       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6419       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6420
6421       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6422       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6423
6424       SDValue Store =
6425         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6426                      MachinePointerInfo::getFixedStack(FrameIdx),
6427                      false, false, 0);
6428
6429       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6430              "Expected an i32 store");
6431
6432       RLI.Ptr = FIdx;
6433       RLI.Chain = Store;
6434       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6435       RLI.Alignment = 4;
6436
6437       MachineMemOperand *MMO =
6438         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6439                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6440       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6441       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6442                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6443                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6444                                      Ops, MVT::i32, MMO);
6445     } else
6446       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6447
6448     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6449
6450     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6451       FP = DAG.getNode(ISD::FP_ROUND, dl,
6452                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6453     return FP;
6454   }
6455
6456   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6457          "Unhandled INT_TO_FP type in custom expander!");
6458   // Since we only generate this in 64-bit mode, we can take advantage of
6459   // 64-bit registers.  In particular, sign extend the input value into the
6460   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6461   // then lfd it and fcfid it.
6462   MachineFunction &MF = DAG.getMachineFunction();
6463   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6464   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6465
6466   SDValue Ld;
6467   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6468     ReuseLoadInfo RLI;
6469     bool ReusingLoad;
6470     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6471                                             DAG))) {
6472       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6473       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6474
6475       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6476                                    MachinePointerInfo::getFixedStack(FrameIdx),
6477                                    false, false, 0);
6478
6479       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6480              "Expected an i32 store");
6481
6482       RLI.Ptr = FIdx;
6483       RLI.Chain = Store;
6484       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6485       RLI.Alignment = 4;
6486     }
6487
6488     MachineMemOperand *MMO =
6489       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6490                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6491     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6492     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6493                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6494                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6495                                  Ops, MVT::i32, MMO);
6496     if (ReusingLoad)
6497       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6498   } else {
6499     assert(Subtarget.isPPC64() &&
6500            "i32->FP without LFIWAX supported only on PPC64");
6501
6502     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6503     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6504
6505     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6506                                 Op.getOperand(0));
6507
6508     // STD the extended value into the stack slot.
6509     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6510                                  MachinePointerInfo::getFixedStack(FrameIdx),
6511                                  false, false, 0);
6512
6513     // Load the value as a double.
6514     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6515                      MachinePointerInfo::getFixedStack(FrameIdx),
6516                      false, false, false, 0);
6517   }
6518
6519   // FCFID it and return it.
6520   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6521   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6522     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6523                      DAG.getIntPtrConstant(0, dl));
6524   return FP;
6525 }
6526
6527 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6528                                             SelectionDAG &DAG) const {
6529   SDLoc dl(Op);
6530   /*
6531    The rounding mode is in bits 30:31 of FPSR, and has the following
6532    settings:
6533      00 Round to nearest
6534      01 Round to 0
6535      10 Round to +inf
6536      11 Round to -inf
6537
6538   FLT_ROUNDS, on the other hand, expects the following:
6539     -1 Undefined
6540      0 Round to 0
6541      1 Round to nearest
6542      2 Round to +inf
6543      3 Round to -inf
6544
6545   To perform the conversion, we do:
6546     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6547   */
6548
6549   MachineFunction &MF = DAG.getMachineFunction();
6550   EVT VT = Op.getValueType();
6551   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6552
6553   // Save FP Control Word to register
6554   EVT NodeTys[] = {
6555     MVT::f64,    // return register
6556     MVT::Glue    // unused in this context
6557   };
6558   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6559
6560   // Save FP register to stack slot
6561   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6562   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6563   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6564                                StackSlot, MachinePointerInfo(), false, false,0);
6565
6566   // Load FP Control Word from low 32 bits of stack slot.
6567   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6568   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6569   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6570                             false, false, false, 0);
6571
6572   // Transform as necessary
6573   SDValue CWD1 =
6574     DAG.getNode(ISD::AND, dl, MVT::i32,
6575                 CWD, DAG.getConstant(3, dl, MVT::i32));
6576   SDValue CWD2 =
6577     DAG.getNode(ISD::SRL, dl, MVT::i32,
6578                 DAG.getNode(ISD::AND, dl, MVT::i32,
6579                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6580                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6581                             DAG.getConstant(3, dl, MVT::i32)),
6582                 DAG.getConstant(1, dl, MVT::i32));
6583
6584   SDValue RetVal =
6585     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6586
6587   return DAG.getNode((VT.getSizeInBits() < 16 ?
6588                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6589 }
6590
6591 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6592   EVT VT = Op.getValueType();
6593   unsigned BitWidth = VT.getSizeInBits();
6594   SDLoc dl(Op);
6595   assert(Op.getNumOperands() == 3 &&
6596          VT == Op.getOperand(1).getValueType() &&
6597          "Unexpected SHL!");
6598
6599   // Expand into a bunch of logical ops.  Note that these ops
6600   // depend on the PPC behavior for oversized shift amounts.
6601   SDValue Lo = Op.getOperand(0);
6602   SDValue Hi = Op.getOperand(1);
6603   SDValue Amt = Op.getOperand(2);
6604   EVT AmtVT = Amt.getValueType();
6605
6606   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6607                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6608   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6609   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6610   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6611   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6612                              DAG.getConstant(-BitWidth, dl, AmtVT));
6613   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6614   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6615   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6616   SDValue OutOps[] = { OutLo, OutHi };
6617   return DAG.getMergeValues(OutOps, dl);
6618 }
6619
6620 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6621   EVT VT = Op.getValueType();
6622   SDLoc dl(Op);
6623   unsigned BitWidth = VT.getSizeInBits();
6624   assert(Op.getNumOperands() == 3 &&
6625          VT == Op.getOperand(1).getValueType() &&
6626          "Unexpected SRL!");
6627
6628   // Expand into a bunch of logical ops.  Note that these ops
6629   // depend on the PPC behavior for oversized shift amounts.
6630   SDValue Lo = Op.getOperand(0);
6631   SDValue Hi = Op.getOperand(1);
6632   SDValue Amt = Op.getOperand(2);
6633   EVT AmtVT = Amt.getValueType();
6634
6635   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6636                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6637   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6638   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6639   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6640   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6641                              DAG.getConstant(-BitWidth, dl, AmtVT));
6642   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6643   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6644   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6645   SDValue OutOps[] = { OutLo, OutHi };
6646   return DAG.getMergeValues(OutOps, dl);
6647 }
6648
6649 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6650   SDLoc dl(Op);
6651   EVT VT = Op.getValueType();
6652   unsigned BitWidth = VT.getSizeInBits();
6653   assert(Op.getNumOperands() == 3 &&
6654          VT == Op.getOperand(1).getValueType() &&
6655          "Unexpected SRA!");
6656
6657   // Expand into a bunch of logical ops, followed by a select_cc.
6658   SDValue Lo = Op.getOperand(0);
6659   SDValue Hi = Op.getOperand(1);
6660   SDValue Amt = Op.getOperand(2);
6661   EVT AmtVT = Amt.getValueType();
6662
6663   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6664                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6665   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6666   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6667   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6668   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6669                              DAG.getConstant(-BitWidth, dl, AmtVT));
6670   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6671   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6672   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6673                                   Tmp4, Tmp6, ISD::SETLE);
6674   SDValue OutOps[] = { OutLo, OutHi };
6675   return DAG.getMergeValues(OutOps, dl);
6676 }
6677
6678 //===----------------------------------------------------------------------===//
6679 // Vector related lowering.
6680 //
6681
6682 /// BuildSplatI - Build a canonical splati of Val with an element size of
6683 /// SplatSize.  Cast the result to VT.
6684 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6685                              SelectionDAG &DAG, SDLoc dl) {
6686   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6687
6688   static const MVT VTys[] = { // canonical VT to use for each size.
6689     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6690   };
6691
6692   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6693
6694   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6695   if (Val == -1)
6696     SplatSize = 1;
6697
6698   EVT CanonicalVT = VTys[SplatSize-1];
6699
6700   // Build a canonical splat for this value.
6701   SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6702   SmallVector<SDValue, 8> Ops;
6703   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6704   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6705   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6706 }
6707
6708 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6709 /// specified intrinsic ID.
6710 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6711                                 SelectionDAG &DAG, SDLoc dl,
6712                                 EVT DestVT = MVT::Other) {
6713   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6714   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6715                      DAG.getConstant(IID, dl, MVT::i32), Op);
6716 }
6717
6718 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6719 /// specified intrinsic ID.
6720 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6721                                 SelectionDAG &DAG, SDLoc dl,
6722                                 EVT DestVT = MVT::Other) {
6723   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6724   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6725                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6726 }
6727
6728 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6729 /// specified intrinsic ID.
6730 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6731                                 SDValue Op2, SelectionDAG &DAG,
6732                                 SDLoc dl, EVT DestVT = MVT::Other) {
6733   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6734   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6735                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6736 }
6737
6738
6739 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6740 /// amount.  The result has the specified value type.
6741 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6742                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6743   // Force LHS/RHS to be the right type.
6744   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6745   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6746
6747   int Ops[16];
6748   for (unsigned i = 0; i != 16; ++i)
6749     Ops[i] = i + Amt;
6750   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6751   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6752 }
6753
6754 // If this is a case we can't handle, return null and let the default
6755 // expansion code take care of it.  If we CAN select this case, and if it
6756 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6757 // this case more efficiently than a constant pool load, lower it to the
6758 // sequence of ops that should be used.
6759 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6760                                              SelectionDAG &DAG) const {
6761   SDLoc dl(Op);
6762   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6763   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6764
6765   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6766     // We first build an i32 vector, load it into a QPX register,
6767     // then convert it to a floating-point vector and compare it
6768     // to a zero vector to get the boolean result.
6769     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6770     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6771     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6772     EVT PtrVT = getPointerTy(DAG.getDataLayout());
6773     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6774
6775     assert(BVN->getNumOperands() == 4 &&
6776       "BUILD_VECTOR for v4i1 does not have 4 operands");
6777
6778     bool IsConst = true;
6779     for (unsigned i = 0; i < 4; ++i) {
6780       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6781       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6782         IsConst = false;
6783         break;
6784       }
6785     }
6786
6787     if (IsConst) {
6788       Constant *One =
6789         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6790       Constant *NegOne =
6791         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6792
6793       SmallVector<Constant*, 4> CV(4, NegOne);
6794       for (unsigned i = 0; i < 4; ++i) {
6795         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6796           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6797         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6798                    getConstantIntValue()->isZero())
6799           continue;
6800         else
6801           CV[i] = One;
6802       }
6803
6804       Constant *CP = ConstantVector::get(CV);
6805       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
6806                                           16 /* alignment */);
6807
6808       SmallVector<SDValue, 2> Ops;
6809       Ops.push_back(DAG.getEntryNode());
6810       Ops.push_back(CPIdx);
6811
6812       SmallVector<EVT, 2> ValueVTs;
6813       ValueVTs.push_back(MVT::v4i1);
6814       ValueVTs.push_back(MVT::Other); // chain
6815       SDVTList VTs = DAG.getVTList(ValueVTs);
6816
6817       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6818         dl, VTs, Ops, MVT::v4f32,
6819         MachinePointerInfo::getConstantPool());
6820     }
6821
6822     SmallVector<SDValue, 4> Stores;
6823     for (unsigned i = 0; i < 4; ++i) {
6824       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6825
6826       unsigned Offset = 4*i;
6827       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6828       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6829
6830       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6831       if (StoreSize > 4) {
6832         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6833                                            BVN->getOperand(i), Idx,
6834                                            PtrInfo.getWithOffset(Offset),
6835                                            MVT::i32, false, false, 0));
6836       } else {
6837         SDValue StoreValue = BVN->getOperand(i);
6838         if (StoreSize < 4)
6839           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6840
6841         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6842                                       StoreValue, Idx,
6843                                       PtrInfo.getWithOffset(Offset),
6844                                       false, false, 0));
6845       }
6846     }
6847
6848     SDValue StoreChain;
6849     if (!Stores.empty())
6850       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6851     else
6852       StoreChain = DAG.getEntryNode();
6853
6854     // Now load from v4i32 into the QPX register; this will extend it to
6855     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6856     // is typed as v4f64 because the QPX register integer states are not
6857     // explicitly represented.
6858
6859     SmallVector<SDValue, 2> Ops;
6860     Ops.push_back(StoreChain);
6861     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6862     Ops.push_back(FIdx);
6863
6864     SmallVector<EVT, 2> ValueVTs;
6865     ValueVTs.push_back(MVT::v4f64);
6866     ValueVTs.push_back(MVT::Other); // chain
6867     SDVTList VTs = DAG.getVTList(ValueVTs);
6868
6869     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6870       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6871     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6872       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6873       LoadedVect);
6874
6875     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6876     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6877                           FPZeros, FPZeros, FPZeros, FPZeros);
6878
6879     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6880   }
6881
6882   // All other QPX vectors are handled by generic code.
6883   if (Subtarget.hasQPX())
6884     return SDValue();
6885
6886   // Check if this is a splat of a constant value.
6887   APInt APSplatBits, APSplatUndef;
6888   unsigned SplatBitSize;
6889   bool HasAnyUndefs;
6890   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6891                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6892       SplatBitSize > 32)
6893     return SDValue();
6894
6895   unsigned SplatBits = APSplatBits.getZExtValue();
6896   unsigned SplatUndef = APSplatUndef.getZExtValue();
6897   unsigned SplatSize = SplatBitSize / 8;
6898
6899   // First, handle single instruction cases.
6900
6901   // All zeros?
6902   if (SplatBits == 0) {
6903     // Canonicalize all zero vectors to be v4i32.
6904     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6905       SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6906       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6907       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6908     }
6909     return Op;
6910   }
6911
6912   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6913   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6914                     (32-SplatBitSize));
6915   if (SextVal >= -16 && SextVal <= 15)
6916     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6917
6918
6919   // Two instruction sequences.
6920
6921   // If this value is in the range [-32,30] and is even, use:
6922   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6923   // If this value is in the range [17,31] and is odd, use:
6924   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6925   // If this value is in the range [-31,-17] and is odd, use:
6926   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6927   // Note the last two are three-instruction sequences.
6928   if (SextVal >= -32 && SextVal <= 31) {
6929     // To avoid having these optimizations undone by constant folding,
6930     // we convert to a pseudo that will be expanded later into one of
6931     // the above forms.
6932     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6933     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6934               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6935     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6936     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6937     if (VT == Op.getValueType())
6938       return RetVal;
6939     else
6940       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6941   }
6942
6943   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6944   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6945   // for fneg/fabs.
6946   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6947     // Make -1 and vspltisw -1:
6948     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6949
6950     // Make the VSLW intrinsic, computing 0x8000_0000.
6951     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6952                                    OnesV, DAG, dl);
6953
6954     // xor by OnesV to invert it.
6955     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6956     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6957   }
6958
6959   // Check to see if this is a wide variety of vsplti*, binop self cases.
6960   static const signed char SplatCsts[] = {
6961     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6962     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6963   };
6964
6965   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6966     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6967     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6968     int i = SplatCsts[idx];
6969
6970     // Figure out what shift amount will be used by altivec if shifted by i in
6971     // this splat size.
6972     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6973
6974     // vsplti + shl self.
6975     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6976       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6977       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6978         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6979         Intrinsic::ppc_altivec_vslw
6980       };
6981       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6982       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6983     }
6984
6985     // vsplti + srl self.
6986     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6987       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6988       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6989         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6990         Intrinsic::ppc_altivec_vsrw
6991       };
6992       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6993       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6994     }
6995
6996     // vsplti + sra self.
6997     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6998       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6999       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7000         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7001         Intrinsic::ppc_altivec_vsraw
7002       };
7003       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7004       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7005     }
7006
7007     // vsplti + rol self.
7008     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7009                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7010       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7011       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7012         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7013         Intrinsic::ppc_altivec_vrlw
7014       };
7015       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7016       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7017     }
7018
7019     // t = vsplti c, result = vsldoi t, t, 1
7020     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7021       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7022       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7023       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7024     }
7025     // t = vsplti c, result = vsldoi t, t, 2
7026     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7027       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7028       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7029       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7030     }
7031     // t = vsplti c, result = vsldoi t, t, 3
7032     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7033       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7034       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7035       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7036     }
7037   }
7038
7039   return SDValue();
7040 }
7041
7042 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7043 /// the specified operations to build the shuffle.
7044 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7045                                       SDValue RHS, SelectionDAG &DAG,
7046                                       SDLoc dl) {
7047   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7048   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7049   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7050
7051   enum {
7052     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7053     OP_VMRGHW,
7054     OP_VMRGLW,
7055     OP_VSPLTISW0,
7056     OP_VSPLTISW1,
7057     OP_VSPLTISW2,
7058     OP_VSPLTISW3,
7059     OP_VSLDOI4,
7060     OP_VSLDOI8,
7061     OP_VSLDOI12
7062   };
7063
7064   if (OpNum == OP_COPY) {
7065     if (LHSID == (1*9+2)*9+3) return LHS;
7066     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7067     return RHS;
7068   }
7069
7070   SDValue OpLHS, OpRHS;
7071   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7072   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7073
7074   int ShufIdxs[16];
7075   switch (OpNum) {
7076   default: llvm_unreachable("Unknown i32 permute!");
7077   case OP_VMRGHW:
7078     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7079     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7080     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7081     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7082     break;
7083   case OP_VMRGLW:
7084     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7085     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7086     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7087     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7088     break;
7089   case OP_VSPLTISW0:
7090     for (unsigned i = 0; i != 16; ++i)
7091       ShufIdxs[i] = (i&3)+0;
7092     break;
7093   case OP_VSPLTISW1:
7094     for (unsigned i = 0; i != 16; ++i)
7095       ShufIdxs[i] = (i&3)+4;
7096     break;
7097   case OP_VSPLTISW2:
7098     for (unsigned i = 0; i != 16; ++i)
7099       ShufIdxs[i] = (i&3)+8;
7100     break;
7101   case OP_VSPLTISW3:
7102     for (unsigned i = 0; i != 16; ++i)
7103       ShufIdxs[i] = (i&3)+12;
7104     break;
7105   case OP_VSLDOI4:
7106     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7107   case OP_VSLDOI8:
7108     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7109   case OP_VSLDOI12:
7110     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7111   }
7112   EVT VT = OpLHS.getValueType();
7113   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7114   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7115   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7116   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7117 }
7118
7119 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7120 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7121 /// return the code it can be lowered into.  Worst case, it can always be
7122 /// lowered into a vperm.
7123 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7124                                                SelectionDAG &DAG) const {
7125   SDLoc dl(Op);
7126   SDValue V1 = Op.getOperand(0);
7127   SDValue V2 = Op.getOperand(1);
7128   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7129   EVT VT = Op.getValueType();
7130   bool isLittleEndian = Subtarget.isLittleEndian();
7131
7132   if (Subtarget.hasQPX()) {
7133     if (VT.getVectorNumElements() != 4)
7134       return SDValue();
7135
7136     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7137
7138     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7139     if (AlignIdx != -1) {
7140       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7141                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7142     } else if (SVOp->isSplat()) {
7143       int SplatIdx = SVOp->getSplatIndex();
7144       if (SplatIdx >= 4) {
7145         std::swap(V1, V2);
7146         SplatIdx -= 4;
7147       }
7148
7149       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
7150       // nothing to do.
7151
7152       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7153                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7154     }
7155
7156     // Lower this into a qvgpci/qvfperm pair.
7157
7158     // Compute the qvgpci literal
7159     unsigned idx = 0;
7160     for (unsigned i = 0; i < 4; ++i) {
7161       int m = SVOp->getMaskElt(i);
7162       unsigned mm = m >= 0 ? (unsigned) m : i;
7163       idx |= mm << (3-i)*3;
7164     }
7165
7166     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7167                              DAG.getConstant(idx, dl, MVT::i32));
7168     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7169   }
7170
7171   // Cases that are handled by instructions that take permute immediates
7172   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7173   // selected by the instruction selector.
7174   if (V2.getOpcode() == ISD::UNDEF) {
7175     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7176         PPC::isSplatShuffleMask(SVOp, 2) ||
7177         PPC::isSplatShuffleMask(SVOp, 4) ||
7178         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7179         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7180         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7181         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7182         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7183         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7184         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7185         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7186         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7187         (Subtarget.hasP8Altivec() && (
7188          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7189          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7190          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7191       return Op;
7192     }
7193   }
7194
7195   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7196   // and produce a fixed permutation.  If any of these match, do not lower to
7197   // VPERM.
7198   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7199   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7200       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7201       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7202       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7203       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7204       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7205       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7206       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7207       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7208       (Subtarget.hasP8Altivec() && (
7209        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7210        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7211        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7212     return Op;
7213
7214   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7215   // perfect shuffle table to emit an optimal matching sequence.
7216   ArrayRef<int> PermMask = SVOp->getMask();
7217
7218   unsigned PFIndexes[4];
7219   bool isFourElementShuffle = true;
7220   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7221     unsigned EltNo = 8;   // Start out undef.
7222     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7223       if (PermMask[i*4+j] < 0)
7224         continue;   // Undef, ignore it.
7225
7226       unsigned ByteSource = PermMask[i*4+j];
7227       if ((ByteSource & 3) != j) {
7228         isFourElementShuffle = false;
7229         break;
7230       }
7231
7232       if (EltNo == 8) {
7233         EltNo = ByteSource/4;
7234       } else if (EltNo != ByteSource/4) {
7235         isFourElementShuffle = false;
7236         break;
7237       }
7238     }
7239     PFIndexes[i] = EltNo;
7240   }
7241
7242   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7243   // perfect shuffle vector to determine if it is cost effective to do this as
7244   // discrete instructions, or whether we should use a vperm.
7245   // For now, we skip this for little endian until such time as we have a
7246   // little-endian perfect shuffle table.
7247   if (isFourElementShuffle && !isLittleEndian) {
7248     // Compute the index in the perfect shuffle table.
7249     unsigned PFTableIndex =
7250       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7251
7252     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7253     unsigned Cost  = (PFEntry >> 30);
7254
7255     // Determining when to avoid vperm is tricky.  Many things affect the cost
7256     // of vperm, particularly how many times the perm mask needs to be computed.
7257     // For example, if the perm mask can be hoisted out of a loop or is already
7258     // used (perhaps because there are multiple permutes with the same shuffle
7259     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7260     // the loop requires an extra register.
7261     //
7262     // As a compromise, we only emit discrete instructions if the shuffle can be
7263     // generated in 3 or fewer operations.  When we have loop information
7264     // available, if this block is within a loop, we should avoid using vperm
7265     // for 3-operation perms and use a constant pool load instead.
7266     if (Cost < 3)
7267       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7268   }
7269
7270   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7271   // vector that will get spilled to the constant pool.
7272   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7273
7274   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7275   // that it is in input element units, not in bytes.  Convert now.
7276
7277   // For little endian, the order of the input vectors is reversed, and
7278   // the permutation mask is complemented with respect to 31.  This is
7279   // necessary to produce proper semantics with the big-endian-biased vperm
7280   // instruction.
7281   EVT EltVT = V1.getValueType().getVectorElementType();
7282   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7283
7284   SmallVector<SDValue, 16> ResultMask;
7285   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7286     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7287
7288     for (unsigned j = 0; j != BytesPerElement; ++j)
7289       if (isLittleEndian)
7290         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7291                                              dl, MVT::i32));
7292       else
7293         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7294                                              MVT::i32));
7295   }
7296
7297   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7298                                   ResultMask);
7299   if (isLittleEndian)
7300     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7301                        V2, V1, VPermMask);
7302   else
7303     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7304                        V1, V2, VPermMask);
7305 }
7306
7307 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7308 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7309 /// information about the intrinsic.
7310 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7311                                   bool &isDot, const PPCSubtarget &Subtarget) {
7312   unsigned IntrinsicID =
7313     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7314   CompareOpc = -1;
7315   isDot = false;
7316   switch (IntrinsicID) {
7317   default: return false;
7318     // Comparison predicates.
7319   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7320   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7321   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7322   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7323   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7324   case Intrinsic::ppc_altivec_vcmpequd_p: 
7325     if (Subtarget.hasP8Altivec()) {
7326       CompareOpc = 199; 
7327       isDot = 1; 
7328     }
7329     else 
7330       return false;
7331
7332     break;
7333   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7334   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7335   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7336   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7337   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7338   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7339     if (Subtarget.hasP8Altivec()) {
7340       CompareOpc = 967; 
7341       isDot = 1; 
7342     }
7343     else 
7344       return false;
7345
7346     break;
7347   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7348   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7349   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7350   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7351     if (Subtarget.hasP8Altivec()) {
7352       CompareOpc = 711; 
7353       isDot = 1; 
7354     }
7355     else 
7356       return false;
7357
7358     break;
7359       
7360     // Normal Comparisons.
7361   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7362   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7363   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7364   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7365   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7366   case Intrinsic::ppc_altivec_vcmpequd:
7367     if (Subtarget.hasP8Altivec()) {
7368       CompareOpc = 199; 
7369       isDot = 0; 
7370     }
7371     else
7372       return false;
7373
7374     break;
7375   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7376   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7377   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7378   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7379   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7380   case Intrinsic::ppc_altivec_vcmpgtsd:   
7381     if (Subtarget.hasP8Altivec()) {
7382       CompareOpc = 967; 
7383       isDot = 0; 
7384     }
7385     else
7386       return false;
7387
7388     break;
7389   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7390   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7391   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7392   case Intrinsic::ppc_altivec_vcmpgtud:   
7393     if (Subtarget.hasP8Altivec()) {
7394       CompareOpc = 711; 
7395       isDot = 0; 
7396     }
7397     else
7398       return false;
7399
7400     break;
7401   }
7402   return true;
7403 }
7404
7405 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7406 /// lower, do it, otherwise return null.
7407 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7408                                                    SelectionDAG &DAG) const {
7409   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7410   // opcode number of the comparison.
7411   SDLoc dl(Op);
7412   int CompareOpc;
7413   bool isDot;
7414   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7415     return SDValue();    // Don't custom lower most intrinsics.
7416
7417   // If this is a non-dot comparison, make the VCMP node and we are done.
7418   if (!isDot) {
7419     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7420                               Op.getOperand(1), Op.getOperand(2),
7421                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7422     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7423   }
7424
7425   // Create the PPCISD altivec 'dot' comparison node.
7426   SDValue Ops[] = {
7427     Op.getOperand(2),  // LHS
7428     Op.getOperand(3),  // RHS
7429     DAG.getConstant(CompareOpc, dl, MVT::i32)
7430   };
7431   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7432   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7433
7434   // Now that we have the comparison, emit a copy from the CR to a GPR.
7435   // This is flagged to the above dot comparison.
7436   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7437                                 DAG.getRegister(PPC::CR6, MVT::i32),
7438                                 CompNode.getValue(1));
7439
7440   // Unpack the result based on how the target uses it.
7441   unsigned BitNo;   // Bit # of CR6.
7442   bool InvertBit;   // Invert result?
7443   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7444   default:  // Can't happen, don't crash on invalid number though.
7445   case 0:   // Return the value of the EQ bit of CR6.
7446     BitNo = 0; InvertBit = false;
7447     break;
7448   case 1:   // Return the inverted value of the EQ bit of CR6.
7449     BitNo = 0; InvertBit = true;
7450     break;
7451   case 2:   // Return the value of the LT bit of CR6.
7452     BitNo = 2; InvertBit = false;
7453     break;
7454   case 3:   // Return the inverted value of the LT bit of CR6.
7455     BitNo = 2; InvertBit = true;
7456     break;
7457   }
7458
7459   // Shift the bit into the low position.
7460   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7461                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7462   // Isolate the bit.
7463   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7464                       DAG.getConstant(1, dl, MVT::i32));
7465
7466   // If we are supposed to, toggle the bit.
7467   if (InvertBit)
7468     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7469                         DAG.getConstant(1, dl, MVT::i32));
7470   return Flags;
7471 }
7472
7473 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7474                                                   SelectionDAG &DAG) const {
7475   SDLoc dl(Op);
7476   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7477   // instructions), but for smaller types, we need to first extend up to v2i32
7478   // before doing going farther.
7479   if (Op.getValueType() == MVT::v2i64) {
7480     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7481     if (ExtVT != MVT::v2i32) {
7482       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7483       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7484                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7485                                         ExtVT.getVectorElementType(), 4)));
7486       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7487       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7488                        DAG.getValueType(MVT::v2i32));
7489     }
7490
7491     return Op;
7492   }
7493
7494   return SDValue();
7495 }
7496
7497 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7498                                                    SelectionDAG &DAG) const {
7499   SDLoc dl(Op);
7500   // Create a stack slot that is 16-byte aligned.
7501   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7502   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7503   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7504   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7505
7506   // Store the input value into Value#0 of the stack slot.
7507   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7508                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7509                                false, false, 0);
7510   // Load it out.
7511   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7512                      false, false, false, 0);
7513 }
7514
7515 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7516                                                    SelectionDAG &DAG) const {
7517   SDLoc dl(Op);
7518   SDNode *N = Op.getNode();
7519
7520   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7521          "Unknown extract_vector_elt type");
7522
7523   SDValue Value = N->getOperand(0);
7524
7525   // The first part of this is like the store lowering except that we don't
7526   // need to track the chain.
7527
7528   // The values are now known to be -1 (false) or 1 (true). To convert this
7529   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7530   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7531   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7532
7533   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7534   // understand how to form the extending load.
7535   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7536   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7537                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7538
7539   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7540
7541   // Now convert to an integer and store.
7542   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7543     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7544     Value);
7545
7546   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7547   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7548   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7549   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7550   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7551
7552   SDValue StoreChain = DAG.getEntryNode();
7553   SmallVector<SDValue, 2> Ops;
7554   Ops.push_back(StoreChain);
7555   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7556   Ops.push_back(Value);
7557   Ops.push_back(FIdx);
7558
7559   SmallVector<EVT, 2> ValueVTs;
7560   ValueVTs.push_back(MVT::Other); // chain
7561   SDVTList VTs = DAG.getVTList(ValueVTs);
7562
7563   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7564     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7565
7566   // Extract the value requested.
7567   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7568   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7569   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7570
7571   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7572                                PtrInfo.getWithOffset(Offset),
7573                                false, false, false, 0);
7574
7575   if (!Subtarget.useCRBits())
7576     return IntVal;
7577
7578   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7579 }
7580
7581 /// Lowering for QPX v4i1 loads
7582 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7583                                            SelectionDAG &DAG) const {
7584   SDLoc dl(Op);
7585   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7586   SDValue LoadChain = LN->getChain();
7587   SDValue BasePtr = LN->getBasePtr();
7588
7589   if (Op.getValueType() == MVT::v4f64 ||
7590       Op.getValueType() == MVT::v4f32) {
7591     EVT MemVT = LN->getMemoryVT();
7592     unsigned Alignment = LN->getAlignment();
7593
7594     // If this load is properly aligned, then it is legal.
7595     if (Alignment >= MemVT.getStoreSize())
7596       return Op;
7597
7598     EVT ScalarVT = Op.getValueType().getScalarType(),
7599         ScalarMemVT = MemVT.getScalarType();
7600     unsigned Stride = ScalarMemVT.getStoreSize();
7601
7602     SmallVector<SDValue, 8> Vals, LoadChains;
7603     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7604       SDValue Load;
7605       if (ScalarVT != ScalarMemVT)
7606         Load =
7607           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7608                          BasePtr,
7609                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7610                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7611                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7612                          LN->getAAInfo());
7613       else
7614         Load =
7615           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7616                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7617                        LN->isVolatile(), LN->isNonTemporal(),
7618                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7619                        LN->getAAInfo());
7620
7621       if (Idx == 0 && LN->isIndexed()) {
7622         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7623                "Unknown addressing mode on vector load");
7624         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7625                                   LN->getAddressingMode());
7626       }
7627
7628       Vals.push_back(Load);
7629       LoadChains.push_back(Load.getValue(1));
7630
7631       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7632                             DAG.getConstant(Stride, dl,
7633                                             BasePtr.getValueType()));
7634     }
7635
7636     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7637     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7638                                 Op.getValueType(), Vals);
7639
7640     if (LN->isIndexed()) {
7641       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7642       return DAG.getMergeValues(RetOps, dl);
7643     }
7644
7645     SDValue RetOps[] = { Value, TF };
7646     return DAG.getMergeValues(RetOps, dl);
7647   }
7648
7649   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7650   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7651
7652   // To lower v4i1 from a byte array, we load the byte elements of the
7653   // vector and then reuse the BUILD_VECTOR logic.
7654
7655   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7656   for (unsigned i = 0; i < 4; ++i) {
7657     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7658     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7659
7660     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7661                         dl, MVT::i32, LoadChain, Idx,
7662                         LN->getPointerInfo().getWithOffset(i),
7663                         MVT::i8 /* memory type */,
7664                         LN->isVolatile(), LN->isNonTemporal(),
7665                         LN->isInvariant(),
7666                         1 /* alignment */, LN->getAAInfo()));
7667     VectElmtChains.push_back(VectElmts[i].getValue(1));
7668   }
7669
7670   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7671   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7672
7673   SDValue RVals[] = { Value, LoadChain };
7674   return DAG.getMergeValues(RVals, dl);
7675 }
7676
7677 /// Lowering for QPX v4i1 stores
7678 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7679                                             SelectionDAG &DAG) const {
7680   SDLoc dl(Op);
7681   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7682   SDValue StoreChain = SN->getChain();
7683   SDValue BasePtr = SN->getBasePtr();
7684   SDValue Value = SN->getValue();
7685
7686   if (Value.getValueType() == MVT::v4f64 ||
7687       Value.getValueType() == MVT::v4f32) {
7688     EVT MemVT = SN->getMemoryVT();
7689     unsigned Alignment = SN->getAlignment();
7690
7691     // If this store is properly aligned, then it is legal.
7692     if (Alignment >= MemVT.getStoreSize())
7693       return Op;
7694
7695     EVT ScalarVT = Value.getValueType().getScalarType(),
7696         ScalarMemVT = MemVT.getScalarType();
7697     unsigned Stride = ScalarMemVT.getStoreSize();
7698
7699     SmallVector<SDValue, 8> Stores;
7700     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7701       SDValue Ex = DAG.getNode(
7702           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7703           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
7704       SDValue Store;
7705       if (ScalarVT != ScalarMemVT)
7706         Store =
7707           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7708                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7709                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7710                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7711       else
7712         Store =
7713           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7714                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7715                        SN->isVolatile(), SN->isNonTemporal(),
7716                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7717
7718       if (Idx == 0 && SN->isIndexed()) {
7719         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7720                "Unknown addressing mode on vector store");
7721         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7722                                     SN->getAddressingMode());
7723       }
7724
7725       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7726                             DAG.getConstant(Stride, dl,
7727                                             BasePtr.getValueType()));
7728       Stores.push_back(Store);
7729     }
7730
7731     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7732
7733     if (SN->isIndexed()) {
7734       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7735       return DAG.getMergeValues(RetOps, dl);
7736     }
7737
7738     return TF;
7739   }
7740
7741   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7742   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7743
7744   // The values are now known to be -1 (false) or 1 (true). To convert this
7745   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7746   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7747   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7748
7749   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7750   // understand how to form the extending load.
7751   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7752   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7753                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7754
7755   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7756
7757   // Now convert to an integer and store.
7758   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7759     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7760     Value);
7761
7762   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7763   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7764   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7765   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7766   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7767
7768   SmallVector<SDValue, 2> Ops;
7769   Ops.push_back(StoreChain);
7770   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7771   Ops.push_back(Value);
7772   Ops.push_back(FIdx);
7773
7774   SmallVector<EVT, 2> ValueVTs;
7775   ValueVTs.push_back(MVT::Other); // chain
7776   SDVTList VTs = DAG.getVTList(ValueVTs);
7777
7778   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7779     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7780
7781   // Move data into the byte array.
7782   SmallVector<SDValue, 4> Loads, LoadChains;
7783   for (unsigned i = 0; i < 4; ++i) {
7784     unsigned Offset = 4*i;
7785     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7786     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7787
7788     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7789                                    PtrInfo.getWithOffset(Offset),
7790                                    false, false, false, 0));
7791     LoadChains.push_back(Loads[i].getValue(1));
7792   }
7793
7794   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7795
7796   SmallVector<SDValue, 4> Stores;
7797   for (unsigned i = 0; i < 4; ++i) {
7798     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7799     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7800
7801     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7802                                        SN->getPointerInfo().getWithOffset(i),
7803                                        MVT::i8 /* memory type */,
7804                                        SN->isNonTemporal(), SN->isVolatile(), 
7805                                        1 /* alignment */, SN->getAAInfo()));
7806   }
7807
7808   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7809
7810   return StoreChain;
7811 }
7812
7813 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7814   SDLoc dl(Op);
7815   if (Op.getValueType() == MVT::v4i32) {
7816     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7817
7818     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7819     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7820
7821     SDValue RHSSwap =   // = vrlw RHS, 16
7822       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7823
7824     // Shrinkify inputs to v8i16.
7825     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7826     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7827     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7828
7829     // Low parts multiplied together, generating 32-bit results (we ignore the
7830     // top parts).
7831     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7832                                         LHS, RHS, DAG, dl, MVT::v4i32);
7833
7834     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7835                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7836     // Shift the high parts up 16 bits.
7837     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7838                               Neg16, DAG, dl);
7839     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7840   } else if (Op.getValueType() == MVT::v8i16) {
7841     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7842
7843     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7844
7845     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7846                             LHS, RHS, Zero, DAG, dl);
7847   } else if (Op.getValueType() == MVT::v16i8) {
7848     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7849     bool isLittleEndian = Subtarget.isLittleEndian();
7850
7851     // Multiply the even 8-bit parts, producing 16-bit sums.
7852     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7853                                            LHS, RHS, DAG, dl, MVT::v8i16);
7854     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7855
7856     // Multiply the odd 8-bit parts, producing 16-bit sums.
7857     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7858                                           LHS, RHS, DAG, dl, MVT::v8i16);
7859     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7860
7861     // Merge the results together.  Because vmuleub and vmuloub are
7862     // instructions with a big-endian bias, we must reverse the
7863     // element numbering and reverse the meaning of "odd" and "even"
7864     // when generating little endian code.
7865     int Ops[16];
7866     for (unsigned i = 0; i != 8; ++i) {
7867       if (isLittleEndian) {
7868         Ops[i*2  ] = 2*i;
7869         Ops[i*2+1] = 2*i+16;
7870       } else {
7871         Ops[i*2  ] = 2*i+1;
7872         Ops[i*2+1] = 2*i+1+16;
7873       }
7874     }
7875     if (isLittleEndian)
7876       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7877     else
7878       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7879   } else {
7880     llvm_unreachable("Unknown mul to lower!");
7881   }
7882 }
7883
7884 /// LowerOperation - Provide custom lowering hooks for some operations.
7885 ///
7886 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7887   switch (Op.getOpcode()) {
7888   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7889   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7890   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7891   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7892   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7893   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7894   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7895   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7896   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7897   case ISD::VASTART:
7898     return LowerVASTART(Op, DAG, Subtarget);
7899
7900   case ISD::VAARG:
7901     return LowerVAARG(Op, DAG, Subtarget);
7902
7903   case ISD::VACOPY:
7904     return LowerVACOPY(Op, DAG, Subtarget);
7905
7906   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7907   case ISD::DYNAMIC_STACKALLOC:
7908     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7909
7910   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7911   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7912
7913   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7914   case ISD::STORE:              return LowerSTORE(Op, DAG);
7915   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7916   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7917   case ISD::FP_TO_UINT:
7918   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7919                                                       SDLoc(Op));
7920   case ISD::UINT_TO_FP:
7921   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7922   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7923
7924   // Lower 64-bit shifts.
7925   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7926   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7927   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7928
7929   // Vector-related lowering.
7930   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7931   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7932   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7933   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7934   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7935   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7936   case ISD::MUL:                return LowerMUL(Op, DAG);
7937
7938   // For counter-based loop handling.
7939   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7940
7941   // Frame & Return address.
7942   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7943   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7944   }
7945 }
7946
7947 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7948                                            SmallVectorImpl<SDValue>&Results,
7949                                            SelectionDAG &DAG) const {
7950   SDLoc dl(N);
7951   switch (N->getOpcode()) {
7952   default:
7953     llvm_unreachable("Do not know how to custom type legalize this operation!");
7954   case ISD::READCYCLECOUNTER: {
7955     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7956     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7957
7958     Results.push_back(RTB);
7959     Results.push_back(RTB.getValue(1));
7960     Results.push_back(RTB.getValue(2));
7961     break;
7962   }
7963   case ISD::INTRINSIC_W_CHAIN: {
7964     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7965         Intrinsic::ppc_is_decremented_ctr_nonzero)
7966       break;
7967
7968     assert(N->getValueType(0) == MVT::i1 &&
7969            "Unexpected result type for CTR decrement intrinsic");
7970     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
7971                                  N->getValueType(0));
7972     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7973     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7974                                  N->getOperand(1)); 
7975
7976     Results.push_back(NewInt);
7977     Results.push_back(NewInt.getValue(1));
7978     break;
7979   }
7980   case ISD::VAARG: {
7981     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7982       return;
7983
7984     EVT VT = N->getValueType(0);
7985
7986     if (VT == MVT::i64) {
7987       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7988
7989       Results.push_back(NewNode);
7990       Results.push_back(NewNode.getValue(1));
7991     }
7992     return;
7993   }
7994   case ISD::FP_ROUND_INREG: {
7995     assert(N->getValueType(0) == MVT::ppcf128);
7996     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7997     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7998                              MVT::f64, N->getOperand(0),
7999                              DAG.getIntPtrConstant(0, dl));
8000     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8001                              MVT::f64, N->getOperand(0),
8002                              DAG.getIntPtrConstant(1, dl));
8003
8004     // Add the two halves of the long double in round-to-zero mode.
8005     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8006
8007     // We know the low half is about to be thrown away, so just use something
8008     // convenient.
8009     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8010                                 FPreg, FPreg));
8011     return;
8012   }
8013   case ISD::FP_TO_SINT:
8014   case ISD::FP_TO_UINT:
8015     // LowerFP_TO_INT() can only handle f32 and f64.
8016     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8017       return;
8018     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8019     return;
8020   }
8021 }
8022
8023
8024 //===----------------------------------------------------------------------===//
8025 //  Other Lowering Code
8026 //===----------------------------------------------------------------------===//
8027
8028 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8029   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8030   Function *Func = Intrinsic::getDeclaration(M, Id);
8031   return Builder.CreateCall(Func, {});
8032 }
8033
8034 // The mappings for emitLeading/TrailingFence is taken from
8035 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8036 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8037                                          AtomicOrdering Ord, bool IsStore,
8038                                          bool IsLoad) const {
8039   if (Ord == SequentiallyConsistent)
8040     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8041   if (isAtLeastRelease(Ord))
8042     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8043   return nullptr;
8044 }
8045
8046 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8047                                           AtomicOrdering Ord, bool IsStore,
8048                                           bool IsLoad) const {
8049   if (IsLoad && isAtLeastAcquire(Ord))
8050     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8051   // FIXME: this is too conservative, a dependent branch + isync is enough.
8052   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8053   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8054   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8055   return nullptr;
8056 }
8057
8058 MachineBasicBlock *
8059 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
8060                                     unsigned AtomicSize,
8061                                     unsigned BinOpcode) const {
8062   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8063   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8064
8065   auto LoadMnemonic = PPC::LDARX;
8066   auto StoreMnemonic = PPC::STDCX;
8067   switch (AtomicSize) {
8068   default:
8069     llvm_unreachable("Unexpected size of atomic entity");
8070   case 1:
8071     LoadMnemonic = PPC::LBARX;
8072     StoreMnemonic = PPC::STBCX;
8073     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8074     break;
8075   case 2:
8076     LoadMnemonic = PPC::LHARX;
8077     StoreMnemonic = PPC::STHCX;
8078     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8079     break;
8080   case 4:
8081     LoadMnemonic = PPC::LWARX;
8082     StoreMnemonic = PPC::STWCX;
8083     break;
8084   case 8:
8085     LoadMnemonic = PPC::LDARX;
8086     StoreMnemonic = PPC::STDCX;
8087     break;
8088   }
8089
8090   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8091   MachineFunction *F = BB->getParent();
8092   MachineFunction::iterator It = BB;
8093   ++It;
8094
8095   unsigned dest = MI->getOperand(0).getReg();
8096   unsigned ptrA = MI->getOperand(1).getReg();
8097   unsigned ptrB = MI->getOperand(2).getReg();
8098   unsigned incr = MI->getOperand(3).getReg();
8099   DebugLoc dl = MI->getDebugLoc();
8100
8101   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8102   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8103   F->insert(It, loopMBB);
8104   F->insert(It, exitMBB);
8105   exitMBB->splice(exitMBB->begin(), BB,
8106                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8107   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8108
8109   MachineRegisterInfo &RegInfo = F->getRegInfo();
8110   unsigned TmpReg = (!BinOpcode) ? incr :
8111     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8112                                            : &PPC::GPRCRegClass);
8113
8114   //  thisMBB:
8115   //   ...
8116   //   fallthrough --> loopMBB
8117   BB->addSuccessor(loopMBB);
8118
8119   //  loopMBB:
8120   //   l[wd]arx dest, ptr
8121   //   add r0, dest, incr
8122   //   st[wd]cx. r0, ptr
8123   //   bne- loopMBB
8124   //   fallthrough --> exitMBB
8125   BB = loopMBB;
8126   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8127     .addReg(ptrA).addReg(ptrB);
8128   if (BinOpcode)
8129     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8130   BuildMI(BB, dl, TII->get(StoreMnemonic))
8131     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8132   BuildMI(BB, dl, TII->get(PPC::BCC))
8133     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8134   BB->addSuccessor(loopMBB);
8135   BB->addSuccessor(exitMBB);
8136
8137   //  exitMBB:
8138   //   ...
8139   BB = exitMBB;
8140   return BB;
8141 }
8142
8143 MachineBasicBlock *
8144 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8145                                             MachineBasicBlock *BB,
8146                                             bool is8bit,    // operation
8147                                             unsigned BinOpcode) const {
8148   // If we support part-word atomic mnemonics, just use them
8149   if (Subtarget.hasPartwordAtomics())
8150     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8151
8152   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8153   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8154   // In 64 bit mode we have to use 64 bits for addresses, even though the
8155   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8156   // registers without caring whether they're 32 or 64, but here we're
8157   // doing actual arithmetic on the addresses.
8158   bool is64bit = Subtarget.isPPC64();
8159   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8160
8161   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8162   MachineFunction *F = BB->getParent();
8163   MachineFunction::iterator It = BB;
8164   ++It;
8165
8166   unsigned dest = MI->getOperand(0).getReg();
8167   unsigned ptrA = MI->getOperand(1).getReg();
8168   unsigned ptrB = MI->getOperand(2).getReg();
8169   unsigned incr = MI->getOperand(3).getReg();
8170   DebugLoc dl = MI->getDebugLoc();
8171
8172   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8173   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8174   F->insert(It, loopMBB);
8175   F->insert(It, exitMBB);
8176   exitMBB->splice(exitMBB->begin(), BB,
8177                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8178   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8179
8180   MachineRegisterInfo &RegInfo = F->getRegInfo();
8181   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8182                                           : &PPC::GPRCRegClass;
8183   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8184   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8185   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8186   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8187   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8188   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8189   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8190   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8191   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8192   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8193   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8194   unsigned Ptr1Reg;
8195   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8196
8197   //  thisMBB:
8198   //   ...
8199   //   fallthrough --> loopMBB
8200   BB->addSuccessor(loopMBB);
8201
8202   // The 4-byte load must be aligned, while a char or short may be
8203   // anywhere in the word.  Hence all this nasty bookkeeping code.
8204   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8205   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8206   //   xori shift, shift1, 24 [16]
8207   //   rlwinm ptr, ptr1, 0, 0, 29
8208   //   slw incr2, incr, shift
8209   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8210   //   slw mask, mask2, shift
8211   //  loopMBB:
8212   //   lwarx tmpDest, ptr
8213   //   add tmp, tmpDest, incr2
8214   //   andc tmp2, tmpDest, mask
8215   //   and tmp3, tmp, mask
8216   //   or tmp4, tmp3, tmp2
8217   //   stwcx. tmp4, ptr
8218   //   bne- loopMBB
8219   //   fallthrough --> exitMBB
8220   //   srw dest, tmpDest, shift
8221   if (ptrA != ZeroReg) {
8222     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8223     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8224       .addReg(ptrA).addReg(ptrB);
8225   } else {
8226     Ptr1Reg = ptrB;
8227   }
8228   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8229       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8230   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8231       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8232   if (is64bit)
8233     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8234       .addReg(Ptr1Reg).addImm(0).addImm(61);
8235   else
8236     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8237       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8238   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8239       .addReg(incr).addReg(ShiftReg);
8240   if (is8bit)
8241     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8242   else {
8243     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8244     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8245   }
8246   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8247       .addReg(Mask2Reg).addReg(ShiftReg);
8248
8249   BB = loopMBB;
8250   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8251     .addReg(ZeroReg).addReg(PtrReg);
8252   if (BinOpcode)
8253     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8254       .addReg(Incr2Reg).addReg(TmpDestReg);
8255   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8256     .addReg(TmpDestReg).addReg(MaskReg);
8257   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8258     .addReg(TmpReg).addReg(MaskReg);
8259   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8260     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8261   BuildMI(BB, dl, TII->get(PPC::STWCX))
8262     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8263   BuildMI(BB, dl, TII->get(PPC::BCC))
8264     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8265   BB->addSuccessor(loopMBB);
8266   BB->addSuccessor(exitMBB);
8267
8268   //  exitMBB:
8269   //   ...
8270   BB = exitMBB;
8271   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8272     .addReg(ShiftReg);
8273   return BB;
8274 }
8275
8276 llvm::MachineBasicBlock*
8277 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8278                                     MachineBasicBlock *MBB) const {
8279   DebugLoc DL = MI->getDebugLoc();
8280   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8281
8282   MachineFunction *MF = MBB->getParent();
8283   MachineRegisterInfo &MRI = MF->getRegInfo();
8284
8285   const BasicBlock *BB = MBB->getBasicBlock();
8286   MachineFunction::iterator I = MBB;
8287   ++I;
8288
8289   // Memory Reference
8290   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8291   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8292
8293   unsigned DstReg = MI->getOperand(0).getReg();
8294   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8295   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8296   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8297   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8298
8299   MVT PVT = getPointerTy(MF->getDataLayout());
8300   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8301          "Invalid Pointer Size!");
8302   // For v = setjmp(buf), we generate
8303   //
8304   // thisMBB:
8305   //  SjLjSetup mainMBB
8306   //  bl mainMBB
8307   //  v_restore = 1
8308   //  b sinkMBB
8309   //
8310   // mainMBB:
8311   //  buf[LabelOffset] = LR
8312   //  v_main = 0
8313   //
8314   // sinkMBB:
8315   //  v = phi(main, restore)
8316   //
8317
8318   MachineBasicBlock *thisMBB = MBB;
8319   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8320   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8321   MF->insert(I, mainMBB);
8322   MF->insert(I, sinkMBB);
8323
8324   MachineInstrBuilder MIB;
8325
8326   // Transfer the remainder of BB and its successor edges to sinkMBB.
8327   sinkMBB->splice(sinkMBB->begin(), MBB,
8328                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8329   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8330
8331   // Note that the structure of the jmp_buf used here is not compatible
8332   // with that used by libc, and is not designed to be. Specifically, it
8333   // stores only those 'reserved' registers that LLVM does not otherwise
8334   // understand how to spill. Also, by convention, by the time this
8335   // intrinsic is called, Clang has already stored the frame address in the
8336   // first slot of the buffer and stack address in the third. Following the
8337   // X86 target code, we'll store the jump address in the second slot. We also
8338   // need to save the TOC pointer (R2) to handle jumps between shared
8339   // libraries, and that will be stored in the fourth slot. The thread
8340   // identifier (R13) is not affected.
8341
8342   // thisMBB:
8343   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8344   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8345   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8346
8347   // Prepare IP either in reg.
8348   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8349   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8350   unsigned BufReg = MI->getOperand(1).getReg();
8351
8352   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8353     setUsesTOCBasePtr(*MBB->getParent());
8354     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8355             .addReg(PPC::X2)
8356             .addImm(TOCOffset)
8357             .addReg(BufReg);
8358     MIB.setMemRefs(MMOBegin, MMOEnd);
8359   }
8360
8361   // Naked functions never have a base pointer, and so we use r1. For all
8362   // other functions, this decision must be delayed until during PEI.
8363   unsigned BaseReg;
8364   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8365     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8366   else
8367     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8368
8369   MIB = BuildMI(*thisMBB, MI, DL,
8370                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8371             .addReg(BaseReg)
8372             .addImm(BPOffset)
8373             .addReg(BufReg);
8374   MIB.setMemRefs(MMOBegin, MMOEnd);
8375
8376   // Setup
8377   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8378   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8379   MIB.addRegMask(TRI->getNoPreservedMask());
8380
8381   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8382
8383   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8384           .addMBB(mainMBB);
8385   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8386
8387   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8388   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8389
8390   // mainMBB:
8391   //  mainDstReg = 0
8392   MIB =
8393       BuildMI(mainMBB, DL,
8394               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8395
8396   // Store IP
8397   if (Subtarget.isPPC64()) {
8398     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8399             .addReg(LabelReg)
8400             .addImm(LabelOffset)
8401             .addReg(BufReg);
8402   } else {
8403     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8404             .addReg(LabelReg)
8405             .addImm(LabelOffset)
8406             .addReg(BufReg);
8407   }
8408
8409   MIB.setMemRefs(MMOBegin, MMOEnd);
8410
8411   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8412   mainMBB->addSuccessor(sinkMBB);
8413
8414   // sinkMBB:
8415   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8416           TII->get(PPC::PHI), DstReg)
8417     .addReg(mainDstReg).addMBB(mainMBB)
8418     .addReg(restoreDstReg).addMBB(thisMBB);
8419
8420   MI->eraseFromParent();
8421   return sinkMBB;
8422 }
8423
8424 MachineBasicBlock *
8425 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8426                                      MachineBasicBlock *MBB) const {
8427   DebugLoc DL = MI->getDebugLoc();
8428   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8429
8430   MachineFunction *MF = MBB->getParent();
8431   MachineRegisterInfo &MRI = MF->getRegInfo();
8432
8433   // Memory Reference
8434   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8435   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8436
8437   MVT PVT = getPointerTy(MF->getDataLayout());
8438   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8439          "Invalid Pointer Size!");
8440
8441   const TargetRegisterClass *RC =
8442     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8443   unsigned Tmp = MRI.createVirtualRegister(RC);
8444   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8445   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8446   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8447   unsigned BP =
8448       (PVT == MVT::i64)
8449           ? PPC::X30
8450           : (Subtarget.isSVR4ABI() &&
8451                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8452                  ? PPC::R29
8453                  : PPC::R30);
8454
8455   MachineInstrBuilder MIB;
8456
8457   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8458   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8459   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8460   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8461
8462   unsigned BufReg = MI->getOperand(0).getReg();
8463
8464   // Reload FP (the jumped-to function may not have had a
8465   // frame pointer, and if so, then its r31 will be restored
8466   // as necessary).
8467   if (PVT == MVT::i64) {
8468     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8469             .addImm(0)
8470             .addReg(BufReg);
8471   } else {
8472     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8473             .addImm(0)
8474             .addReg(BufReg);
8475   }
8476   MIB.setMemRefs(MMOBegin, MMOEnd);
8477
8478   // Reload IP
8479   if (PVT == MVT::i64) {
8480     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8481             .addImm(LabelOffset)
8482             .addReg(BufReg);
8483   } else {
8484     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8485             .addImm(LabelOffset)
8486             .addReg(BufReg);
8487   }
8488   MIB.setMemRefs(MMOBegin, MMOEnd);
8489
8490   // Reload SP
8491   if (PVT == MVT::i64) {
8492     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8493             .addImm(SPOffset)
8494             .addReg(BufReg);
8495   } else {
8496     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8497             .addImm(SPOffset)
8498             .addReg(BufReg);
8499   }
8500   MIB.setMemRefs(MMOBegin, MMOEnd);
8501
8502   // Reload BP
8503   if (PVT == MVT::i64) {
8504     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8505             .addImm(BPOffset)
8506             .addReg(BufReg);
8507   } else {
8508     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8509             .addImm(BPOffset)
8510             .addReg(BufReg);
8511   }
8512   MIB.setMemRefs(MMOBegin, MMOEnd);
8513
8514   // Reload TOC
8515   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8516     setUsesTOCBasePtr(*MBB->getParent());
8517     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8518             .addImm(TOCOffset)
8519             .addReg(BufReg);
8520
8521     MIB.setMemRefs(MMOBegin, MMOEnd);
8522   }
8523
8524   // Jump
8525   BuildMI(*MBB, MI, DL,
8526           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8527   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8528
8529   MI->eraseFromParent();
8530   return MBB;
8531 }
8532
8533 MachineBasicBlock *
8534 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8535                                                MachineBasicBlock *BB) const {
8536   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8537       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8538     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8539         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8540       // Call lowering should have added an r2 operand to indicate a dependence
8541       // on the TOC base pointer value. It can't however, because there is no
8542       // way to mark the dependence as implicit there, and so the stackmap code
8543       // will confuse it with a regular operand. Instead, add the dependence
8544       // here.
8545       setUsesTOCBasePtr(*BB->getParent());
8546       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8547     }
8548
8549     return emitPatchPoint(MI, BB);
8550   }
8551
8552   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8553       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8554     return emitEHSjLjSetJmp(MI, BB);
8555   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8556              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8557     return emitEHSjLjLongJmp(MI, BB);
8558   }
8559
8560   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8561
8562   // To "insert" these instructions we actually have to insert their
8563   // control-flow patterns.
8564   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8565   MachineFunction::iterator It = BB;
8566   ++It;
8567
8568   MachineFunction *F = BB->getParent();
8569
8570   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8571                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8572                               MI->getOpcode() == PPC::SELECT_I4 ||
8573                               MI->getOpcode() == PPC::SELECT_I8)) {
8574     SmallVector<MachineOperand, 2> Cond;
8575     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8576         MI->getOpcode() == PPC::SELECT_CC_I8)
8577       Cond.push_back(MI->getOperand(4));
8578     else
8579       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8580     Cond.push_back(MI->getOperand(1));
8581
8582     DebugLoc dl = MI->getDebugLoc();
8583     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8584                       Cond, MI->getOperand(2).getReg(),
8585                       MI->getOperand(3).getReg());
8586   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8587              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8588              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8589              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8590              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8591              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8592              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8593              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8594              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8595              MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8596              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8597              MI->getOpcode() == PPC::SELECT_I4 ||
8598              MI->getOpcode() == PPC::SELECT_I8 ||
8599              MI->getOpcode() == PPC::SELECT_F4 ||
8600              MI->getOpcode() == PPC::SELECT_F8 ||
8601              MI->getOpcode() == PPC::SELECT_QFRC ||
8602              MI->getOpcode() == PPC::SELECT_QSRC ||
8603              MI->getOpcode() == PPC::SELECT_QBRC ||
8604              MI->getOpcode() == PPC::SELECT_VRRC ||
8605              MI->getOpcode() == PPC::SELECT_VSFRC ||
8606              MI->getOpcode() == PPC::SELECT_VSSRC ||
8607              MI->getOpcode() == PPC::SELECT_VSRC) {
8608     // The incoming instruction knows the destination vreg to set, the
8609     // condition code register to branch on, the true/false values to
8610     // select between, and a branch opcode to use.
8611
8612     //  thisMBB:
8613     //  ...
8614     //   TrueVal = ...
8615     //   cmpTY ccX, r1, r2
8616     //   bCC copy1MBB
8617     //   fallthrough --> copy0MBB
8618     MachineBasicBlock *thisMBB = BB;
8619     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8620     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8621     DebugLoc dl = MI->getDebugLoc();
8622     F->insert(It, copy0MBB);
8623     F->insert(It, sinkMBB);
8624
8625     // Transfer the remainder of BB and its successor edges to sinkMBB.
8626     sinkMBB->splice(sinkMBB->begin(), BB,
8627                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8628     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8629
8630     // Next, add the true and fallthrough blocks as its successors.
8631     BB->addSuccessor(copy0MBB);
8632     BB->addSuccessor(sinkMBB);
8633
8634     if (MI->getOpcode() == PPC::SELECT_I4 ||
8635         MI->getOpcode() == PPC::SELECT_I8 ||
8636         MI->getOpcode() == PPC::SELECT_F4 ||
8637         MI->getOpcode() == PPC::SELECT_F8 ||
8638         MI->getOpcode() == PPC::SELECT_QFRC ||
8639         MI->getOpcode() == PPC::SELECT_QSRC ||
8640         MI->getOpcode() == PPC::SELECT_QBRC ||
8641         MI->getOpcode() == PPC::SELECT_VRRC ||
8642         MI->getOpcode() == PPC::SELECT_VSFRC ||
8643         MI->getOpcode() == PPC::SELECT_VSSRC ||
8644         MI->getOpcode() == PPC::SELECT_VSRC) {
8645       BuildMI(BB, dl, TII->get(PPC::BC))
8646         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8647     } else {
8648       unsigned SelectPred = MI->getOperand(4).getImm();
8649       BuildMI(BB, dl, TII->get(PPC::BCC))
8650         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8651     }
8652
8653     //  copy0MBB:
8654     //   %FalseValue = ...
8655     //   # fallthrough to sinkMBB
8656     BB = copy0MBB;
8657
8658     // Update machine-CFG edges
8659     BB->addSuccessor(sinkMBB);
8660
8661     //  sinkMBB:
8662     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8663     //  ...
8664     BB = sinkMBB;
8665     BuildMI(*BB, BB->begin(), dl,
8666             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8667       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8668       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8669   } else if (MI->getOpcode() == PPC::ReadTB) {
8670     // To read the 64-bit time-base register on a 32-bit target, we read the
8671     // two halves. Should the counter have wrapped while it was being read, we
8672     // need to try again.
8673     // ...
8674     // readLoop:
8675     // mfspr Rx,TBU # load from TBU
8676     // mfspr Ry,TB  # load from TB
8677     // mfspr Rz,TBU # load from TBU
8678     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8679     // bne readLoop   # branch if they're not equal
8680     // ...
8681
8682     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8683     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8684     DebugLoc dl = MI->getDebugLoc();
8685     F->insert(It, readMBB);
8686     F->insert(It, sinkMBB);
8687
8688     // Transfer the remainder of BB and its successor edges to sinkMBB.
8689     sinkMBB->splice(sinkMBB->begin(), BB,
8690                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8691     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8692
8693     BB->addSuccessor(readMBB);
8694     BB = readMBB;
8695
8696     MachineRegisterInfo &RegInfo = F->getRegInfo();
8697     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8698     unsigned LoReg = MI->getOperand(0).getReg();
8699     unsigned HiReg = MI->getOperand(1).getReg();
8700
8701     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8702     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8703     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8704
8705     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8706
8707     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8708       .addReg(HiReg).addReg(ReadAgainReg);
8709     BuildMI(BB, dl, TII->get(PPC::BCC))
8710       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8711
8712     BB->addSuccessor(readMBB);
8713     BB->addSuccessor(sinkMBB);
8714   }
8715   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8716     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8717   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8718     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8719   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8720     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8721   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8722     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8723
8724   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8725     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8726   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8727     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8728   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8729     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8730   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8731     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8732
8733   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8734     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8735   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8736     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8737   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8738     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8739   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8740     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8741
8742   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8743     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8744   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8745     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8746   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8747     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8748   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8749     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8750
8751   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8752     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8753   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8754     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8755   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8756     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8757   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8758     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8759
8760   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8761     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8762   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8763     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8764   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8765     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8766   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8767     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8768
8769   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8770     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8771   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8772     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8773   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8774     BB = EmitAtomicBinary(MI, BB, 4, 0);
8775   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8776     BB = EmitAtomicBinary(MI, BB, 8, 0);
8777
8778   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8779            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8780            (Subtarget.hasPartwordAtomics() &&
8781             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8782            (Subtarget.hasPartwordAtomics() &&
8783             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8784     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8785
8786     auto LoadMnemonic = PPC::LDARX;
8787     auto StoreMnemonic = PPC::STDCX;
8788     switch(MI->getOpcode()) {
8789     default:
8790       llvm_unreachable("Compare and swap of unknown size");
8791     case PPC::ATOMIC_CMP_SWAP_I8:
8792       LoadMnemonic = PPC::LBARX;
8793       StoreMnemonic = PPC::STBCX;
8794       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8795       break;
8796     case PPC::ATOMIC_CMP_SWAP_I16:
8797       LoadMnemonic = PPC::LHARX;
8798       StoreMnemonic = PPC::STHCX;
8799       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8800       break;
8801     case PPC::ATOMIC_CMP_SWAP_I32:
8802       LoadMnemonic = PPC::LWARX;
8803       StoreMnemonic = PPC::STWCX;
8804       break;
8805     case PPC::ATOMIC_CMP_SWAP_I64:
8806       LoadMnemonic = PPC::LDARX;
8807       StoreMnemonic = PPC::STDCX;
8808       break;
8809     }
8810     unsigned dest   = MI->getOperand(0).getReg();
8811     unsigned ptrA   = MI->getOperand(1).getReg();
8812     unsigned ptrB   = MI->getOperand(2).getReg();
8813     unsigned oldval = MI->getOperand(3).getReg();
8814     unsigned newval = MI->getOperand(4).getReg();
8815     DebugLoc dl     = MI->getDebugLoc();
8816
8817     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8818     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8819     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8820     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8821     F->insert(It, loop1MBB);
8822     F->insert(It, loop2MBB);
8823     F->insert(It, midMBB);
8824     F->insert(It, exitMBB);
8825     exitMBB->splice(exitMBB->begin(), BB,
8826                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8827     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8828
8829     //  thisMBB:
8830     //   ...
8831     //   fallthrough --> loopMBB
8832     BB->addSuccessor(loop1MBB);
8833
8834     // loop1MBB:
8835     //   l[bhwd]arx dest, ptr
8836     //   cmp[wd] dest, oldval
8837     //   bne- midMBB
8838     // loop2MBB:
8839     //   st[bhwd]cx. newval, ptr
8840     //   bne- loopMBB
8841     //   b exitBB
8842     // midMBB:
8843     //   st[bhwd]cx. dest, ptr
8844     // exitBB:
8845     BB = loop1MBB;
8846     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8847       .addReg(ptrA).addReg(ptrB);
8848     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8849       .addReg(oldval).addReg(dest);
8850     BuildMI(BB, dl, TII->get(PPC::BCC))
8851       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8852     BB->addSuccessor(loop2MBB);
8853     BB->addSuccessor(midMBB);
8854
8855     BB = loop2MBB;
8856     BuildMI(BB, dl, TII->get(StoreMnemonic))
8857       .addReg(newval).addReg(ptrA).addReg(ptrB);
8858     BuildMI(BB, dl, TII->get(PPC::BCC))
8859       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8860     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8861     BB->addSuccessor(loop1MBB);
8862     BB->addSuccessor(exitMBB);
8863
8864     BB = midMBB;
8865     BuildMI(BB, dl, TII->get(StoreMnemonic))
8866       .addReg(dest).addReg(ptrA).addReg(ptrB);
8867     BB->addSuccessor(exitMBB);
8868
8869     //  exitMBB:
8870     //   ...
8871     BB = exitMBB;
8872   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8873              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8874     // We must use 64-bit registers for addresses when targeting 64-bit,
8875     // since we're actually doing arithmetic on them.  Other registers
8876     // can be 32-bit.
8877     bool is64bit = Subtarget.isPPC64();
8878     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8879
8880     unsigned dest   = MI->getOperand(0).getReg();
8881     unsigned ptrA   = MI->getOperand(1).getReg();
8882     unsigned ptrB   = MI->getOperand(2).getReg();
8883     unsigned oldval = MI->getOperand(3).getReg();
8884     unsigned newval = MI->getOperand(4).getReg();
8885     DebugLoc dl     = MI->getDebugLoc();
8886
8887     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8888     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8889     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8890     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8891     F->insert(It, loop1MBB);
8892     F->insert(It, loop2MBB);
8893     F->insert(It, midMBB);
8894     F->insert(It, exitMBB);
8895     exitMBB->splice(exitMBB->begin(), BB,
8896                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8897     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8898
8899     MachineRegisterInfo &RegInfo = F->getRegInfo();
8900     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8901                                             : &PPC::GPRCRegClass;
8902     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8903     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8904     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8905     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8906     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8907     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8908     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8909     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8910     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8911     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8912     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8913     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8914     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8915     unsigned Ptr1Reg;
8916     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8917     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8918     //  thisMBB:
8919     //   ...
8920     //   fallthrough --> loopMBB
8921     BB->addSuccessor(loop1MBB);
8922
8923     // The 4-byte load must be aligned, while a char or short may be
8924     // anywhere in the word.  Hence all this nasty bookkeeping code.
8925     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8926     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8927     //   xori shift, shift1, 24 [16]
8928     //   rlwinm ptr, ptr1, 0, 0, 29
8929     //   slw newval2, newval, shift
8930     //   slw oldval2, oldval,shift
8931     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8932     //   slw mask, mask2, shift
8933     //   and newval3, newval2, mask
8934     //   and oldval3, oldval2, mask
8935     // loop1MBB:
8936     //   lwarx tmpDest, ptr
8937     //   and tmp, tmpDest, mask
8938     //   cmpw tmp, oldval3
8939     //   bne- midMBB
8940     // loop2MBB:
8941     //   andc tmp2, tmpDest, mask
8942     //   or tmp4, tmp2, newval3
8943     //   stwcx. tmp4, ptr
8944     //   bne- loop1MBB
8945     //   b exitBB
8946     // midMBB:
8947     //   stwcx. tmpDest, ptr
8948     // exitBB:
8949     //   srw dest, tmpDest, shift
8950     if (ptrA != ZeroReg) {
8951       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8952       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8953         .addReg(ptrA).addReg(ptrB);
8954     } else {
8955       Ptr1Reg = ptrB;
8956     }
8957     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8958         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8959     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8960         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8961     if (is64bit)
8962       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8963         .addReg(Ptr1Reg).addImm(0).addImm(61);
8964     else
8965       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8966         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8967     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8968         .addReg(newval).addReg(ShiftReg);
8969     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8970         .addReg(oldval).addReg(ShiftReg);
8971     if (is8bit)
8972       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8973     else {
8974       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8975       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8976         .addReg(Mask3Reg).addImm(65535);
8977     }
8978     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8979         .addReg(Mask2Reg).addReg(ShiftReg);
8980     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8981         .addReg(NewVal2Reg).addReg(MaskReg);
8982     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8983         .addReg(OldVal2Reg).addReg(MaskReg);
8984
8985     BB = loop1MBB;
8986     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8987         .addReg(ZeroReg).addReg(PtrReg);
8988     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8989         .addReg(TmpDestReg).addReg(MaskReg);
8990     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8991         .addReg(TmpReg).addReg(OldVal3Reg);
8992     BuildMI(BB, dl, TII->get(PPC::BCC))
8993         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8994     BB->addSuccessor(loop2MBB);
8995     BB->addSuccessor(midMBB);
8996
8997     BB = loop2MBB;
8998     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8999         .addReg(TmpDestReg).addReg(MaskReg);
9000     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9001         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9002     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9003         .addReg(ZeroReg).addReg(PtrReg);
9004     BuildMI(BB, dl, TII->get(PPC::BCC))
9005       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9006     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9007     BB->addSuccessor(loop1MBB);
9008     BB->addSuccessor(exitMBB);
9009
9010     BB = midMBB;
9011     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9012       .addReg(ZeroReg).addReg(PtrReg);
9013     BB->addSuccessor(exitMBB);
9014
9015     //  exitMBB:
9016     //   ...
9017     BB = exitMBB;
9018     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9019       .addReg(ShiftReg);
9020   } else if (MI->getOpcode() == PPC::FADDrtz) {
9021     // This pseudo performs an FADD with rounding mode temporarily forced
9022     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9023     // is not modeled at the SelectionDAG level.
9024     unsigned Dest = MI->getOperand(0).getReg();
9025     unsigned Src1 = MI->getOperand(1).getReg();
9026     unsigned Src2 = MI->getOperand(2).getReg();
9027     DebugLoc dl   = MI->getDebugLoc();
9028
9029     MachineRegisterInfo &RegInfo = F->getRegInfo();
9030     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9031
9032     // Save FPSCR value.
9033     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9034
9035     // Set rounding mode to round-to-zero.
9036     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9037     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9038
9039     // Perform addition.
9040     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9041
9042     // Restore FPSCR value.
9043     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9044   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9045              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
9046              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9047              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9048     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9049                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
9050                       PPC::ANDIo8 : PPC::ANDIo;
9051     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9052                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9053
9054     MachineRegisterInfo &RegInfo = F->getRegInfo();
9055     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9056                                                   &PPC::GPRCRegClass :
9057                                                   &PPC::G8RCRegClass);
9058
9059     DebugLoc dl   = MI->getDebugLoc();
9060     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9061       .addReg(MI->getOperand(1).getReg()).addImm(1);
9062     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9063             MI->getOperand(0).getReg())
9064       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9065   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
9066     DebugLoc Dl = MI->getDebugLoc();
9067     MachineRegisterInfo &RegInfo = F->getRegInfo();
9068     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9069     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9070     return BB;
9071   } else {
9072     llvm_unreachable("Unexpected instr type to insert");
9073   }
9074
9075   MI->eraseFromParent();   // The pseudo instruction is gone now.
9076   return BB;
9077 }
9078
9079 //===----------------------------------------------------------------------===//
9080 // Target Optimization Hooks
9081 //===----------------------------------------------------------------------===//
9082
9083 static std::string getRecipOp(const char *Base, EVT VT) {
9084   std::string RecipOp(Base);
9085   if (VT.getScalarType() == MVT::f64)
9086     RecipOp += "d";
9087   else
9088     RecipOp += "f";
9089
9090   if (VT.isVector())
9091     RecipOp = "vec-" + RecipOp;
9092
9093   return RecipOp;
9094 }
9095
9096 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9097                                             DAGCombinerInfo &DCI,
9098                                             unsigned &RefinementSteps,
9099                                             bool &UseOneConstNR) const {
9100   EVT VT = Operand.getValueType();
9101   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9102       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9103       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9104       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9105       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9106       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9107     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9108     std::string RecipOp = getRecipOp("sqrt", VT);
9109     if (!Recips.isEnabled(RecipOp))
9110       return SDValue();
9111
9112     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9113     UseOneConstNR = true;
9114     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9115   }
9116   return SDValue();
9117 }
9118
9119 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9120                                             DAGCombinerInfo &DCI,
9121                                             unsigned &RefinementSteps) const {
9122   EVT VT = Operand.getValueType();
9123   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9124       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9125       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9126       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9127       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9128       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9129     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9130     std::string RecipOp = getRecipOp("div", VT);
9131     if (!Recips.isEnabled(RecipOp))
9132       return SDValue();
9133
9134     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9135     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9136   }
9137   return SDValue();
9138 }
9139
9140 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
9141   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9142   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9143   // enabled for division), this functionality is redundant with the default
9144   // combiner logic (once the division -> reciprocal/multiply transformation
9145   // has taken place). As a result, this matters more for older cores than for
9146   // newer ones.
9147
9148   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9149   // reciprocal if there are two or more FDIVs (for embedded cores with only
9150   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9151   switch (Subtarget.getDarwinDirective()) {
9152   default:
9153     return NumUsers > 2;
9154   case PPC::DIR_440:
9155   case PPC::DIR_A2:
9156   case PPC::DIR_E500mc:
9157   case PPC::DIR_E5500:
9158     return NumUsers > 1;
9159   }
9160 }
9161
9162 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9163                             unsigned Bytes, int Dist,
9164                             SelectionDAG &DAG) {
9165   if (VT.getSizeInBits() / 8 != Bytes)
9166     return false;
9167
9168   SDValue BaseLoc = Base->getBasePtr();
9169   if (Loc.getOpcode() == ISD::FrameIndex) {
9170     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9171       return false;
9172     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9173     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9174     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9175     int FS  = MFI->getObjectSize(FI);
9176     int BFS = MFI->getObjectSize(BFI);
9177     if (FS != BFS || FS != (int)Bytes) return false;
9178     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9179   }
9180
9181   // Handle X+C
9182   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
9183       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
9184     return true;
9185
9186   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9187   const GlobalValue *GV1 = nullptr;
9188   const GlobalValue *GV2 = nullptr;
9189   int64_t Offset1 = 0;
9190   int64_t Offset2 = 0;
9191   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9192   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9193   if (isGA1 && isGA2 && GV1 == GV2)
9194     return Offset1 == (Offset2 + Dist*Bytes);
9195   return false;
9196 }
9197
9198 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9199 // not enforce equality of the chain operands.
9200 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9201                             unsigned Bytes, int Dist,
9202                             SelectionDAG &DAG) {
9203   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9204     EVT VT = LS->getMemoryVT();
9205     SDValue Loc = LS->getBasePtr();
9206     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9207   }
9208
9209   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9210     EVT VT;
9211     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9212     default: return false;
9213     case Intrinsic::ppc_qpx_qvlfd:
9214     case Intrinsic::ppc_qpx_qvlfda:
9215       VT = MVT::v4f64;
9216       break;
9217     case Intrinsic::ppc_qpx_qvlfs:
9218     case Intrinsic::ppc_qpx_qvlfsa:
9219       VT = MVT::v4f32;
9220       break;
9221     case Intrinsic::ppc_qpx_qvlfcd:
9222     case Intrinsic::ppc_qpx_qvlfcda:
9223       VT = MVT::v2f64;
9224       break;
9225     case Intrinsic::ppc_qpx_qvlfcs:
9226     case Intrinsic::ppc_qpx_qvlfcsa:
9227       VT = MVT::v2f32;
9228       break;
9229     case Intrinsic::ppc_qpx_qvlfiwa:
9230     case Intrinsic::ppc_qpx_qvlfiwz:
9231     case Intrinsic::ppc_altivec_lvx:
9232     case Intrinsic::ppc_altivec_lvxl:
9233     case Intrinsic::ppc_vsx_lxvw4x:
9234       VT = MVT::v4i32;
9235       break;
9236     case Intrinsic::ppc_vsx_lxvd2x:
9237       VT = MVT::v2f64;
9238       break;
9239     case Intrinsic::ppc_altivec_lvebx:
9240       VT = MVT::i8;
9241       break;
9242     case Intrinsic::ppc_altivec_lvehx:
9243       VT = MVT::i16;
9244       break;
9245     case Intrinsic::ppc_altivec_lvewx:
9246       VT = MVT::i32;
9247       break;
9248     }
9249
9250     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9251   }
9252
9253   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9254     EVT VT;
9255     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9256     default: return false;
9257     case Intrinsic::ppc_qpx_qvstfd:
9258     case Intrinsic::ppc_qpx_qvstfda:
9259       VT = MVT::v4f64;
9260       break;
9261     case Intrinsic::ppc_qpx_qvstfs:
9262     case Intrinsic::ppc_qpx_qvstfsa:
9263       VT = MVT::v4f32;
9264       break;
9265     case Intrinsic::ppc_qpx_qvstfcd:
9266     case Intrinsic::ppc_qpx_qvstfcda:
9267       VT = MVT::v2f64;
9268       break;
9269     case Intrinsic::ppc_qpx_qvstfcs:
9270     case Intrinsic::ppc_qpx_qvstfcsa:
9271       VT = MVT::v2f32;
9272       break;
9273     case Intrinsic::ppc_qpx_qvstfiw:
9274     case Intrinsic::ppc_qpx_qvstfiwa:
9275     case Intrinsic::ppc_altivec_stvx:
9276     case Intrinsic::ppc_altivec_stvxl:
9277     case Intrinsic::ppc_vsx_stxvw4x:
9278       VT = MVT::v4i32;
9279       break;
9280     case Intrinsic::ppc_vsx_stxvd2x:
9281       VT = MVT::v2f64;
9282       break;
9283     case Intrinsic::ppc_altivec_stvebx:
9284       VT = MVT::i8;
9285       break;
9286     case Intrinsic::ppc_altivec_stvehx:
9287       VT = MVT::i16;
9288       break;
9289     case Intrinsic::ppc_altivec_stvewx:
9290       VT = MVT::i32;
9291       break;
9292     }
9293
9294     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9295   }
9296
9297   return false;
9298 }
9299
9300 // Return true is there is a nearyby consecutive load to the one provided
9301 // (regardless of alignment). We search up and down the chain, looking though
9302 // token factors and other loads (but nothing else). As a result, a true result
9303 // indicates that it is safe to create a new consecutive load adjacent to the
9304 // load provided.
9305 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9306   SDValue Chain = LD->getChain();
9307   EVT VT = LD->getMemoryVT();
9308
9309   SmallSet<SDNode *, 16> LoadRoots;
9310   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9311   SmallSet<SDNode *, 16> Visited;
9312
9313   // First, search up the chain, branching to follow all token-factor operands.
9314   // If we find a consecutive load, then we're done, otherwise, record all
9315   // nodes just above the top-level loads and token factors.
9316   while (!Queue.empty()) {
9317     SDNode *ChainNext = Queue.pop_back_val();
9318     if (!Visited.insert(ChainNext).second)
9319       continue;
9320
9321     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9322       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9323         return true;
9324
9325       if (!Visited.count(ChainLD->getChain().getNode()))
9326         Queue.push_back(ChainLD->getChain().getNode());
9327     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9328       for (const SDUse &O : ChainNext->ops())
9329         if (!Visited.count(O.getNode()))
9330           Queue.push_back(O.getNode());
9331     } else
9332       LoadRoots.insert(ChainNext);
9333   }
9334
9335   // Second, search down the chain, starting from the top-level nodes recorded
9336   // in the first phase. These top-level nodes are the nodes just above all
9337   // loads and token factors. Starting with their uses, recursively look though
9338   // all loads (just the chain uses) and token factors to find a consecutive
9339   // load.
9340   Visited.clear();
9341   Queue.clear();
9342
9343   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9344        IE = LoadRoots.end(); I != IE; ++I) {
9345     Queue.push_back(*I);
9346        
9347     while (!Queue.empty()) {
9348       SDNode *LoadRoot = Queue.pop_back_val();
9349       if (!Visited.insert(LoadRoot).second)
9350         continue;
9351
9352       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9353         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9354           return true;
9355
9356       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9357            UE = LoadRoot->use_end(); UI != UE; ++UI)
9358         if (((isa<MemSDNode>(*UI) &&
9359             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9360             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9361           Queue.push_back(*UI);
9362     }
9363   }
9364
9365   return false;
9366 }
9367
9368 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9369                                                   DAGCombinerInfo &DCI) const {
9370   SelectionDAG &DAG = DCI.DAG;
9371   SDLoc dl(N);
9372
9373   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9374   // If we're tracking CR bits, we need to be careful that we don't have:
9375   //   trunc(binary-ops(zext(x), zext(y)))
9376   // or
9377   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9378   // such that we're unnecessarily moving things into GPRs when it would be
9379   // better to keep them in CR bits.
9380
9381   // Note that trunc here can be an actual i1 trunc, or can be the effective
9382   // truncation that comes from a setcc or select_cc.
9383   if (N->getOpcode() == ISD::TRUNCATE &&
9384       N->getValueType(0) != MVT::i1)
9385     return SDValue();
9386
9387   if (N->getOperand(0).getValueType() != MVT::i32 &&
9388       N->getOperand(0).getValueType() != MVT::i64)
9389     return SDValue();
9390
9391   if (N->getOpcode() == ISD::SETCC ||
9392       N->getOpcode() == ISD::SELECT_CC) {
9393     // If we're looking at a comparison, then we need to make sure that the
9394     // high bits (all except for the first) don't matter the result.
9395     ISD::CondCode CC =
9396       cast<CondCodeSDNode>(N->getOperand(
9397         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9398     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9399
9400     if (ISD::isSignedIntSetCC(CC)) {
9401       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9402           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9403         return SDValue();
9404     } else if (ISD::isUnsignedIntSetCC(CC)) {
9405       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9406                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9407           !DAG.MaskedValueIsZero(N->getOperand(1),
9408                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9409         return SDValue();
9410     } else {
9411       // This is neither a signed nor an unsigned comparison, just make sure
9412       // that the high bits are equal.
9413       APInt Op1Zero, Op1One;
9414       APInt Op2Zero, Op2One;
9415       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9416       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9417
9418       // We don't really care about what is known about the first bit (if
9419       // anything), so clear it in all masks prior to comparing them.
9420       Op1Zero.clearBit(0); Op1One.clearBit(0);
9421       Op2Zero.clearBit(0); Op2One.clearBit(0);
9422
9423       if (Op1Zero != Op2Zero || Op1One != Op2One)
9424         return SDValue();
9425     }
9426   }
9427
9428   // We now know that the higher-order bits are irrelevant, we just need to
9429   // make sure that all of the intermediate operations are bit operations, and
9430   // all inputs are extensions.
9431   if (N->getOperand(0).getOpcode() != ISD::AND &&
9432       N->getOperand(0).getOpcode() != ISD::OR  &&
9433       N->getOperand(0).getOpcode() != ISD::XOR &&
9434       N->getOperand(0).getOpcode() != ISD::SELECT &&
9435       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9436       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9437       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9438       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9439       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9440     return SDValue();
9441
9442   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9443       N->getOperand(1).getOpcode() != ISD::AND &&
9444       N->getOperand(1).getOpcode() != ISD::OR  &&
9445       N->getOperand(1).getOpcode() != ISD::XOR &&
9446       N->getOperand(1).getOpcode() != ISD::SELECT &&
9447       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9448       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9449       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9450       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9451       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9452     return SDValue();
9453
9454   SmallVector<SDValue, 4> Inputs;
9455   SmallVector<SDValue, 8> BinOps, PromOps;
9456   SmallPtrSet<SDNode *, 16> Visited;
9457
9458   for (unsigned i = 0; i < 2; ++i) {
9459     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9460           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9461           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9462           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9463         isa<ConstantSDNode>(N->getOperand(i)))
9464       Inputs.push_back(N->getOperand(i));
9465     else
9466       BinOps.push_back(N->getOperand(i));
9467
9468     if (N->getOpcode() == ISD::TRUNCATE)
9469       break;
9470   }
9471
9472   // Visit all inputs, collect all binary operations (and, or, xor and
9473   // select) that are all fed by extensions. 
9474   while (!BinOps.empty()) {
9475     SDValue BinOp = BinOps.back();
9476     BinOps.pop_back();
9477
9478     if (!Visited.insert(BinOp.getNode()).second)
9479       continue;
9480
9481     PromOps.push_back(BinOp);
9482
9483     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9484       // The condition of the select is not promoted.
9485       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9486         continue;
9487       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9488         continue;
9489
9490       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9491             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9492             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9493            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9494           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9495         Inputs.push_back(BinOp.getOperand(i)); 
9496       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9497                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9498                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9499                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9500                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9501                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9502                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9503                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9504                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9505         BinOps.push_back(BinOp.getOperand(i));
9506       } else {
9507         // We have an input that is not an extension or another binary
9508         // operation; we'll abort this transformation.
9509         return SDValue();
9510       }
9511     }
9512   }
9513
9514   // Make sure that this is a self-contained cluster of operations (which
9515   // is not quite the same thing as saying that everything has only one
9516   // use).
9517   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9518     if (isa<ConstantSDNode>(Inputs[i]))
9519       continue;
9520
9521     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9522                               UE = Inputs[i].getNode()->use_end();
9523          UI != UE; ++UI) {
9524       SDNode *User = *UI;
9525       if (User != N && !Visited.count(User))
9526         return SDValue();
9527
9528       // Make sure that we're not going to promote the non-output-value
9529       // operand(s) or SELECT or SELECT_CC.
9530       // FIXME: Although we could sometimes handle this, and it does occur in
9531       // practice that one of the condition inputs to the select is also one of
9532       // the outputs, we currently can't deal with this.
9533       if (User->getOpcode() == ISD::SELECT) {
9534         if (User->getOperand(0) == Inputs[i])
9535           return SDValue();
9536       } else if (User->getOpcode() == ISD::SELECT_CC) {
9537         if (User->getOperand(0) == Inputs[i] ||
9538             User->getOperand(1) == Inputs[i])
9539           return SDValue();
9540       }
9541     }
9542   }
9543
9544   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9545     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9546                               UE = PromOps[i].getNode()->use_end();
9547          UI != UE; ++UI) {
9548       SDNode *User = *UI;
9549       if (User != N && !Visited.count(User))
9550         return SDValue();
9551
9552       // Make sure that we're not going to promote the non-output-value
9553       // operand(s) or SELECT or SELECT_CC.
9554       // FIXME: Although we could sometimes handle this, and it does occur in
9555       // practice that one of the condition inputs to the select is also one of
9556       // the outputs, we currently can't deal with this.
9557       if (User->getOpcode() == ISD::SELECT) {
9558         if (User->getOperand(0) == PromOps[i])
9559           return SDValue();
9560       } else if (User->getOpcode() == ISD::SELECT_CC) {
9561         if (User->getOperand(0) == PromOps[i] ||
9562             User->getOperand(1) == PromOps[i])
9563           return SDValue();
9564       }
9565     }
9566   }
9567
9568   // Replace all inputs with the extension operand.
9569   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9570     // Constants may have users outside the cluster of to-be-promoted nodes,
9571     // and so we need to replace those as we do the promotions.
9572     if (isa<ConstantSDNode>(Inputs[i]))
9573       continue;
9574     else
9575       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9576   }
9577
9578   // Replace all operations (these are all the same, but have a different
9579   // (i1) return type). DAG.getNode will validate that the types of
9580   // a binary operator match, so go through the list in reverse so that
9581   // we've likely promoted both operands first. Any intermediate truncations or
9582   // extensions disappear.
9583   while (!PromOps.empty()) {
9584     SDValue PromOp = PromOps.back();
9585     PromOps.pop_back();
9586
9587     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9588         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9589         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9590         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9591       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9592           PromOp.getOperand(0).getValueType() != MVT::i1) {
9593         // The operand is not yet ready (see comment below).
9594         PromOps.insert(PromOps.begin(), PromOp);
9595         continue;
9596       }
9597
9598       SDValue RepValue = PromOp.getOperand(0);
9599       if (isa<ConstantSDNode>(RepValue))
9600         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9601
9602       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9603       continue;
9604     }
9605
9606     unsigned C;
9607     switch (PromOp.getOpcode()) {
9608     default:             C = 0; break;
9609     case ISD::SELECT:    C = 1; break;
9610     case ISD::SELECT_CC: C = 2; break;
9611     }
9612
9613     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9614          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9615         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9616          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9617       // The to-be-promoted operands of this node have not yet been
9618       // promoted (this should be rare because we're going through the
9619       // list backward, but if one of the operands has several users in
9620       // this cluster of to-be-promoted nodes, it is possible).
9621       PromOps.insert(PromOps.begin(), PromOp);
9622       continue;
9623     }
9624
9625     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9626                                 PromOp.getNode()->op_end());
9627
9628     // If there are any constant inputs, make sure they're replaced now.
9629     for (unsigned i = 0; i < 2; ++i)
9630       if (isa<ConstantSDNode>(Ops[C+i]))
9631         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9632
9633     DAG.ReplaceAllUsesOfValueWith(PromOp,
9634       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9635   }
9636
9637   // Now we're left with the initial truncation itself.
9638   if (N->getOpcode() == ISD::TRUNCATE)
9639     return N->getOperand(0);
9640
9641   // Otherwise, this is a comparison. The operands to be compared have just
9642   // changed type (to i1), but everything else is the same.
9643   return SDValue(N, 0);
9644 }
9645
9646 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9647                                                   DAGCombinerInfo &DCI) const {
9648   SelectionDAG &DAG = DCI.DAG;
9649   SDLoc dl(N);
9650
9651   // If we're tracking CR bits, we need to be careful that we don't have:
9652   //   zext(binary-ops(trunc(x), trunc(y)))
9653   // or
9654   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9655   // such that we're unnecessarily moving things into CR bits that can more
9656   // efficiently stay in GPRs. Note that if we're not certain that the high
9657   // bits are set as required by the final extension, we still may need to do
9658   // some masking to get the proper behavior.
9659
9660   // This same functionality is important on PPC64 when dealing with
9661   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9662   // the return values of functions. Because it is so similar, it is handled
9663   // here as well.
9664
9665   if (N->getValueType(0) != MVT::i32 &&
9666       N->getValueType(0) != MVT::i64)
9667     return SDValue();
9668
9669   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9670         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9671     return SDValue();
9672
9673   if (N->getOperand(0).getOpcode() != ISD::AND &&
9674       N->getOperand(0).getOpcode() != ISD::OR  &&
9675       N->getOperand(0).getOpcode() != ISD::XOR &&
9676       N->getOperand(0).getOpcode() != ISD::SELECT &&
9677       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9678     return SDValue();
9679
9680   SmallVector<SDValue, 4> Inputs;
9681   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9682   SmallPtrSet<SDNode *, 16> Visited;
9683
9684   // Visit all inputs, collect all binary operations (and, or, xor and
9685   // select) that are all fed by truncations. 
9686   while (!BinOps.empty()) {
9687     SDValue BinOp = BinOps.back();
9688     BinOps.pop_back();
9689
9690     if (!Visited.insert(BinOp.getNode()).second)
9691       continue;
9692
9693     PromOps.push_back(BinOp);
9694
9695     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9696       // The condition of the select is not promoted.
9697       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9698         continue;
9699       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9700         continue;
9701
9702       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9703           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9704         Inputs.push_back(BinOp.getOperand(i)); 
9705       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9706                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9707                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9708                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9709                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9710         BinOps.push_back(BinOp.getOperand(i));
9711       } else {
9712         // We have an input that is not a truncation or another binary
9713         // operation; we'll abort this transformation.
9714         return SDValue();
9715       }
9716     }
9717   }
9718
9719   // The operands of a select that must be truncated when the select is
9720   // promoted because the operand is actually part of the to-be-promoted set.
9721   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9722
9723   // Make sure that this is a self-contained cluster of operations (which
9724   // is not quite the same thing as saying that everything has only one
9725   // use).
9726   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9727     if (isa<ConstantSDNode>(Inputs[i]))
9728       continue;
9729
9730     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9731                               UE = Inputs[i].getNode()->use_end();
9732          UI != UE; ++UI) {
9733       SDNode *User = *UI;
9734       if (User != N && !Visited.count(User))
9735         return SDValue();
9736
9737       // If we're going to promote the non-output-value operand(s) or SELECT or
9738       // SELECT_CC, record them for truncation.
9739       if (User->getOpcode() == ISD::SELECT) {
9740         if (User->getOperand(0) == Inputs[i])
9741           SelectTruncOp[0].insert(std::make_pair(User,
9742                                     User->getOperand(0).getValueType()));
9743       } else if (User->getOpcode() == ISD::SELECT_CC) {
9744         if (User->getOperand(0) == Inputs[i])
9745           SelectTruncOp[0].insert(std::make_pair(User,
9746                                     User->getOperand(0).getValueType()));
9747         if (User->getOperand(1) == Inputs[i])
9748           SelectTruncOp[1].insert(std::make_pair(User,
9749                                     User->getOperand(1).getValueType()));
9750       }
9751     }
9752   }
9753
9754   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9755     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9756                               UE = PromOps[i].getNode()->use_end();
9757          UI != UE; ++UI) {
9758       SDNode *User = *UI;
9759       if (User != N && !Visited.count(User))
9760         return SDValue();
9761
9762       // If we're going to promote the non-output-value operand(s) or SELECT or
9763       // SELECT_CC, record them for truncation.
9764       if (User->getOpcode() == ISD::SELECT) {
9765         if (User->getOperand(0) == PromOps[i])
9766           SelectTruncOp[0].insert(std::make_pair(User,
9767                                     User->getOperand(0).getValueType()));
9768       } else if (User->getOpcode() == ISD::SELECT_CC) {
9769         if (User->getOperand(0) == PromOps[i])
9770           SelectTruncOp[0].insert(std::make_pair(User,
9771                                     User->getOperand(0).getValueType()));
9772         if (User->getOperand(1) == PromOps[i])
9773           SelectTruncOp[1].insert(std::make_pair(User,
9774                                     User->getOperand(1).getValueType()));
9775       }
9776     }
9777   }
9778
9779   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9780   bool ReallyNeedsExt = false;
9781   if (N->getOpcode() != ISD::ANY_EXTEND) {
9782     // If all of the inputs are not already sign/zero extended, then
9783     // we'll still need to do that at the end.
9784     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9785       if (isa<ConstantSDNode>(Inputs[i]))
9786         continue;
9787
9788       unsigned OpBits =
9789         Inputs[i].getOperand(0).getValueSizeInBits();
9790       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9791
9792       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9793            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9794                                   APInt::getHighBitsSet(OpBits,
9795                                                         OpBits-PromBits))) ||
9796           (N->getOpcode() == ISD::SIGN_EXTEND &&
9797            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9798              (OpBits-(PromBits-1)))) {
9799         ReallyNeedsExt = true;
9800         break;
9801       }
9802     }
9803   }
9804
9805   // Replace all inputs, either with the truncation operand, or a
9806   // truncation or extension to the final output type.
9807   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9808     // Constant inputs need to be replaced with the to-be-promoted nodes that
9809     // use them because they might have users outside of the cluster of
9810     // promoted nodes.
9811     if (isa<ConstantSDNode>(Inputs[i]))
9812       continue;
9813
9814     SDValue InSrc = Inputs[i].getOperand(0);
9815     if (Inputs[i].getValueType() == N->getValueType(0))
9816       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9817     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9818       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9819         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9820     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9821       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9822         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9823     else
9824       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9825         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9826   }
9827
9828   // Replace all operations (these are all the same, but have a different
9829   // (promoted) return type). DAG.getNode will validate that the types of
9830   // a binary operator match, so go through the list in reverse so that
9831   // we've likely promoted both operands first.
9832   while (!PromOps.empty()) {
9833     SDValue PromOp = PromOps.back();
9834     PromOps.pop_back();
9835
9836     unsigned C;
9837     switch (PromOp.getOpcode()) {
9838     default:             C = 0; break;
9839     case ISD::SELECT:    C = 1; break;
9840     case ISD::SELECT_CC: C = 2; break;
9841     }
9842
9843     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9844          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9845         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9846          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9847       // The to-be-promoted operands of this node have not yet been
9848       // promoted (this should be rare because we're going through the
9849       // list backward, but if one of the operands has several users in
9850       // this cluster of to-be-promoted nodes, it is possible).
9851       PromOps.insert(PromOps.begin(), PromOp);
9852       continue;
9853     }
9854
9855     // For SELECT and SELECT_CC nodes, we do a similar check for any
9856     // to-be-promoted comparison inputs.
9857     if (PromOp.getOpcode() == ISD::SELECT ||
9858         PromOp.getOpcode() == ISD::SELECT_CC) {
9859       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9860            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9861           (SelectTruncOp[1].count(PromOp.getNode()) &&
9862            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9863         PromOps.insert(PromOps.begin(), PromOp);
9864         continue;
9865       }
9866     }
9867
9868     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9869                                 PromOp.getNode()->op_end());
9870
9871     // If this node has constant inputs, then they'll need to be promoted here.
9872     for (unsigned i = 0; i < 2; ++i) {
9873       if (!isa<ConstantSDNode>(Ops[C+i]))
9874         continue;
9875       if (Ops[C+i].getValueType() == N->getValueType(0))
9876         continue;
9877
9878       if (N->getOpcode() == ISD::SIGN_EXTEND)
9879         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9880       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9881         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9882       else
9883         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9884     }
9885
9886     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9887     // truncate them again to the original value type.
9888     if (PromOp.getOpcode() == ISD::SELECT ||
9889         PromOp.getOpcode() == ISD::SELECT_CC) {
9890       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9891       if (SI0 != SelectTruncOp[0].end())
9892         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9893       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9894       if (SI1 != SelectTruncOp[1].end())
9895         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9896     }
9897
9898     DAG.ReplaceAllUsesOfValueWith(PromOp,
9899       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9900   }
9901
9902   // Now we're left with the initial extension itself.
9903   if (!ReallyNeedsExt)
9904     return N->getOperand(0);
9905
9906   // To zero extend, just mask off everything except for the first bit (in the
9907   // i1 case).
9908   if (N->getOpcode() == ISD::ZERO_EXTEND)
9909     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9910                        DAG.getConstant(APInt::getLowBitsSet(
9911                                          N->getValueSizeInBits(0), PromBits),
9912                                        dl, N->getValueType(0)));
9913
9914   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9915          "Invalid extension type");
9916   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
9917   SDValue ShiftCst =
9918     DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9919   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9920                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9921                                  N->getOperand(0), ShiftCst), ShiftCst);
9922 }
9923
9924 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9925                                               DAGCombinerInfo &DCI) const {
9926   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9927           N->getOpcode() == ISD::UINT_TO_FP) &&
9928          "Need an int -> FP conversion node here");
9929
9930   if (!Subtarget.has64BitSupport())
9931     return SDValue();
9932
9933   SelectionDAG &DAG = DCI.DAG;
9934   SDLoc dl(N);
9935   SDValue Op(N, 0);
9936
9937   // Don't handle ppc_fp128 here or i1 conversions.
9938   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9939     return SDValue();
9940   if (Op.getOperand(0).getValueType() == MVT::i1)
9941     return SDValue();
9942
9943   // For i32 intermediate values, unfortunately, the conversion functions
9944   // leave the upper 32 bits of the value are undefined. Within the set of
9945   // scalar instructions, we have no method for zero- or sign-extending the
9946   // value. Thus, we cannot handle i32 intermediate values here.
9947   if (Op.getOperand(0).getValueType() == MVT::i32)
9948     return SDValue();
9949
9950   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9951          "UINT_TO_FP is supported only with FPCVT");
9952
9953   // If we have FCFIDS, then use it when converting to single-precision.
9954   // Otherwise, convert to double-precision and then round.
9955   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9956                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9957                                                             : PPCISD::FCFIDS)
9958                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9959                                                             : PPCISD::FCFID);
9960   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9961                   ? MVT::f32
9962                   : MVT::f64;
9963
9964   // If we're converting from a float, to an int, and back to a float again,
9965   // then we don't need the store/load pair at all.
9966   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9967        Subtarget.hasFPCVT()) ||
9968       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9969     SDValue Src = Op.getOperand(0).getOperand(0);
9970     if (Src.getValueType() == MVT::f32) {
9971       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9972       DCI.AddToWorklist(Src.getNode());
9973     } else if (Src.getValueType() != MVT::f64) {
9974       // Make sure that we don't pick up a ppc_fp128 source value.
9975       return SDValue();
9976     }
9977
9978     unsigned FCTOp =
9979       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9980                                                         PPCISD::FCTIDUZ;
9981
9982     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9983     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9984
9985     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9986       FP = DAG.getNode(ISD::FP_ROUND, dl,
9987                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
9988       DCI.AddToWorklist(FP.getNode());
9989     }
9990
9991     return FP;
9992   }
9993
9994   return SDValue();
9995 }
9996
9997 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9998 // builtins) into loads with swaps.
9999 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10000                                               DAGCombinerInfo &DCI) const {
10001   SelectionDAG &DAG = DCI.DAG;
10002   SDLoc dl(N);
10003   SDValue Chain;
10004   SDValue Base;
10005   MachineMemOperand *MMO;
10006
10007   switch (N->getOpcode()) {
10008   default:
10009     llvm_unreachable("Unexpected opcode for little endian VSX load");
10010   case ISD::LOAD: {
10011     LoadSDNode *LD = cast<LoadSDNode>(N);
10012     Chain = LD->getChain();
10013     Base = LD->getBasePtr();
10014     MMO = LD->getMemOperand();
10015     // If the MMO suggests this isn't a load of a full vector, leave
10016     // things alone.  For a built-in, we have to make the change for
10017     // correctness, so if there is a size problem that will be a bug.
10018     if (MMO->getSize() < 16)
10019       return SDValue();
10020     break;
10021   }
10022   case ISD::INTRINSIC_W_CHAIN: {
10023     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10024     Chain = Intrin->getChain();
10025     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10026     // us what we want. Get operand 2 instead.
10027     Base = Intrin->getOperand(2);
10028     MMO = Intrin->getMemOperand();
10029     break;
10030   }
10031   }
10032
10033   MVT VecTy = N->getValueType(0).getSimpleVT();
10034   SDValue LoadOps[] = { Chain, Base };
10035   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10036                                          DAG.getVTList(VecTy, MVT::Other),
10037                                          LoadOps, VecTy, MMO);
10038   DCI.AddToWorklist(Load.getNode());
10039   Chain = Load.getValue(1);
10040   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10041                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
10042   DCI.AddToWorklist(Swap.getNode());
10043   return Swap;
10044 }
10045
10046 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10047 // builtins) into stores with swaps.
10048 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10049                                                DAGCombinerInfo &DCI) const {
10050   SelectionDAG &DAG = DCI.DAG;
10051   SDLoc dl(N);
10052   SDValue Chain;
10053   SDValue Base;
10054   unsigned SrcOpnd;
10055   MachineMemOperand *MMO;
10056
10057   switch (N->getOpcode()) {
10058   default:
10059     llvm_unreachable("Unexpected opcode for little endian VSX store");
10060   case ISD::STORE: {
10061     StoreSDNode *ST = cast<StoreSDNode>(N);
10062     Chain = ST->getChain();
10063     Base = ST->getBasePtr();
10064     MMO = ST->getMemOperand();
10065     SrcOpnd = 1;
10066     // If the MMO suggests this isn't a store of a full vector, leave
10067     // things alone.  For a built-in, we have to make the change for
10068     // correctness, so if there is a size problem that will be a bug.
10069     if (MMO->getSize() < 16)
10070       return SDValue();
10071     break;
10072   }
10073   case ISD::INTRINSIC_VOID: {
10074     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10075     Chain = Intrin->getChain();
10076     // Intrin->getBasePtr() oddly does not get what we want.
10077     Base = Intrin->getOperand(3);
10078     MMO = Intrin->getMemOperand();
10079     SrcOpnd = 2;
10080     break;
10081   }
10082   }
10083
10084   SDValue Src = N->getOperand(SrcOpnd);
10085   MVT VecTy = Src.getValueType().getSimpleVT();
10086   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10087                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
10088   DCI.AddToWorklist(Swap.getNode());
10089   Chain = Swap.getValue(1);
10090   SDValue StoreOps[] = { Chain, Swap, Base };
10091   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10092                                           DAG.getVTList(MVT::Other),
10093                                           StoreOps, VecTy, MMO);
10094   DCI.AddToWorklist(Store.getNode());
10095   return Store;
10096 }
10097
10098 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10099                                              DAGCombinerInfo &DCI) const {
10100   SelectionDAG &DAG = DCI.DAG;
10101   SDLoc dl(N);
10102   switch (N->getOpcode()) {
10103   default: break;
10104   case PPCISD::SHL:
10105     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10106       if (C->isNullValue())   // 0 << V -> 0.
10107         return N->getOperand(0);
10108     }
10109     break;
10110   case PPCISD::SRL:
10111     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10112       if (C->isNullValue())   // 0 >>u V -> 0.
10113         return N->getOperand(0);
10114     }
10115     break;
10116   case PPCISD::SRA:
10117     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10118       if (C->isNullValue() ||   //  0 >>s V -> 0.
10119           C->isAllOnesValue())    // -1 >>s V -> -1.
10120         return N->getOperand(0);
10121     }
10122     break;
10123   case ISD::SIGN_EXTEND:
10124   case ISD::ZERO_EXTEND:
10125   case ISD::ANY_EXTEND: 
10126     return DAGCombineExtBoolTrunc(N, DCI);
10127   case ISD::TRUNCATE:
10128   case ISD::SETCC:
10129   case ISD::SELECT_CC:
10130     return DAGCombineTruncBoolExt(N, DCI);
10131   case ISD::SINT_TO_FP:
10132   case ISD::UINT_TO_FP:
10133     return combineFPToIntToFP(N, DCI);
10134   case ISD::STORE: {
10135     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10136     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10137         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10138         N->getOperand(1).getValueType() == MVT::i32 &&
10139         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10140       SDValue Val = N->getOperand(1).getOperand(0);
10141       if (Val.getValueType() == MVT::f32) {
10142         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10143         DCI.AddToWorklist(Val.getNode());
10144       }
10145       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10146       DCI.AddToWorklist(Val.getNode());
10147
10148       SDValue Ops[] = {
10149         N->getOperand(0), Val, N->getOperand(2),
10150         DAG.getValueType(N->getOperand(1).getValueType())
10151       };
10152
10153       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10154               DAG.getVTList(MVT::Other), Ops,
10155               cast<StoreSDNode>(N)->getMemoryVT(),
10156               cast<StoreSDNode>(N)->getMemOperand());
10157       DCI.AddToWorklist(Val.getNode());
10158       return Val;
10159     }
10160
10161     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10162     if (cast<StoreSDNode>(N)->isUnindexed() &&
10163         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10164         N->getOperand(1).getNode()->hasOneUse() &&
10165         (N->getOperand(1).getValueType() == MVT::i32 ||
10166          N->getOperand(1).getValueType() == MVT::i16 ||
10167          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10168           N->getOperand(1).getValueType() == MVT::i64))) {
10169       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10170       // Do an any-extend to 32-bits if this is a half-word input.
10171       if (BSwapOp.getValueType() == MVT::i16)
10172         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10173
10174       SDValue Ops[] = {
10175         N->getOperand(0), BSwapOp, N->getOperand(2),
10176         DAG.getValueType(N->getOperand(1).getValueType())
10177       };
10178       return
10179         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10180                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10181                                 cast<StoreSDNode>(N)->getMemOperand());
10182     }
10183
10184     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10185     EVT VT = N->getOperand(1).getValueType();
10186     if (VT.isSimple()) {
10187       MVT StoreVT = VT.getSimpleVT();
10188       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10189           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10190            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10191         return expandVSXStoreForLE(N, DCI);
10192     }
10193     break;
10194   }
10195   case ISD::LOAD: {
10196     LoadSDNode *LD = cast<LoadSDNode>(N);
10197     EVT VT = LD->getValueType(0);
10198
10199     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10200     if (VT.isSimple()) {
10201       MVT LoadVT = VT.getSimpleVT();
10202       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10203           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10204            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10205         return expandVSXLoadForLE(N, DCI);
10206     }
10207
10208     EVT MemVT = LD->getMemoryVT();
10209     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10210     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10211     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10212     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10213     if (LD->isUnindexed() && VT.isVector() &&
10214         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10215           // P8 and later hardware should just use LOAD.
10216           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10217                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10218          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10219           LD->getAlignment() >= ScalarABIAlignment)) &&
10220         LD->getAlignment() < ABIAlignment) {
10221       // This is a type-legal unaligned Altivec or QPX load.
10222       SDValue Chain = LD->getChain();
10223       SDValue Ptr = LD->getBasePtr();
10224       bool isLittleEndian = Subtarget.isLittleEndian();
10225
10226       // This implements the loading of unaligned vectors as described in
10227       // the venerable Apple Velocity Engine overview. Specifically:
10228       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10229       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10230       //
10231       // The general idea is to expand a sequence of one or more unaligned
10232       // loads into an alignment-based permutation-control instruction (lvsl
10233       // or lvsr), a series of regular vector loads (which always truncate
10234       // their input address to an aligned address), and a series of
10235       // permutations.  The results of these permutations are the requested
10236       // loaded values.  The trick is that the last "extra" load is not taken
10237       // from the address you might suspect (sizeof(vector) bytes after the
10238       // last requested load), but rather sizeof(vector) - 1 bytes after the
10239       // last requested vector. The point of this is to avoid a page fault if
10240       // the base address happened to be aligned. This works because if the
10241       // base address is aligned, then adding less than a full vector length
10242       // will cause the last vector in the sequence to be (re)loaded.
10243       // Otherwise, the next vector will be fetched as you might suspect was
10244       // necessary.
10245
10246       // We might be able to reuse the permutation generation from
10247       // a different base address offset from this one by an aligned amount.
10248       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10249       // optimization later.
10250       Intrinsic::ID Intr, IntrLD, IntrPerm;
10251       MVT PermCntlTy, PermTy, LDTy;
10252       if (Subtarget.hasAltivec()) {
10253         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10254                                  Intrinsic::ppc_altivec_lvsl;
10255         IntrLD = Intrinsic::ppc_altivec_lvx;
10256         IntrPerm = Intrinsic::ppc_altivec_vperm;
10257         PermCntlTy = MVT::v16i8;
10258         PermTy = MVT::v4i32;
10259         LDTy = MVT::v4i32;
10260       } else {
10261         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10262                                        Intrinsic::ppc_qpx_qvlpcls;
10263         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10264                                        Intrinsic::ppc_qpx_qvlfs;
10265         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10266         PermCntlTy = MVT::v4f64;
10267         PermTy = MVT::v4f64;
10268         LDTy = MemVT.getSimpleVT();
10269       }
10270
10271       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10272
10273       // Create the new MMO for the new base load. It is like the original MMO,
10274       // but represents an area in memory almost twice the vector size centered
10275       // on the original address. If the address is unaligned, we might start
10276       // reading up to (sizeof(vector)-1) bytes below the address of the
10277       // original unaligned load.
10278       MachineFunction &MF = DAG.getMachineFunction();
10279       MachineMemOperand *BaseMMO =
10280         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10281                                 2*MemVT.getStoreSize()-1);
10282
10283       // Create the new base load.
10284       SDValue LDXIntID =
10285           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10286       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10287       SDValue BaseLoad =
10288         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10289                                 DAG.getVTList(PermTy, MVT::Other),
10290                                 BaseLoadOps, LDTy, BaseMMO);
10291
10292       // Note that the value of IncOffset (which is provided to the next
10293       // load's pointer info offset value, and thus used to calculate the
10294       // alignment), and the value of IncValue (which is actually used to
10295       // increment the pointer value) are different! This is because we
10296       // require the next load to appear to be aligned, even though it
10297       // is actually offset from the base pointer by a lesser amount.
10298       int IncOffset = VT.getSizeInBits() / 8;
10299       int IncValue = IncOffset;
10300
10301       // Walk (both up and down) the chain looking for another load at the real
10302       // (aligned) offset (the alignment of the other load does not matter in
10303       // this case). If found, then do not use the offset reduction trick, as
10304       // that will prevent the loads from being later combined (as they would
10305       // otherwise be duplicates).
10306       if (!findConsecutiveLoad(LD, DAG))
10307         --IncValue;
10308
10309       SDValue Increment =
10310           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10311       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10312
10313       MachineMemOperand *ExtraMMO =
10314         MF.getMachineMemOperand(LD->getMemOperand(),
10315                                 1, 2*MemVT.getStoreSize()-1);
10316       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10317       SDValue ExtraLoad =
10318         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10319                                 DAG.getVTList(PermTy, MVT::Other),
10320                                 ExtraLoadOps, LDTy, ExtraMMO);
10321
10322       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10323         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10324
10325       // Because vperm has a big-endian bias, we must reverse the order
10326       // of the input vectors and complement the permute control vector
10327       // when generating little endian code.  We have already handled the
10328       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10329       // and ExtraLoad here.
10330       SDValue Perm;
10331       if (isLittleEndian)
10332         Perm = BuildIntrinsicOp(IntrPerm,
10333                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10334       else
10335         Perm = BuildIntrinsicOp(IntrPerm,
10336                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10337
10338       if (VT != PermTy)
10339         Perm = Subtarget.hasAltivec() ?
10340                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10341                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10342                                DAG.getTargetConstant(1, dl, MVT::i64));
10343                                // second argument is 1 because this rounding
10344                                // is always exact.
10345
10346       // The output of the permutation is our loaded result, the TokenFactor is
10347       // our new chain.
10348       DCI.CombineTo(N, Perm, TF);
10349       return SDValue(N, 0);
10350     }
10351     }
10352     break;
10353     case ISD::INTRINSIC_WO_CHAIN: {
10354       bool isLittleEndian = Subtarget.isLittleEndian();
10355       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10356       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10357                                            : Intrinsic::ppc_altivec_lvsl);
10358       if ((IID == Intr ||
10359            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10360            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10361         N->getOperand(1)->getOpcode() == ISD::ADD) {
10362         SDValue Add = N->getOperand(1);
10363
10364         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10365                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10366
10367         if (DAG.MaskedValueIsZero(
10368                 Add->getOperand(1),
10369                 APInt::getAllOnesValue(Bits /* alignment */)
10370                     .zext(
10371                         Add.getValueType().getScalarType().getSizeInBits()))) {
10372           SDNode *BasePtr = Add->getOperand(0).getNode();
10373           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10374                                     UE = BasePtr->use_end();
10375                UI != UE; ++UI) {
10376             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10377                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10378               // We've found another LVSL/LVSR, and this address is an aligned
10379               // multiple of that one. The results will be the same, so use the
10380               // one we've just found instead.
10381
10382               return SDValue(*UI, 0);
10383             }
10384           }
10385         }
10386
10387         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10388           SDNode *BasePtr = Add->getOperand(0).getNode();
10389           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10390                UE = BasePtr->use_end(); UI != UE; ++UI) {
10391             if (UI->getOpcode() == ISD::ADD &&
10392                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10393                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10394                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10395                 (1ULL << Bits) == 0) {
10396               SDNode *OtherAdd = *UI;
10397               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10398                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10399                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10400                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10401                   return SDValue(*VI, 0);
10402                 }
10403               }
10404             }
10405           }
10406         }
10407       }
10408     }
10409
10410     break;
10411   case ISD::INTRINSIC_W_CHAIN: {
10412     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10413     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10414       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10415       default:
10416         break;
10417       case Intrinsic::ppc_vsx_lxvw4x:
10418       case Intrinsic::ppc_vsx_lxvd2x:
10419         return expandVSXLoadForLE(N, DCI);
10420       }
10421     }
10422     break;
10423   }
10424   case ISD::INTRINSIC_VOID: {
10425     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10426     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10427       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10428       default:
10429         break;
10430       case Intrinsic::ppc_vsx_stxvw4x:
10431       case Intrinsic::ppc_vsx_stxvd2x:
10432         return expandVSXStoreForLE(N, DCI);
10433       }
10434     }
10435     break;
10436   }
10437   case ISD::BSWAP:
10438     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10439     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10440         N->getOperand(0).hasOneUse() &&
10441         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10442          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10443           N->getValueType(0) == MVT::i64))) {
10444       SDValue Load = N->getOperand(0);
10445       LoadSDNode *LD = cast<LoadSDNode>(Load);
10446       // Create the byte-swapping load.
10447       SDValue Ops[] = {
10448         LD->getChain(),    // Chain
10449         LD->getBasePtr(),  // Ptr
10450         DAG.getValueType(N->getValueType(0)) // VT
10451       };
10452       SDValue BSLoad =
10453         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10454                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10455                                               MVT::i64 : MVT::i32, MVT::Other),
10456                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10457
10458       // If this is an i16 load, insert the truncate.
10459       SDValue ResVal = BSLoad;
10460       if (N->getValueType(0) == MVT::i16)
10461         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10462
10463       // First, combine the bswap away.  This makes the value produced by the
10464       // load dead.
10465       DCI.CombineTo(N, ResVal);
10466
10467       // Next, combine the load away, we give it a bogus result value but a real
10468       // chain result.  The result value is dead because the bswap is dead.
10469       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10470
10471       // Return N so it doesn't get rechecked!
10472       return SDValue(N, 0);
10473     }
10474
10475     break;
10476   case PPCISD::VCMP: {
10477     // If a VCMPo node already exists with exactly the same operands as this
10478     // node, use its result instead of this node (VCMPo computes both a CR6 and
10479     // a normal output).
10480     //
10481     if (!N->getOperand(0).hasOneUse() &&
10482         !N->getOperand(1).hasOneUse() &&
10483         !N->getOperand(2).hasOneUse()) {
10484
10485       // Scan all of the users of the LHS, looking for VCMPo's that match.
10486       SDNode *VCMPoNode = nullptr;
10487
10488       SDNode *LHSN = N->getOperand(0).getNode();
10489       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10490            UI != E; ++UI)
10491         if (UI->getOpcode() == PPCISD::VCMPo &&
10492             UI->getOperand(1) == N->getOperand(1) &&
10493             UI->getOperand(2) == N->getOperand(2) &&
10494             UI->getOperand(0) == N->getOperand(0)) {
10495           VCMPoNode = *UI;
10496           break;
10497         }
10498
10499       // If there is no VCMPo node, or if the flag value has a single use, don't
10500       // transform this.
10501       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10502         break;
10503
10504       // Look at the (necessarily single) use of the flag value.  If it has a
10505       // chain, this transformation is more complex.  Note that multiple things
10506       // could use the value result, which we should ignore.
10507       SDNode *FlagUser = nullptr;
10508       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10509            FlagUser == nullptr; ++UI) {
10510         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10511         SDNode *User = *UI;
10512         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10513           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10514             FlagUser = User;
10515             break;
10516           }
10517         }
10518       }
10519
10520       // If the user is a MFOCRF instruction, we know this is safe.
10521       // Otherwise we give up for right now.
10522       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10523         return SDValue(VCMPoNode, 0);
10524     }
10525     break;
10526   }
10527   case ISD::BRCOND: {
10528     SDValue Cond = N->getOperand(1);
10529     SDValue Target = N->getOperand(2);
10530  
10531     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10532         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10533           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10534
10535       // We now need to make the intrinsic dead (it cannot be instruction
10536       // selected).
10537       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10538       assert(Cond.getNode()->hasOneUse() &&
10539              "Counter decrement has more than one use");
10540
10541       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10542                          N->getOperand(0), Target);
10543     }
10544   }
10545   break;
10546   case ISD::BR_CC: {
10547     // If this is a branch on an altivec predicate comparison, lower this so
10548     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10549     // lowering is done pre-legalize, because the legalizer lowers the predicate
10550     // compare down to code that is difficult to reassemble.
10551     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10552     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10553
10554     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10555     // value. If so, pass-through the AND to get to the intrinsic.
10556     if (LHS.getOpcode() == ISD::AND &&
10557         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10558         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10559           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10560         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10561         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10562           isZero())
10563       LHS = LHS.getOperand(0);
10564
10565     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10566         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10567           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10568         isa<ConstantSDNode>(RHS)) {
10569       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10570              "Counter decrement comparison is not EQ or NE");
10571
10572       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10573       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10574                     (CC == ISD::SETNE && !Val);
10575
10576       // We now need to make the intrinsic dead (it cannot be instruction
10577       // selected).
10578       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10579       assert(LHS.getNode()->hasOneUse() &&
10580              "Counter decrement has more than one use");
10581
10582       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10583                          N->getOperand(0), N->getOperand(4));
10584     }
10585
10586     int CompareOpc;
10587     bool isDot;
10588
10589     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10590         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10591         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10592       assert(isDot && "Can't compare against a vector result!");
10593
10594       // If this is a comparison against something other than 0/1, then we know
10595       // that the condition is never/always true.
10596       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10597       if (Val != 0 && Val != 1) {
10598         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10599           return N->getOperand(0);
10600         // Always !=, turn it into an unconditional branch.
10601         return DAG.getNode(ISD::BR, dl, MVT::Other,
10602                            N->getOperand(0), N->getOperand(4));
10603       }
10604
10605       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10606
10607       // Create the PPCISD altivec 'dot' comparison node.
10608       SDValue Ops[] = {
10609         LHS.getOperand(2),  // LHS of compare
10610         LHS.getOperand(3),  // RHS of compare
10611         DAG.getConstant(CompareOpc, dl, MVT::i32)
10612       };
10613       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10614       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10615
10616       // Unpack the result based on how the target uses it.
10617       PPC::Predicate CompOpc;
10618       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10619       default:  // Can't happen, don't crash on invalid number though.
10620       case 0:   // Branch on the value of the EQ bit of CR6.
10621         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10622         break;
10623       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10624         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10625         break;
10626       case 2:   // Branch on the value of the LT bit of CR6.
10627         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10628         break;
10629       case 3:   // Branch on the inverted value of the LT bit of CR6.
10630         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10631         break;
10632       }
10633
10634       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10635                          DAG.getConstant(CompOpc, dl, MVT::i32),
10636                          DAG.getRegister(PPC::CR6, MVT::i32),
10637                          N->getOperand(4), CompNode.getValue(1));
10638     }
10639     break;
10640   }
10641   }
10642
10643   return SDValue();
10644 }
10645
10646 SDValue
10647 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10648                                   SelectionDAG &DAG,
10649                                   std::vector<SDNode *> *Created) const {
10650   // fold (sdiv X, pow2)
10651   EVT VT = N->getValueType(0);
10652   if (VT == MVT::i64 && !Subtarget.isPPC64())
10653     return SDValue();
10654   if ((VT != MVT::i32 && VT != MVT::i64) ||
10655       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10656     return SDValue();
10657
10658   SDLoc DL(N);
10659   SDValue N0 = N->getOperand(0);
10660
10661   bool IsNegPow2 = (-Divisor).isPowerOf2();
10662   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10663   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10664
10665   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10666   if (Created)
10667     Created->push_back(Op.getNode());
10668
10669   if (IsNegPow2) {
10670     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10671     if (Created)
10672       Created->push_back(Op.getNode());
10673   }
10674
10675   return Op;
10676 }
10677
10678 //===----------------------------------------------------------------------===//
10679 // Inline Assembly Support
10680 //===----------------------------------------------------------------------===//
10681
10682 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10683                                                       APInt &KnownZero,
10684                                                       APInt &KnownOne,
10685                                                       const SelectionDAG &DAG,
10686                                                       unsigned Depth) const {
10687   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10688   switch (Op.getOpcode()) {
10689   default: break;
10690   case PPCISD::LBRX: {
10691     // lhbrx is known to have the top bits cleared out.
10692     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10693       KnownZero = 0xFFFF0000;
10694     break;
10695   }
10696   case ISD::INTRINSIC_WO_CHAIN: {
10697     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10698     default: break;
10699     case Intrinsic::ppc_altivec_vcmpbfp_p:
10700     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10701     case Intrinsic::ppc_altivec_vcmpequb_p:
10702     case Intrinsic::ppc_altivec_vcmpequh_p:
10703     case Intrinsic::ppc_altivec_vcmpequw_p:
10704     case Intrinsic::ppc_altivec_vcmpequd_p:
10705     case Intrinsic::ppc_altivec_vcmpgefp_p:
10706     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10707     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10708     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10709     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10710     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10711     case Intrinsic::ppc_altivec_vcmpgtub_p:
10712     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10713     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10714     case Intrinsic::ppc_altivec_vcmpgtud_p:
10715       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10716       break;
10717     }
10718   }
10719   }
10720 }
10721
10722 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10723   switch (Subtarget.getDarwinDirective()) {
10724   default: break;
10725   case PPC::DIR_970:
10726   case PPC::DIR_PWR4:
10727   case PPC::DIR_PWR5:
10728   case PPC::DIR_PWR5X:
10729   case PPC::DIR_PWR6:
10730   case PPC::DIR_PWR6X:
10731   case PPC::DIR_PWR7:
10732   case PPC::DIR_PWR8: {
10733     if (!ML)
10734       break;
10735
10736     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10737
10738     // For small loops (between 5 and 8 instructions), align to a 32-byte
10739     // boundary so that the entire loop fits in one instruction-cache line.
10740     uint64_t LoopSize = 0;
10741     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10742       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10743         LoopSize += TII->GetInstSizeInBytes(J);
10744
10745     if (LoopSize > 16 && LoopSize <= 32)
10746       return 5;
10747
10748     break;
10749   }
10750   }
10751
10752   return TargetLowering::getPrefLoopAlignment(ML);
10753 }
10754
10755 /// getConstraintType - Given a constraint, return the type of
10756 /// constraint it is for this target.
10757 PPCTargetLowering::ConstraintType
10758 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
10759   if (Constraint.size() == 1) {
10760     switch (Constraint[0]) {
10761     default: break;
10762     case 'b':
10763     case 'r':
10764     case 'f':
10765     case 'v':
10766     case 'y':
10767       return C_RegisterClass;
10768     case 'Z':
10769       // FIXME: While Z does indicate a memory constraint, it specifically
10770       // indicates an r+r address (used in conjunction with the 'y' modifier
10771       // in the replacement string). Currently, we're forcing the base
10772       // register to be r0 in the asm printer (which is interpreted as zero)
10773       // and forming the complete address in the second register. This is
10774       // suboptimal.
10775       return C_Memory;
10776     }
10777   } else if (Constraint == "wc") { // individual CR bits.
10778     return C_RegisterClass;
10779   } else if (Constraint == "wa" || Constraint == "wd" ||
10780              Constraint == "wf" || Constraint == "ws") {
10781     return C_RegisterClass; // VSX registers.
10782   }
10783   return TargetLowering::getConstraintType(Constraint);
10784 }
10785
10786 /// Examine constraint type and operand type and determine a weight value.
10787 /// This object must already have been set up with the operand type
10788 /// and the current alternative constraint selected.
10789 TargetLowering::ConstraintWeight
10790 PPCTargetLowering::getSingleConstraintMatchWeight(
10791     AsmOperandInfo &info, const char *constraint) const {
10792   ConstraintWeight weight = CW_Invalid;
10793   Value *CallOperandVal = info.CallOperandVal;
10794     // If we don't have a value, we can't do a match,
10795     // but allow it at the lowest weight.
10796   if (!CallOperandVal)
10797     return CW_Default;
10798   Type *type = CallOperandVal->getType();
10799
10800   // Look at the constraint type.
10801   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10802     return CW_Register; // an individual CR bit.
10803   else if ((StringRef(constraint) == "wa" ||
10804             StringRef(constraint) == "wd" ||
10805             StringRef(constraint) == "wf") &&
10806            type->isVectorTy())
10807     return CW_Register;
10808   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10809     return CW_Register;
10810
10811   switch (*constraint) {
10812   default:
10813     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10814     break;
10815   case 'b':
10816     if (type->isIntegerTy())
10817       weight = CW_Register;
10818     break;
10819   case 'f':
10820     if (type->isFloatTy())
10821       weight = CW_Register;
10822     break;
10823   case 'd':
10824     if (type->isDoubleTy())
10825       weight = CW_Register;
10826     break;
10827   case 'v':
10828     if (type->isVectorTy())
10829       weight = CW_Register;
10830     break;
10831   case 'y':
10832     weight = CW_Register;
10833     break;
10834   case 'Z':
10835     weight = CW_Memory;
10836     break;
10837   }
10838   return weight;
10839 }
10840
10841 std::pair<unsigned, const TargetRegisterClass *>
10842 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10843                                                 StringRef Constraint,
10844                                                 MVT VT) const {
10845   if (Constraint.size() == 1) {
10846     // GCC RS6000 Constraint Letters
10847     switch (Constraint[0]) {
10848     case 'b':   // R1-R31
10849       if (VT == MVT::i64 && Subtarget.isPPC64())
10850         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10851       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10852     case 'r':   // R0-R31
10853       if (VT == MVT::i64 && Subtarget.isPPC64())
10854         return std::make_pair(0U, &PPC::G8RCRegClass);
10855       return std::make_pair(0U, &PPC::GPRCRegClass);
10856     case 'f':
10857       if (VT == MVT::f32 || VT == MVT::i32)
10858         return std::make_pair(0U, &PPC::F4RCRegClass);
10859       if (VT == MVT::f64 || VT == MVT::i64)
10860         return std::make_pair(0U, &PPC::F8RCRegClass);
10861       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10862         return std::make_pair(0U, &PPC::QFRCRegClass);
10863       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10864         return std::make_pair(0U, &PPC::QSRCRegClass);
10865       break;
10866     case 'v':
10867       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10868         return std::make_pair(0U, &PPC::QFRCRegClass);
10869       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10870         return std::make_pair(0U, &PPC::QSRCRegClass);
10871       return std::make_pair(0U, &PPC::VRRCRegClass);
10872     case 'y':   // crrc
10873       return std::make_pair(0U, &PPC::CRRCRegClass);
10874     }
10875   } else if (Constraint == "wc") { // an individual CR bit.
10876     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10877   } else if (Constraint == "wa" || Constraint == "wd" ||
10878              Constraint == "wf") {
10879     return std::make_pair(0U, &PPC::VSRCRegClass);
10880   } else if (Constraint == "ws") {
10881     if (VT == MVT::f32)
10882       return std::make_pair(0U, &PPC::VSSRCRegClass);
10883     else
10884       return std::make_pair(0U, &PPC::VSFRCRegClass);
10885   }
10886
10887   std::pair<unsigned, const TargetRegisterClass *> R =
10888       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10889
10890   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10891   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10892   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10893   // register.
10894   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10895   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10896   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10897       PPC::GPRCRegClass.contains(R.first))
10898     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10899                             PPC::sub_32, &PPC::G8RCRegClass),
10900                           &PPC::G8RCRegClass);
10901
10902   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10903   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10904     R.first = PPC::CR0;
10905     R.second = &PPC::CRRCRegClass;
10906   }
10907
10908   return R;
10909 }
10910
10911
10912 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10913 /// vector.  If it is invalid, don't add anything to Ops.
10914 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10915                                                      std::string &Constraint,
10916                                                      std::vector<SDValue>&Ops,
10917                                                      SelectionDAG &DAG) const {
10918   SDValue Result;
10919
10920   // Only support length 1 constraints.
10921   if (Constraint.length() > 1) return;
10922
10923   char Letter = Constraint[0];
10924   switch (Letter) {
10925   default: break;
10926   case 'I':
10927   case 'J':
10928   case 'K':
10929   case 'L':
10930   case 'M':
10931   case 'N':
10932   case 'O':
10933   case 'P': {
10934     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10935     if (!CST) return; // Must be an immediate to match.
10936     SDLoc dl(Op);
10937     int64_t Value = CST->getSExtValue();
10938     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10939                          // numbers are printed as such.
10940     switch (Letter) {
10941     default: llvm_unreachable("Unknown constraint letter!");
10942     case 'I':  // "I" is a signed 16-bit constant.
10943       if (isInt<16>(Value))
10944         Result = DAG.getTargetConstant(Value, dl, TCVT);
10945       break;
10946     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10947       if (isShiftedUInt<16, 16>(Value))
10948         Result = DAG.getTargetConstant(Value, dl, TCVT);
10949       break;
10950     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10951       if (isShiftedInt<16, 16>(Value))
10952         Result = DAG.getTargetConstant(Value, dl, TCVT);
10953       break;
10954     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10955       if (isUInt<16>(Value))
10956         Result = DAG.getTargetConstant(Value, dl, TCVT);
10957       break;
10958     case 'M':  // "M" is a constant that is greater than 31.
10959       if (Value > 31)
10960         Result = DAG.getTargetConstant(Value, dl, TCVT);
10961       break;
10962     case 'N':  // "N" is a positive constant that is an exact power of two.
10963       if (Value > 0 && isPowerOf2_64(Value))
10964         Result = DAG.getTargetConstant(Value, dl, TCVT);
10965       break;
10966     case 'O':  // "O" is the constant zero.
10967       if (Value == 0)
10968         Result = DAG.getTargetConstant(Value, dl, TCVT);
10969       break;
10970     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10971       if (isInt<16>(-Value))
10972         Result = DAG.getTargetConstant(Value, dl, TCVT);
10973       break;
10974     }
10975     break;
10976   }
10977   }
10978
10979   if (Result.getNode()) {
10980     Ops.push_back(Result);
10981     return;
10982   }
10983
10984   // Handle standard constraint letters.
10985   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10986 }
10987
10988 // isLegalAddressingMode - Return true if the addressing mode represented
10989 // by AM is legal for this target, for a load/store of the specified type.
10990 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10991                                               const AddrMode &AM, Type *Ty,
10992                                               unsigned AS) const {
10993   // PPC does not allow r+i addressing modes for vectors!
10994   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10995     return false;
10996
10997   // PPC allows a sign-extended 16-bit immediate field.
10998   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10999     return false;
11000
11001   // No global is ever allowed as a base.
11002   if (AM.BaseGV)
11003     return false;
11004
11005   // PPC only support r+r,
11006   switch (AM.Scale) {
11007   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11008     break;
11009   case 1:
11010     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11011       return false;
11012     // Otherwise we have r+r or r+i.
11013     break;
11014   case 2:
11015     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11016       return false;
11017     // Allow 2*r as r+r.
11018     break;
11019   default:
11020     // No other scales are supported.
11021     return false;
11022   }
11023
11024   return true;
11025 }
11026
11027 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11028                                            SelectionDAG &DAG) const {
11029   MachineFunction &MF = DAG.getMachineFunction();
11030   MachineFrameInfo *MFI = MF.getFrameInfo();
11031   MFI->setReturnAddressIsTaken(true);
11032
11033   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11034     return SDValue();
11035
11036   SDLoc dl(Op);
11037   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11038
11039   // Make sure the function does not optimize away the store of the RA to
11040   // the stack.
11041   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11042   FuncInfo->setLRStoreRequired();
11043   bool isPPC64 = Subtarget.isPPC64();
11044   auto PtrVT = getPointerTy(MF.getDataLayout());
11045
11046   if (Depth > 0) {
11047     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11048     SDValue Offset =
11049         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11050                         isPPC64 ? MVT::i64 : MVT::i32);
11051     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11052                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11053                        MachinePointerInfo(), false, false, false, 0);
11054   }
11055
11056   // Just load the return address off the stack.
11057   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11058   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11059                      MachinePointerInfo(), false, false, false, 0);
11060 }
11061
11062 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11063                                           SelectionDAG &DAG) const {
11064   SDLoc dl(Op);
11065   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11066
11067   MachineFunction &MF = DAG.getMachineFunction();
11068   MachineFrameInfo *MFI = MF.getFrameInfo();
11069   MFI->setFrameAddressIsTaken(true);
11070
11071   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
11072   bool isPPC64 = PtrVT == MVT::i64;
11073
11074   // Naked functions never have a frame pointer, and so we use r1. For all
11075   // other functions, this decision must be delayed until during PEI.
11076   unsigned FrameReg;
11077   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11078     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11079   else
11080     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11081
11082   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11083                                          PtrVT);
11084   while (Depth--)
11085     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11086                             FrameAddr, MachinePointerInfo(), false, false,
11087                             false, 0);
11088   return FrameAddr;
11089 }
11090
11091 // FIXME? Maybe this could be a TableGen attribute on some registers and
11092 // this table could be generated automatically from RegInfo.
11093 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11094                                               SelectionDAG &DAG) const {
11095   bool isPPC64 = Subtarget.isPPC64();
11096   bool isDarwinABI = Subtarget.isDarwinABI();
11097
11098   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11099       (!isPPC64 && VT != MVT::i32))
11100     report_fatal_error("Invalid register global variable type");
11101
11102   bool is64Bit = isPPC64 && VT == MVT::i64;
11103   unsigned Reg = StringSwitch<unsigned>(RegName)
11104                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11105                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11106                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11107                                   (is64Bit ? PPC::X13 : PPC::R13))
11108                    .Default(0);
11109
11110   if (Reg)
11111     return Reg;
11112   report_fatal_error("Invalid register name global variable");
11113 }
11114
11115 bool
11116 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11117   // The PowerPC target isn't yet aware of offsets.
11118   return false;
11119 }
11120
11121 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11122                                            const CallInst &I,
11123                                            unsigned Intrinsic) const {
11124
11125   switch (Intrinsic) {
11126   case Intrinsic::ppc_qpx_qvlfd:
11127   case Intrinsic::ppc_qpx_qvlfs:
11128   case Intrinsic::ppc_qpx_qvlfcd:
11129   case Intrinsic::ppc_qpx_qvlfcs:
11130   case Intrinsic::ppc_qpx_qvlfiwa:
11131   case Intrinsic::ppc_qpx_qvlfiwz:
11132   case Intrinsic::ppc_altivec_lvx:
11133   case Intrinsic::ppc_altivec_lvxl:
11134   case Intrinsic::ppc_altivec_lvebx:
11135   case Intrinsic::ppc_altivec_lvehx:
11136   case Intrinsic::ppc_altivec_lvewx:
11137   case Intrinsic::ppc_vsx_lxvd2x:
11138   case Intrinsic::ppc_vsx_lxvw4x: {
11139     EVT VT;
11140     switch (Intrinsic) {
11141     case Intrinsic::ppc_altivec_lvebx:
11142       VT = MVT::i8;
11143       break;
11144     case Intrinsic::ppc_altivec_lvehx:
11145       VT = MVT::i16;
11146       break;
11147     case Intrinsic::ppc_altivec_lvewx:
11148       VT = MVT::i32;
11149       break;
11150     case Intrinsic::ppc_vsx_lxvd2x:
11151       VT = MVT::v2f64;
11152       break;
11153     case Intrinsic::ppc_qpx_qvlfd:
11154       VT = MVT::v4f64;
11155       break;
11156     case Intrinsic::ppc_qpx_qvlfs:
11157       VT = MVT::v4f32;
11158       break;
11159     case Intrinsic::ppc_qpx_qvlfcd:
11160       VT = MVT::v2f64;
11161       break;
11162     case Intrinsic::ppc_qpx_qvlfcs:
11163       VT = MVT::v2f32;
11164       break;
11165     default:
11166       VT = MVT::v4i32;
11167       break;
11168     }
11169
11170     Info.opc = ISD::INTRINSIC_W_CHAIN;
11171     Info.memVT = VT;
11172     Info.ptrVal = I.getArgOperand(0);
11173     Info.offset = -VT.getStoreSize()+1;
11174     Info.size = 2*VT.getStoreSize()-1;
11175     Info.align = 1;
11176     Info.vol = false;
11177     Info.readMem = true;
11178     Info.writeMem = false;
11179     return true;
11180   }
11181   case Intrinsic::ppc_qpx_qvlfda:
11182   case Intrinsic::ppc_qpx_qvlfsa:
11183   case Intrinsic::ppc_qpx_qvlfcda:
11184   case Intrinsic::ppc_qpx_qvlfcsa:
11185   case Intrinsic::ppc_qpx_qvlfiwaa:
11186   case Intrinsic::ppc_qpx_qvlfiwza: {
11187     EVT VT;
11188     switch (Intrinsic) {
11189     case Intrinsic::ppc_qpx_qvlfda:
11190       VT = MVT::v4f64;
11191       break;
11192     case Intrinsic::ppc_qpx_qvlfsa:
11193       VT = MVT::v4f32;
11194       break;
11195     case Intrinsic::ppc_qpx_qvlfcda:
11196       VT = MVT::v2f64;
11197       break;
11198     case Intrinsic::ppc_qpx_qvlfcsa:
11199       VT = MVT::v2f32;
11200       break;
11201     default:
11202       VT = MVT::v4i32;
11203       break;
11204     }
11205
11206     Info.opc = ISD::INTRINSIC_W_CHAIN;
11207     Info.memVT = VT;
11208     Info.ptrVal = I.getArgOperand(0);
11209     Info.offset = 0;
11210     Info.size = VT.getStoreSize();
11211     Info.align = 1;
11212     Info.vol = false;
11213     Info.readMem = true;
11214     Info.writeMem = false;
11215     return true;
11216   }
11217   case Intrinsic::ppc_qpx_qvstfd:
11218   case Intrinsic::ppc_qpx_qvstfs:
11219   case Intrinsic::ppc_qpx_qvstfcd:
11220   case Intrinsic::ppc_qpx_qvstfcs:
11221   case Intrinsic::ppc_qpx_qvstfiw:
11222   case Intrinsic::ppc_altivec_stvx:
11223   case Intrinsic::ppc_altivec_stvxl:
11224   case Intrinsic::ppc_altivec_stvebx:
11225   case Intrinsic::ppc_altivec_stvehx:
11226   case Intrinsic::ppc_altivec_stvewx:
11227   case Intrinsic::ppc_vsx_stxvd2x:
11228   case Intrinsic::ppc_vsx_stxvw4x: {
11229     EVT VT;
11230     switch (Intrinsic) {
11231     case Intrinsic::ppc_altivec_stvebx:
11232       VT = MVT::i8;
11233       break;
11234     case Intrinsic::ppc_altivec_stvehx:
11235       VT = MVT::i16;
11236       break;
11237     case Intrinsic::ppc_altivec_stvewx:
11238       VT = MVT::i32;
11239       break;
11240     case Intrinsic::ppc_vsx_stxvd2x:
11241       VT = MVT::v2f64;
11242       break;
11243     case Intrinsic::ppc_qpx_qvstfd:
11244       VT = MVT::v4f64;
11245       break;
11246     case Intrinsic::ppc_qpx_qvstfs:
11247       VT = MVT::v4f32;
11248       break;
11249     case Intrinsic::ppc_qpx_qvstfcd:
11250       VT = MVT::v2f64;
11251       break;
11252     case Intrinsic::ppc_qpx_qvstfcs:
11253       VT = MVT::v2f32;
11254       break;
11255     default:
11256       VT = MVT::v4i32;
11257       break;
11258     }
11259
11260     Info.opc = ISD::INTRINSIC_VOID;
11261     Info.memVT = VT;
11262     Info.ptrVal = I.getArgOperand(1);
11263     Info.offset = -VT.getStoreSize()+1;
11264     Info.size = 2*VT.getStoreSize()-1;
11265     Info.align = 1;
11266     Info.vol = false;
11267     Info.readMem = false;
11268     Info.writeMem = true;
11269     return true;
11270   }
11271   case Intrinsic::ppc_qpx_qvstfda:
11272   case Intrinsic::ppc_qpx_qvstfsa:
11273   case Intrinsic::ppc_qpx_qvstfcda:
11274   case Intrinsic::ppc_qpx_qvstfcsa:
11275   case Intrinsic::ppc_qpx_qvstfiwa: {
11276     EVT VT;
11277     switch (Intrinsic) {
11278     case Intrinsic::ppc_qpx_qvstfda:
11279       VT = MVT::v4f64;
11280       break;
11281     case Intrinsic::ppc_qpx_qvstfsa:
11282       VT = MVT::v4f32;
11283       break;
11284     case Intrinsic::ppc_qpx_qvstfcda:
11285       VT = MVT::v2f64;
11286       break;
11287     case Intrinsic::ppc_qpx_qvstfcsa:
11288       VT = MVT::v2f32;
11289       break;
11290     default:
11291       VT = MVT::v4i32;
11292       break;
11293     }
11294
11295     Info.opc = ISD::INTRINSIC_VOID;
11296     Info.memVT = VT;
11297     Info.ptrVal = I.getArgOperand(1);
11298     Info.offset = 0;
11299     Info.size = VT.getStoreSize();
11300     Info.align = 1;
11301     Info.vol = false;
11302     Info.readMem = false;
11303     Info.writeMem = true;
11304     return true;
11305   }
11306   default:
11307     break;
11308   }
11309
11310   return false;
11311 }
11312
11313 /// getOptimalMemOpType - Returns the target specific optimal type for load
11314 /// and store operations as a result of memset, memcpy, and memmove
11315 /// lowering. If DstAlign is zero that means it's safe to destination
11316 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11317 /// means there isn't a need to check it against alignment requirement,
11318 /// probably because the source does not need to be loaded. If 'IsMemset' is
11319 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11320 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11321 /// source is constant so it does not need to be loaded.
11322 /// It returns EVT::Other if the type should be determined using generic
11323 /// target-independent logic.
11324 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11325                                            unsigned DstAlign, unsigned SrcAlign,
11326                                            bool IsMemset, bool ZeroMemset,
11327                                            bool MemcpyStrSrc,
11328                                            MachineFunction &MF) const {
11329   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11330     const Function *F = MF.getFunction();
11331     // When expanding a memset, require at least two QPX instructions to cover
11332     // the cost of loading the value to be stored from the constant pool.
11333     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11334        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11335         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11336       return MVT::v4f64;
11337     }
11338
11339     // We should use Altivec/VSX loads and stores when available. For unaligned
11340     // addresses, unaligned VSX loads are only fast starting with the P8.
11341     if (Subtarget.hasAltivec() && Size >= 16 &&
11342         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11343          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11344       return MVT::v4i32;
11345   }
11346
11347   if (Subtarget.isPPC64()) {
11348     return MVT::i64;
11349   }
11350
11351   return MVT::i32;
11352 }
11353
11354 /// \brief Returns true if it is beneficial to convert a load of a constant
11355 /// to just the constant itself.
11356 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11357                                                           Type *Ty) const {
11358   assert(Ty->isIntegerTy());
11359
11360   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11361   if (BitSize == 0 || BitSize > 64)
11362     return false;
11363   return true;
11364 }
11365
11366 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11367   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11368     return false;
11369   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11370   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11371   return NumBits1 == 64 && NumBits2 == 32;
11372 }
11373
11374 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11375   if (!VT1.isInteger() || !VT2.isInteger())
11376     return false;
11377   unsigned NumBits1 = VT1.getSizeInBits();
11378   unsigned NumBits2 = VT2.getSizeInBits();
11379   return NumBits1 == 64 && NumBits2 == 32;
11380 }
11381
11382 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11383   // Generally speaking, zexts are not free, but they are free when they can be
11384   // folded with other operations.
11385   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11386     EVT MemVT = LD->getMemoryVT();
11387     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11388          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11389         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11390          LD->getExtensionType() == ISD::ZEXTLOAD))
11391       return true;
11392   }
11393
11394   // FIXME: Add other cases...
11395   //  - 32-bit shifts with a zext to i64
11396   //  - zext after ctlz, bswap, etc.
11397   //  - zext after and by a constant mask
11398
11399   return TargetLowering::isZExtFree(Val, VT2);
11400 }
11401
11402 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11403   assert(VT.isFloatingPoint());
11404   return true;
11405 }
11406
11407 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11408   return isInt<16>(Imm) || isUInt<16>(Imm);
11409 }
11410
11411 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11412   return isInt<16>(Imm) || isUInt<16>(Imm);
11413 }
11414
11415 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11416                                                        unsigned,
11417                                                        unsigned,
11418                                                        bool *Fast) const {
11419   if (DisablePPCUnaligned)
11420     return false;
11421
11422   // PowerPC supports unaligned memory access for simple non-vector types.
11423   // Although accessing unaligned addresses is not as efficient as accessing
11424   // aligned addresses, it is generally more efficient than manual expansion,
11425   // and generally only traps for software emulation when crossing page
11426   // boundaries.
11427
11428   if (!VT.isSimple())
11429     return false;
11430
11431   if (VT.getSimpleVT().isVector()) {
11432     if (Subtarget.hasVSX()) {
11433       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11434           VT != MVT::v4f32 && VT != MVT::v4i32)
11435         return false;
11436     } else {
11437       return false;
11438     }
11439   }
11440
11441   if (VT == MVT::ppcf128)
11442     return false;
11443
11444   if (Fast)
11445     *Fast = true;
11446
11447   return true;
11448 }
11449
11450 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11451   VT = VT.getScalarType();
11452
11453   if (!VT.isSimple())
11454     return false;
11455
11456   switch (VT.getSimpleVT().SimpleTy) {
11457   case MVT::f32:
11458   case MVT::f64:
11459     return true;
11460   default:
11461     break;
11462   }
11463
11464   return false;
11465 }
11466
11467 const MCPhysReg *
11468 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11469   // LR is a callee-save register, but we must treat it as clobbered by any call
11470   // site. Hence we include LR in the scratch registers, which are in turn added
11471   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11472   // to CTR, which is used by any indirect call.
11473   static const MCPhysReg ScratchRegs[] = {
11474     PPC::X12, PPC::LR8, PPC::CTR8, 0
11475   };
11476
11477   return ScratchRegs;
11478 }
11479
11480 bool
11481 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11482                      EVT VT , unsigned DefinedValues) const {
11483   if (VT == MVT::v2i64)
11484     return false;
11485
11486   if (Subtarget.hasQPX()) {
11487     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11488       return true;
11489   }
11490
11491   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11492 }
11493
11494 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11495   if (DisableILPPref || Subtarget.enableMachineScheduler())
11496     return TargetLowering::getSchedulingPreference(N);
11497
11498   return Sched::ILP;
11499 }
11500
11501 // Create a fast isel object.
11502 FastISel *
11503 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11504                                   const TargetLibraryInfo *LibInfo) const {
11505   return PPC::createFastISel(FuncInfo, LibInfo);
11506 }