]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
MFV r309299:
[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 "PPCCCState.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCPerfectShuffle.h"
20 #include "PPCTargetMachine.h"
21 #include "PPCTargetObjectFile.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAG.h"
33 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include <list>
46
47 using namespace llvm;
48
49 #define DEBUG_TYPE "ppc-lowering"
50
51 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
52 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
53
54 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
55 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
56
57 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
58 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
59
60 static cl::opt<bool> DisableSCO("disable-ppc-sco",
61 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
62
63 STATISTIC(NumTailCalls, "Number of tail calls");
64 STATISTIC(NumSiblingCalls, "Number of sibling calls");
65
66 // FIXME: Remove this once the bug has been fixed!
67 extern cl::opt<bool> ANDIGlueBug;
68
69 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
70                                      const PPCSubtarget &STI)
71     : TargetLowering(TM), Subtarget(STI) {
72   // Use _setjmp/_longjmp instead of setjmp/longjmp.
73   setUseUnderscoreSetJmp(true);
74   setUseUnderscoreLongJmp(true);
75
76   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
77   // arguments are at least 4/8 bytes aligned.
78   bool isPPC64 = Subtarget.isPPC64();
79   setMinStackArgumentAlignment(isPPC64 ? 8:4);
80
81   // Set up the register classes.
82   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
83   if (!useSoftFloat()) {
84     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
85     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
86   }
87
88   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
89   for (MVT VT : MVT::integer_valuetypes()) {
90     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
91     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
92   }
93
94   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
95
96   // PowerPC has pre-inc load and store's.
97   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
98   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
99   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
100   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
101   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
102   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
103   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
104   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
105   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
106   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
107   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
108   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
109   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
110   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
111
112   if (Subtarget.useCRBits()) {
113     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
114
115     if (isPPC64 || Subtarget.hasFPCVT()) {
116       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
117       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
118                          isPPC64 ? MVT::i64 : MVT::i32);
119       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
120       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
121                         isPPC64 ? MVT::i64 : MVT::i32);
122     } else {
123       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
124       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
125     }
126
127     // PowerPC does not support direct load / store of condition registers
128     setOperationAction(ISD::LOAD, MVT::i1, Custom);
129     setOperationAction(ISD::STORE, MVT::i1, Custom);
130
131     // FIXME: Remove this once the ANDI glue bug is fixed:
132     if (ANDIGlueBug)
133       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
134
135     for (MVT VT : MVT::integer_valuetypes()) {
136       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
137       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
138       setTruncStoreAction(VT, MVT::i1, Expand);
139     }
140
141     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
142   }
143
144   // This is used in the ppcf128->int sequence.  Note it has different semantics
145   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
146   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
147
148   // We do not currently implement these libm ops for PowerPC.
149   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
150   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
151   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
152   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
153   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
154   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
155
156   // PowerPC has no SREM/UREM instructions
157   setOperationAction(ISD::SREM, MVT::i32, Expand);
158   setOperationAction(ISD::UREM, MVT::i32, Expand);
159   setOperationAction(ISD::SREM, MVT::i64, Expand);
160   setOperationAction(ISD::UREM, MVT::i64, Expand);
161
162   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
163   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
164   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
165   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
166   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
167   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
168   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
169   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
170   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
171
172   // We don't support sin/cos/sqrt/fmod/pow
173   setOperationAction(ISD::FSIN , MVT::f64, Expand);
174   setOperationAction(ISD::FCOS , MVT::f64, Expand);
175   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
176   setOperationAction(ISD::FREM , MVT::f64, Expand);
177   setOperationAction(ISD::FPOW , MVT::f64, Expand);
178   setOperationAction(ISD::FMA  , MVT::f64, Legal);
179   setOperationAction(ISD::FSIN , MVT::f32, Expand);
180   setOperationAction(ISD::FCOS , MVT::f32, Expand);
181   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
182   setOperationAction(ISD::FREM , MVT::f32, Expand);
183   setOperationAction(ISD::FPOW , MVT::f32, Expand);
184   setOperationAction(ISD::FMA  , MVT::f32, Legal);
185
186   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
187
188   // If we're enabling GP optimizations, use hardware square root
189   if (!Subtarget.hasFSQRT() &&
190       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
191         Subtarget.hasFRE()))
192     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
193
194   if (!Subtarget.hasFSQRT() &&
195       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
196         Subtarget.hasFRES()))
197     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
198
199   if (Subtarget.hasFCPSGN()) {
200     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
201     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
202   } else {
203     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
204     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
205   }
206
207   if (Subtarget.hasFPRND()) {
208     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
209     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
210     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
211     setOperationAction(ISD::FROUND, MVT::f64, Legal);
212
213     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
214     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
215     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
216     setOperationAction(ISD::FROUND, MVT::f32, Legal);
217   }
218
219   // PowerPC does not have BSWAP, CTPOP or CTTZ
220   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
221   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
222   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
223   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
224
225   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
226     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
227     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
228   } else {
229     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
230     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
231   }
232
233   // PowerPC does not have ROTR
234   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
235   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
236
237   if (!Subtarget.useCRBits()) {
238     // PowerPC does not have Select
239     setOperationAction(ISD::SELECT, MVT::i32, Expand);
240     setOperationAction(ISD::SELECT, MVT::i64, Expand);
241     setOperationAction(ISD::SELECT, MVT::f32, Expand);
242     setOperationAction(ISD::SELECT, MVT::f64, Expand);
243   }
244
245   // PowerPC wants to turn select_cc of FP into fsel when possible.
246   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
247   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
248
249   // PowerPC wants to optimize integer setcc a bit
250   if (!Subtarget.useCRBits())
251     setOperationAction(ISD::SETCC, MVT::i32, Custom);
252
253   // PowerPC does not have BRCOND which requires SetCC
254   if (!Subtarget.useCRBits())
255     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
256
257   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
258
259   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
260   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261
262   // PowerPC does not have [U|S]INT_TO_FP
263   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
264   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
265
266   if (Subtarget.hasDirectMove() && isPPC64) {
267     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
268     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
269     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
270     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
271   } else {
272     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
273     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
274     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
275     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
276   }
277
278   // We cannot sextinreg(i1).  Expand to shifts.
279   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
280
281   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
282   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
283   // support continuation, user-level threading, and etc.. As a result, no
284   // other SjLj exception interfaces are implemented and please don't build
285   // your own exception handling based on them.
286   // LLVM/Clang supports zero-cost DWARF exception handling.
287   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
288   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
289
290   // We want to legalize GlobalAddress and ConstantPool nodes into the
291   // appropriate instructions to materialize the address.
292   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
293   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
294   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
295   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
296   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
297   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
298   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
299   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
300   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
301   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
302
303   // TRAP is legal.
304   setOperationAction(ISD::TRAP, MVT::Other, Legal);
305
306   // TRAMPOLINE is custom lowered.
307   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
308   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
309
310   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
311   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
312
313   if (Subtarget.isSVR4ABI()) {
314     if (isPPC64) {
315       // VAARG always uses double-word chunks, so promote anything smaller.
316       setOperationAction(ISD::VAARG, MVT::i1, Promote);
317       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
318       setOperationAction(ISD::VAARG, MVT::i8, Promote);
319       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
320       setOperationAction(ISD::VAARG, MVT::i16, Promote);
321       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
322       setOperationAction(ISD::VAARG, MVT::i32, Promote);
323       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
324       setOperationAction(ISD::VAARG, MVT::Other, Expand);
325     } else {
326       // VAARG is custom lowered with the 32-bit SVR4 ABI.
327       setOperationAction(ISD::VAARG, MVT::Other, Custom);
328       setOperationAction(ISD::VAARG, MVT::i64, Custom);
329     }
330   } else
331     setOperationAction(ISD::VAARG, MVT::Other, Expand);
332
333   if (Subtarget.isSVR4ABI() && !isPPC64)
334     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
335     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
336   else
337     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
338
339   // Use the default implementation.
340   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
341   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
342   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
343   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
344   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
345   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
346   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
347   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
348   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
349
350   // We want to custom lower some of our intrinsics.
351   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
352
353   // To handle counter-based loop conditions.
354   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
355
356   // Comparisons that require checking two conditions.
357   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
358   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
359   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
360   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
361   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
362   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
363   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
364   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
365   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
366   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
367   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
368   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
369
370   if (Subtarget.has64BitSupport()) {
371     // They also have instructions for converting between i64 and fp.
372     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
374     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
376     // This is just the low 32 bits of a (signed) fp->i64 conversion.
377     // We cannot do this with Promote because i64 is not a legal type.
378     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
379
380     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
381       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382   } else {
383     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
384     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
385   }
386
387   // With the instructions enabled under FPCVT, we can do everything.
388   if (Subtarget.hasFPCVT()) {
389     if (Subtarget.has64BitSupport()) {
390       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
391       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
392       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
393       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
394     }
395
396     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
397     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
398     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
399     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
400   }
401
402   if (Subtarget.use64BitRegs()) {
403     // 64-bit PowerPC implementations can support i64 types directly
404     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
405     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
406     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
407     // 64-bit PowerPC wants to expand i128 shifts itself.
408     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
409     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
410     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
411   } else {
412     // 32-bit PowerPC wants to expand i64 shifts itself.
413     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
414     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
415     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
416   }
417
418   if (Subtarget.hasAltivec()) {
419     // First set operation action for all vector types to expand. Then we
420     // will selectively turn on ones that can be effectively codegen'd.
421     for (MVT VT : MVT::vector_valuetypes()) {
422       // add/sub are legal for all supported vector VT's.
423       setOperationAction(ISD::ADD, VT, Legal);
424       setOperationAction(ISD::SUB, VT, Legal);
425
426       // Vector instructions introduced in P8
427       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
428         setOperationAction(ISD::CTPOP, VT, Legal);
429         setOperationAction(ISD::CTLZ, VT, Legal);
430       }
431       else {
432         setOperationAction(ISD::CTPOP, VT, Expand);
433         setOperationAction(ISD::CTLZ, VT, Expand);
434       }
435
436       // We promote all shuffles to v16i8.
437       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
438       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
439
440       // We promote all non-typed operations to v4i32.
441       setOperationAction(ISD::AND   , VT, Promote);
442       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
443       setOperationAction(ISD::OR    , VT, Promote);
444       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
445       setOperationAction(ISD::XOR   , VT, Promote);
446       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
447       setOperationAction(ISD::LOAD  , VT, Promote);
448       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
449       setOperationAction(ISD::SELECT, VT, Promote);
450       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
451       setOperationAction(ISD::SELECT_CC, VT, Promote);
452       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
453       setOperationAction(ISD::STORE, VT, Promote);
454       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
455
456       // No other operations are legal.
457       setOperationAction(ISD::MUL , VT, Expand);
458       setOperationAction(ISD::SDIV, VT, Expand);
459       setOperationAction(ISD::SREM, VT, Expand);
460       setOperationAction(ISD::UDIV, VT, Expand);
461       setOperationAction(ISD::UREM, VT, Expand);
462       setOperationAction(ISD::FDIV, VT, Expand);
463       setOperationAction(ISD::FREM, VT, Expand);
464       setOperationAction(ISD::FNEG, VT, Expand);
465       setOperationAction(ISD::FSQRT, VT, Expand);
466       setOperationAction(ISD::FLOG, VT, Expand);
467       setOperationAction(ISD::FLOG10, VT, Expand);
468       setOperationAction(ISD::FLOG2, VT, Expand);
469       setOperationAction(ISD::FEXP, VT, Expand);
470       setOperationAction(ISD::FEXP2, VT, Expand);
471       setOperationAction(ISD::FSIN, VT, Expand);
472       setOperationAction(ISD::FCOS, VT, Expand);
473       setOperationAction(ISD::FABS, VT, Expand);
474       setOperationAction(ISD::FPOWI, VT, Expand);
475       setOperationAction(ISD::FFLOOR, VT, Expand);
476       setOperationAction(ISD::FCEIL,  VT, Expand);
477       setOperationAction(ISD::FTRUNC, VT, Expand);
478       setOperationAction(ISD::FRINT,  VT, Expand);
479       setOperationAction(ISD::FNEARBYINT, VT, Expand);
480       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
481       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
482       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
483       setOperationAction(ISD::MULHU, VT, Expand);
484       setOperationAction(ISD::MULHS, VT, Expand);
485       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
486       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
487       setOperationAction(ISD::UDIVREM, VT, Expand);
488       setOperationAction(ISD::SDIVREM, VT, Expand);
489       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
490       setOperationAction(ISD::FPOW, VT, Expand);
491       setOperationAction(ISD::BSWAP, VT, Expand);
492       setOperationAction(ISD::CTTZ, VT, Expand);
493       setOperationAction(ISD::VSELECT, VT, Expand);
494       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
495       setOperationAction(ISD::ROTL, VT, Expand);
496       setOperationAction(ISD::ROTR, VT, Expand);
497
498       for (MVT InnerVT : MVT::vector_valuetypes()) {
499         setTruncStoreAction(VT, InnerVT, Expand);
500         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
501         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
502         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
503       }
504     }
505
506     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
507     // with merges, splats, etc.
508     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
509
510     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
511     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
512     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
513     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
514     setOperationAction(ISD::SELECT, MVT::v4i32,
515                        Subtarget.useCRBits() ? Legal : Expand);
516     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
517     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
518     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
519     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
520     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
521     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
524     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
525
526     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
527     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
528     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
529     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
530
531     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
532     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
533
534     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
535       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
536       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
537     }
538
539     if (Subtarget.hasP8Altivec())
540       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
541     else
542       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
543
544     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
545     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
546
547     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
548     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
549
550     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
551     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
552     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
553     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
554
555     // Altivec does not contain unordered floating-point compare instructions
556     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
557     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
558     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
559     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
560
561     if (Subtarget.hasVSX()) {
562       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
563       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
564       if (Subtarget.hasP8Vector()) {
565         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
566         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
567       }
568       if (Subtarget.hasDirectMove() && isPPC64) {
569         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
570         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
571         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
572         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
573         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
574         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
575         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
576         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
577       }
578       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
579
580       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
581       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
582       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
583       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
584       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
585
586       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
587
588       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
589       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
590
591       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
592       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
593
594       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
595       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
596       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
597       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
598       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
599
600       // Share the Altivec comparison restrictions.
601       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
602       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
603       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
604       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
605
606       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
607       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
608
609       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
610
611       if (Subtarget.hasP8Vector())
612         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
613
614       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
615
616       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
617       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
618       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
619
620       if (Subtarget.hasP8Altivec()) {
621         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
622         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
623         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
624
625         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
626       }
627       else {
628         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
629         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
630         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
631
632         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
633
634         // VSX v2i64 only supports non-arithmetic operations.
635         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
636         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
637       }
638
639       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
640       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
641       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
642       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
643
644       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
645
646       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
647       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
648       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
649       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
650
651       // Vector operation legalization checks the result type of
652       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
653       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
654       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
655       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
656       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
657
658       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
659       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
660       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
661       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
662
663       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
664     }
665
666     if (Subtarget.hasP8Altivec()) {
667       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
668       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
669     }
670     if (Subtarget.hasP9Vector()) {
671       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
672       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Legal);
673     }
674   }
675
676   if (Subtarget.hasQPX()) {
677     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
678     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
679     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
680     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
681
682     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
683     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
684
685     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
686     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
687
688     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
689     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
690
691     if (!Subtarget.useCRBits())
692       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
693     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
694
695     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
696     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
697     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
698     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
700     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
701     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
702
703     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
704     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
705
706     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
707     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
708     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
709
710     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
711     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
712     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
713     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
714     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
715     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
716     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
717     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
718     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
719     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
720     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
721
722     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
723     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
724
725     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
726     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
727
728     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
729
730     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
731     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
732     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
733     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
734
735     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
736     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
737
738     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
739     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
740
741     if (!Subtarget.useCRBits())
742       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
743     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
744
745     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
746     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
747     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
748     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
749     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
750     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
751     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
752
753     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
754     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
755
756     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
757     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
758     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
759     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
760     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
761     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
762     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
763     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
764     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
765     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
766     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
767
768     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
769     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
770
771     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
772     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
773
774     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
775
776     setOperationAction(ISD::AND , MVT::v4i1, Legal);
777     setOperationAction(ISD::OR , MVT::v4i1, Legal);
778     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
779
780     if (!Subtarget.useCRBits())
781       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
782     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
783
784     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
785     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
786
787     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
788     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
789     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
790     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
791     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
792     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
793     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
794
795     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
796     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
797
798     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
799
800     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
801     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
802     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
803     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
804
805     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
806     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
807     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
808     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
809
810     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
811     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
812
813     // These need to set FE_INEXACT, and so cannot be vectorized here.
814     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
815     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
816
817     if (TM.Options.UnsafeFPMath) {
818       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
819       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
820
821       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
822       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
823     } else {
824       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
825       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
826
827       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
828       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
829     }
830   }
831
832   if (Subtarget.has64BitSupport())
833     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
834
835   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
836
837   if (!isPPC64) {
838     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
839     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
840   }
841
842   setBooleanContents(ZeroOrOneBooleanContent);
843
844   if (Subtarget.hasAltivec()) {
845     // Altivec instructions set fields to all zeros or all ones.
846     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
847   }
848
849   if (!isPPC64) {
850     // These libcalls are not available in 32-bit.
851     setLibcallName(RTLIB::SHL_I128, nullptr);
852     setLibcallName(RTLIB::SRL_I128, nullptr);
853     setLibcallName(RTLIB::SRA_I128, nullptr);
854   }
855
856   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
857
858   // We have target-specific dag combine patterns for the following nodes:
859   setTargetDAGCombine(ISD::SINT_TO_FP);
860   setTargetDAGCombine(ISD::BUILD_VECTOR);
861   if (Subtarget.hasFPCVT())
862     setTargetDAGCombine(ISD::UINT_TO_FP);
863   setTargetDAGCombine(ISD::LOAD);
864   setTargetDAGCombine(ISD::STORE);
865   setTargetDAGCombine(ISD::BR_CC);
866   if (Subtarget.useCRBits())
867     setTargetDAGCombine(ISD::BRCOND);
868   setTargetDAGCombine(ISD::BSWAP);
869   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
870   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
871   setTargetDAGCombine(ISD::INTRINSIC_VOID);
872
873   setTargetDAGCombine(ISD::SIGN_EXTEND);
874   setTargetDAGCombine(ISD::ZERO_EXTEND);
875   setTargetDAGCombine(ISD::ANY_EXTEND);
876
877   if (Subtarget.useCRBits()) {
878     setTargetDAGCombine(ISD::TRUNCATE);
879     setTargetDAGCombine(ISD::SETCC);
880     setTargetDAGCombine(ISD::SELECT_CC);
881   }
882
883   // Use reciprocal estimates.
884   if (TM.Options.UnsafeFPMath) {
885     setTargetDAGCombine(ISD::FDIV);
886     setTargetDAGCombine(ISD::FSQRT);
887   }
888
889   // Darwin long double math library functions have $LDBL128 appended.
890   if (Subtarget.isDarwin()) {
891     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
892     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
893     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
894     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
895     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
896     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
897     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
898     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
899     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
900     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
901   }
902
903   // With 32 condition bits, we don't need to sink (and duplicate) compares
904   // aggressively in CodeGenPrep.
905   if (Subtarget.useCRBits()) {
906     setHasMultipleConditionRegisters();
907     setJumpIsExpensive();
908   }
909
910   setMinFunctionAlignment(2);
911   if (Subtarget.isDarwin())
912     setPrefFunctionAlignment(4);
913
914   switch (Subtarget.getDarwinDirective()) {
915   default: break;
916   case PPC::DIR_970:
917   case PPC::DIR_A2:
918   case PPC::DIR_E500mc:
919   case PPC::DIR_E5500:
920   case PPC::DIR_PWR4:
921   case PPC::DIR_PWR5:
922   case PPC::DIR_PWR5X:
923   case PPC::DIR_PWR6:
924   case PPC::DIR_PWR6X:
925   case PPC::DIR_PWR7:
926   case PPC::DIR_PWR8:
927   case PPC::DIR_PWR9:
928     setPrefFunctionAlignment(4);
929     setPrefLoopAlignment(4);
930     break;
931   }
932
933   if (Subtarget.enableMachineScheduler())
934     setSchedulingPreference(Sched::Source);
935   else
936     setSchedulingPreference(Sched::Hybrid);
937
938   computeRegisterProperties(STI.getRegisterInfo());
939
940   // The Freescale cores do better with aggressive inlining of memcpy and
941   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
942   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
943       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
944     MaxStoresPerMemset = 32;
945     MaxStoresPerMemsetOptSize = 16;
946     MaxStoresPerMemcpy = 32;
947     MaxStoresPerMemcpyOptSize = 8;
948     MaxStoresPerMemmove = 32;
949     MaxStoresPerMemmoveOptSize = 8;
950   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
951     // The A2 also benefits from (very) aggressive inlining of memcpy and
952     // friends. The overhead of a the function call, even when warm, can be
953     // over one hundred cycles.
954     MaxStoresPerMemset = 128;
955     MaxStoresPerMemcpy = 128;
956     MaxStoresPerMemmove = 128;
957   }
958 }
959
960 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
961 /// the desired ByVal argument alignment.
962 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
963                              unsigned MaxMaxAlign) {
964   if (MaxAlign == MaxMaxAlign)
965     return;
966   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
967     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
968       MaxAlign = 32;
969     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
970       MaxAlign = 16;
971   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
972     unsigned EltAlign = 0;
973     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
974     if (EltAlign > MaxAlign)
975       MaxAlign = EltAlign;
976   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
977     for (auto *EltTy : STy->elements()) {
978       unsigned EltAlign = 0;
979       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
980       if (EltAlign > MaxAlign)
981         MaxAlign = EltAlign;
982       if (MaxAlign == MaxMaxAlign)
983         break;
984     }
985   }
986 }
987
988 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
989 /// function arguments in the caller parameter area.
990 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
991                                                   const DataLayout &DL) const {
992   // Darwin passes everything on 4 byte boundary.
993   if (Subtarget.isDarwin())
994     return 4;
995
996   // 16byte and wider vectors are passed on 16byte boundary.
997   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
998   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
999   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1000     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1001   return Align;
1002 }
1003
1004 bool PPCTargetLowering::useSoftFloat() const {
1005   return Subtarget.useSoftFloat();
1006 }
1007
1008 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009   switch ((PPCISD::NodeType)Opcode) {
1010   case PPCISD::FIRST_NUMBER:    break;
1011   case PPCISD::FSEL:            return "PPCISD::FSEL";
1012   case PPCISD::FCFID:           return "PPCISD::FCFID";
1013   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1014   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1015   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1016   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1017   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1018   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1019   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1020   case PPCISD::FRE:             return "PPCISD::FRE";
1021   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1022   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1023   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1024   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1025   case PPCISD::VPERM:           return "PPCISD::VPERM";
1026   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1027   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1028   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1029   case PPCISD::CMPB:            return "PPCISD::CMPB";
1030   case PPCISD::Hi:              return "PPCISD::Hi";
1031   case PPCISD::Lo:              return "PPCISD::Lo";
1032   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1033   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1034   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1035   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1036   case PPCISD::SRL:             return "PPCISD::SRL";
1037   case PPCISD::SRA:             return "PPCISD::SRA";
1038   case PPCISD::SHL:             return "PPCISD::SHL";
1039   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1040   case PPCISD::CALL:            return "PPCISD::CALL";
1041   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1042   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1043   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1044   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1045   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1046   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1047   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1048   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1049   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1050   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1051   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1052   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1053   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1054   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1055   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1056   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1057   case PPCISD::VCMP:            return "PPCISD::VCMP";
1058   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1059   case PPCISD::LBRX:            return "PPCISD::LBRX";
1060   case PPCISD::STBRX:           return "PPCISD::STBRX";
1061   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1062   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1063   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1064   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1065   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1066   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1067   case PPCISD::BDZ:             return "PPCISD::BDZ";
1068   case PPCISD::MFFS:            return "PPCISD::MFFS";
1069   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1070   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1071   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1072   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1073   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1074   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1075   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1076   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1077   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1078   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1079   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1080   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1081   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1082   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1083   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1084   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1085   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1086   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1087   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1088   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1089   case PPCISD::SC:              return "PPCISD::SC";
1090   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1091   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1092   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1093   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1094   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1095   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1096   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1097   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1098   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1099   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1100   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1101   }
1102   return nullptr;
1103 }
1104
1105 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1106                                           EVT VT) const {
1107   if (!VT.isVector())
1108     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1109
1110   if (Subtarget.hasQPX())
1111     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1112
1113   return VT.changeVectorElementTypeToInteger();
1114 }
1115
1116 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1117   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1118   return true;
1119 }
1120
1121 //===----------------------------------------------------------------------===//
1122 // Node matching predicates, for use by the tblgen matching code.
1123 //===----------------------------------------------------------------------===//
1124
1125 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1126 static bool isFloatingPointZero(SDValue Op) {
1127   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1128     return CFP->getValueAPF().isZero();
1129   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1130     // Maybe this has already been legalized into the constant pool?
1131     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1132       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1133         return CFP->getValueAPF().isZero();
1134   }
1135   return false;
1136 }
1137
1138 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1139 /// true if Op is undef or if it matches the specified value.
1140 static bool isConstantOrUndef(int Op, int Val) {
1141   return Op < 0 || Op == Val;
1142 }
1143
1144 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1145 /// VPKUHUM instruction.
1146 /// The ShuffleKind distinguishes between big-endian operations with
1147 /// two different inputs (0), either-endian operations with two identical
1148 /// inputs (1), and little-endian operations with two different inputs (2).
1149 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1150 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1151                                SelectionDAG &DAG) {
1152   bool IsLE = DAG.getDataLayout().isLittleEndian();
1153   if (ShuffleKind == 0) {
1154     if (IsLE)
1155       return false;
1156     for (unsigned i = 0; i != 16; ++i)
1157       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1158         return false;
1159   } else if (ShuffleKind == 2) {
1160     if (!IsLE)
1161       return false;
1162     for (unsigned i = 0; i != 16; ++i)
1163       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1164         return false;
1165   } else if (ShuffleKind == 1) {
1166     unsigned j = IsLE ? 0 : 1;
1167     for (unsigned i = 0; i != 8; ++i)
1168       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1169           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1170         return false;
1171   }
1172   return true;
1173 }
1174
1175 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1176 /// VPKUWUM instruction.
1177 /// The ShuffleKind distinguishes between big-endian operations with
1178 /// two different inputs (0), either-endian operations with two identical
1179 /// inputs (1), and little-endian operations with two different inputs (2).
1180 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1181 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1182                                SelectionDAG &DAG) {
1183   bool IsLE = DAG.getDataLayout().isLittleEndian();
1184   if (ShuffleKind == 0) {
1185     if (IsLE)
1186       return false;
1187     for (unsigned i = 0; i != 16; i += 2)
1188       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1189           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1190         return false;
1191   } else if (ShuffleKind == 2) {
1192     if (!IsLE)
1193       return false;
1194     for (unsigned i = 0; i != 16; i += 2)
1195       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1196           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1197         return false;
1198   } else if (ShuffleKind == 1) {
1199     unsigned j = IsLE ? 0 : 2;
1200     for (unsigned i = 0; i != 8; i += 2)
1201       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1202           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1203           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1204           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1205         return false;
1206   }
1207   return true;
1208 }
1209
1210 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1211 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1212 /// current subtarget.
1213 ///
1214 /// The ShuffleKind distinguishes between big-endian operations with
1215 /// two different inputs (0), either-endian operations with two identical
1216 /// inputs (1), and little-endian operations with two different inputs (2).
1217 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1218 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1219                                SelectionDAG &DAG) {
1220   const PPCSubtarget& Subtarget =
1221     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1222   if (!Subtarget.hasP8Vector())
1223     return false;
1224
1225   bool IsLE = DAG.getDataLayout().isLittleEndian();
1226   if (ShuffleKind == 0) {
1227     if (IsLE)
1228       return false;
1229     for (unsigned i = 0; i != 16; i += 4)
1230       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1231           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1232           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1233           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1234         return false;
1235   } else if (ShuffleKind == 2) {
1236     if (!IsLE)
1237       return false;
1238     for (unsigned i = 0; i != 16; i += 4)
1239       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1240           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1241           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1242           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1243         return false;
1244   } else if (ShuffleKind == 1) {
1245     unsigned j = IsLE ? 0 : 4;
1246     for (unsigned i = 0; i != 8; i += 4)
1247       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1248           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1249           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1250           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1251           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1252           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1253           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1254           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1255         return false;
1256   }
1257   return true;
1258 }
1259
1260 /// isVMerge - Common function, used to match vmrg* shuffles.
1261 ///
1262 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1263                      unsigned LHSStart, unsigned RHSStart) {
1264   if (N->getValueType(0) != MVT::v16i8)
1265     return false;
1266   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1267          "Unsupported merge size!");
1268
1269   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1270     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1271       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1272                              LHSStart+j+i*UnitSize) ||
1273           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1274                              RHSStart+j+i*UnitSize))
1275         return false;
1276     }
1277   return true;
1278 }
1279
1280 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1281 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1282 /// The ShuffleKind distinguishes between big-endian merges with two
1283 /// different inputs (0), either-endian merges with two identical inputs (1),
1284 /// and little-endian merges with two different inputs (2).  For the latter,
1285 /// the input operands are swapped (see PPCInstrAltivec.td).
1286 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1287                              unsigned ShuffleKind, SelectionDAG &DAG) {
1288   if (DAG.getDataLayout().isLittleEndian()) {
1289     if (ShuffleKind == 1) // unary
1290       return isVMerge(N, UnitSize, 0, 0);
1291     else if (ShuffleKind == 2) // swapped
1292       return isVMerge(N, UnitSize, 0, 16);
1293     else
1294       return false;
1295   } else {
1296     if (ShuffleKind == 1) // unary
1297       return isVMerge(N, UnitSize, 8, 8);
1298     else if (ShuffleKind == 0) // normal
1299       return isVMerge(N, UnitSize, 8, 24);
1300     else
1301       return false;
1302   }
1303 }
1304
1305 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1306 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1307 /// The ShuffleKind distinguishes between big-endian merges with two
1308 /// different inputs (0), either-endian merges with two identical inputs (1),
1309 /// and little-endian merges with two different inputs (2).  For the latter,
1310 /// the input operands are swapped (see PPCInstrAltivec.td).
1311 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1312                              unsigned ShuffleKind, SelectionDAG &DAG) {
1313   if (DAG.getDataLayout().isLittleEndian()) {
1314     if (ShuffleKind == 1) // unary
1315       return isVMerge(N, UnitSize, 8, 8);
1316     else if (ShuffleKind == 2) // swapped
1317       return isVMerge(N, UnitSize, 8, 24);
1318     else
1319       return false;
1320   } else {
1321     if (ShuffleKind == 1) // unary
1322       return isVMerge(N, UnitSize, 0, 0);
1323     else if (ShuffleKind == 0) // normal
1324       return isVMerge(N, UnitSize, 0, 16);
1325     else
1326       return false;
1327   }
1328 }
1329
1330 /**
1331  * \brief Common function used to match vmrgew and vmrgow shuffles
1332  *
1333  * The indexOffset determines whether to look for even or odd words in
1334  * the shuffle mask. This is based on the of the endianness of the target
1335  * machine.
1336  *   - Little Endian:
1337  *     - Use offset of 0 to check for odd elements
1338  *     - Use offset of 4 to check for even elements
1339  *   - Big Endian:
1340  *     - Use offset of 0 to check for even elements
1341  *     - Use offset of 4 to check for odd elements
1342  * A detailed description of the vector element ordering for little endian and
1343  * big endian can be found at
1344  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1345  * Targeting your applications - what little endian and big endian IBM XL C/C++
1346  * compiler differences mean to you
1347  *
1348  * The mask to the shuffle vector instruction specifies the indices of the
1349  * elements from the two input vectors to place in the result. The elements are
1350  * numbered in array-access order, starting with the first vector. These vectors
1351  * are always of type v16i8, thus each vector will contain 16 elements of size
1352  * 8. More info on the shuffle vector can be found in the
1353  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1354  * Language Reference.
1355  *
1356  * The RHSStartValue indicates whether the same input vectors are used (unary)
1357  * or two different input vectors are used, based on the following:
1358  *   - If the instruction uses the same vector for both inputs, the range of the
1359  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1360  *     be 0.
1361  *   - If the instruction has two different vectors then the range of the
1362  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1363  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1364  *     to 31 specify elements in the second vector).
1365  *
1366  * \param[in] N The shuffle vector SD Node to analyze
1367  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1368  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1369  * vector to the shuffle_vector instruction
1370  * \return true iff this shuffle vector represents an even or odd word merge
1371  */
1372 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1373                      unsigned RHSStartValue) {
1374   if (N->getValueType(0) != MVT::v16i8)
1375     return false;
1376
1377   for (unsigned i = 0; i < 2; ++i)
1378     for (unsigned j = 0; j < 4; ++j)
1379       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1380                              i*RHSStartValue+j+IndexOffset) ||
1381           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1382                              i*RHSStartValue+j+IndexOffset+8))
1383         return false;
1384   return true;
1385 }
1386
1387 /**
1388  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1389  * vmrgow instructions.
1390  *
1391  * \param[in] N The shuffle vector SD Node to analyze
1392  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1393  * \param[in] ShuffleKind Identify the type of merge:
1394  *   - 0 = big-endian merge with two different inputs;
1395  *   - 1 = either-endian merge with two identical inputs;
1396  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1397  *     little-endian merges).
1398  * \param[in] DAG The current SelectionDAG
1399  * \return true iff this shuffle mask
1400  */
1401 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1402                               unsigned ShuffleKind, SelectionDAG &DAG) {
1403   if (DAG.getDataLayout().isLittleEndian()) {
1404     unsigned indexOffset = CheckEven ? 4 : 0;
1405     if (ShuffleKind == 1) // Unary
1406       return isVMerge(N, indexOffset, 0);
1407     else if (ShuffleKind == 2) // swapped
1408       return isVMerge(N, indexOffset, 16);
1409     else
1410       return false;
1411   }
1412   else {
1413     unsigned indexOffset = CheckEven ? 0 : 4;
1414     if (ShuffleKind == 1) // Unary
1415       return isVMerge(N, indexOffset, 0);
1416     else if (ShuffleKind == 0) // Normal
1417       return isVMerge(N, indexOffset, 16);
1418     else
1419       return false;
1420   }
1421   return false;
1422 }
1423
1424 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1425 /// amount, otherwise return -1.
1426 /// The ShuffleKind distinguishes between big-endian operations with two
1427 /// different inputs (0), either-endian operations with two identical inputs
1428 /// (1), and little-endian operations with two different inputs (2).  For the
1429 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1430 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1431                              SelectionDAG &DAG) {
1432   if (N->getValueType(0) != MVT::v16i8)
1433     return -1;
1434
1435   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1436
1437   // Find the first non-undef value in the shuffle mask.
1438   unsigned i;
1439   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1440     /*search*/;
1441
1442   if (i == 16) return -1;  // all undef.
1443
1444   // Otherwise, check to see if the rest of the elements are consecutively
1445   // numbered from this value.
1446   unsigned ShiftAmt = SVOp->getMaskElt(i);
1447   if (ShiftAmt < i) return -1;
1448
1449   ShiftAmt -= i;
1450   bool isLE = DAG.getDataLayout().isLittleEndian();
1451
1452   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1453     // Check the rest of the elements to see if they are consecutive.
1454     for (++i; i != 16; ++i)
1455       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1456         return -1;
1457   } else if (ShuffleKind == 1) {
1458     // Check the rest of the elements to see if they are consecutive.
1459     for (++i; i != 16; ++i)
1460       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1461         return -1;
1462   } else
1463     return -1;
1464
1465   if (isLE)
1466     ShiftAmt = 16 - ShiftAmt;
1467
1468   return ShiftAmt;
1469 }
1470
1471 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1472 /// specifies a splat of a single element that is suitable for input to
1473 /// VSPLTB/VSPLTH/VSPLTW.
1474 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1475   assert(N->getValueType(0) == MVT::v16i8 &&
1476          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1477
1478   // The consecutive indices need to specify an element, not part of two
1479   // different elements.  So abandon ship early if this isn't the case.
1480   if (N->getMaskElt(0) % EltSize != 0)
1481     return false;
1482
1483   // This is a splat operation if each element of the permute is the same, and
1484   // if the value doesn't reference the second vector.
1485   unsigned ElementBase = N->getMaskElt(0);
1486
1487   // FIXME: Handle UNDEF elements too!
1488   if (ElementBase >= 16)
1489     return false;
1490
1491   // Check that the indices are consecutive, in the case of a multi-byte element
1492   // splatted with a v16i8 mask.
1493   for (unsigned i = 1; i != EltSize; ++i)
1494     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1495       return false;
1496
1497   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1498     if (N->getMaskElt(i) < 0) continue;
1499     for (unsigned j = 0; j != EltSize; ++j)
1500       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1501         return false;
1502   }
1503   return true;
1504 }
1505
1506 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1507                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1508
1509   // Check that the mask is shuffling words
1510   for (unsigned i = 0; i < 4; ++i) {
1511     unsigned B0 = N->getMaskElt(i*4);
1512     unsigned B1 = N->getMaskElt(i*4+1);
1513     unsigned B2 = N->getMaskElt(i*4+2);
1514     unsigned B3 = N->getMaskElt(i*4+3);
1515     if (B0 % 4)
1516       return false;
1517     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1518       return false;
1519   }
1520
1521   // Now we look at mask elements 0,4,8,12
1522   unsigned M0 = N->getMaskElt(0) / 4;
1523   unsigned M1 = N->getMaskElt(4) / 4;
1524   unsigned M2 = N->getMaskElt(8) / 4;
1525   unsigned M3 = N->getMaskElt(12) / 4;
1526   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1527   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1528
1529   // Below, let H and L be arbitrary elements of the shuffle mask
1530   // where H is in the range [4,7] and L is in the range [0,3].
1531   // H, 1, 2, 3 or L, 5, 6, 7
1532   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1533       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1534     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1535     InsertAtByte = IsLE ? 12 : 0;
1536     Swap = M0 < 4;
1537     return true;
1538   }
1539   // 0, H, 2, 3 or 4, L, 6, 7
1540   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1541       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1542     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1543     InsertAtByte = IsLE ? 8 : 4;
1544     Swap = M1 < 4;
1545     return true;
1546   }
1547   // 0, 1, H, 3 or 4, 5, L, 7
1548   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1549       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1550     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1551     InsertAtByte = IsLE ? 4 : 8;
1552     Swap = M2 < 4;
1553     return true;
1554   }
1555   // 0, 1, 2, H or 4, 5, 6, L
1556   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1557       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1558     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1559     InsertAtByte = IsLE ? 0 : 12;
1560     Swap = M3 < 4;
1561     return true;
1562   }
1563
1564   // If both vector operands for the shuffle are the same vector, the mask will
1565   // contain only elements from the first one and the second one will be undef.
1566   if (N->getOperand(1).isUndef()) {
1567     ShiftElts = 0;
1568     Swap = true;
1569     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1570     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1571       InsertAtByte = IsLE ? 12 : 0;
1572       return true;
1573     }
1574     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1575       InsertAtByte = IsLE ? 8 : 4;
1576       return true;
1577     }
1578     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1579       InsertAtByte = IsLE ? 4 : 8;
1580       return true;
1581     }
1582     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1583       InsertAtByte = IsLE ? 0 : 12;
1584       return true;
1585     }
1586   }
1587
1588   return false;
1589 }
1590
1591 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1592 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1593 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1594                                 SelectionDAG &DAG) {
1595   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1596   assert(isSplatShuffleMask(SVOp, EltSize));
1597   if (DAG.getDataLayout().isLittleEndian())
1598     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1599   else
1600     return SVOp->getMaskElt(0) / EltSize;
1601 }
1602
1603 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1604 /// by using a vspltis[bhw] instruction of the specified element size, return
1605 /// the constant being splatted.  The ByteSize field indicates the number of
1606 /// bytes of each element [124] -> [bhw].
1607 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1608   SDValue OpVal(nullptr, 0);
1609
1610   // If ByteSize of the splat is bigger than the element size of the
1611   // build_vector, then we have a case where we are checking for a splat where
1612   // multiple elements of the buildvector are folded together into a single
1613   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1614   unsigned EltSize = 16/N->getNumOperands();
1615   if (EltSize < ByteSize) {
1616     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1617     SDValue UniquedVals[4];
1618     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1619
1620     // See if all of the elements in the buildvector agree across.
1621     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1622       if (N->getOperand(i).isUndef()) continue;
1623       // If the element isn't a constant, bail fully out.
1624       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1625
1626
1627       if (!UniquedVals[i&(Multiple-1)].getNode())
1628         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1629       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1630         return SDValue();  // no match.
1631     }
1632
1633     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1634     // either constant or undef values that are identical for each chunk.  See
1635     // if these chunks can form into a larger vspltis*.
1636
1637     // Check to see if all of the leading entries are either 0 or -1.  If
1638     // neither, then this won't fit into the immediate field.
1639     bool LeadingZero = true;
1640     bool LeadingOnes = true;
1641     for (unsigned i = 0; i != Multiple-1; ++i) {
1642       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1643
1644       LeadingZero &= isNullConstant(UniquedVals[i]);
1645       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1646     }
1647     // Finally, check the least significant entry.
1648     if (LeadingZero) {
1649       if (!UniquedVals[Multiple-1].getNode())
1650         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1651       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1652       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1653         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1654     }
1655     if (LeadingOnes) {
1656       if (!UniquedVals[Multiple-1].getNode())
1657         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1658       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1659       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1660         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1661     }
1662
1663     return SDValue();
1664   }
1665
1666   // Check to see if this buildvec has a single non-undef value in its elements.
1667   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1668     if (N->getOperand(i).isUndef()) continue;
1669     if (!OpVal.getNode())
1670       OpVal = N->getOperand(i);
1671     else if (OpVal != N->getOperand(i))
1672       return SDValue();
1673   }
1674
1675   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1676
1677   unsigned ValSizeInBytes = EltSize;
1678   uint64_t Value = 0;
1679   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1680     Value = CN->getZExtValue();
1681   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1682     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1683     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1684   }
1685
1686   // If the splat value is larger than the element value, then we can never do
1687   // this splat.  The only case that we could fit the replicated bits into our
1688   // immediate field for would be zero, and we prefer to use vxor for it.
1689   if (ValSizeInBytes < ByteSize) return SDValue();
1690
1691   // If the element value is larger than the splat value, check if it consists
1692   // of a repeated bit pattern of size ByteSize.
1693   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1694     return SDValue();
1695
1696   // Properly sign extend the value.
1697   int MaskVal = SignExtend32(Value, ByteSize * 8);
1698
1699   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1700   if (MaskVal == 0) return SDValue();
1701
1702   // Finally, if this value fits in a 5 bit sext field, return it
1703   if (SignExtend32<5>(MaskVal) == MaskVal)
1704     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1705   return SDValue();
1706 }
1707
1708 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1709 /// amount, otherwise return -1.
1710 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1711   EVT VT = N->getValueType(0);
1712   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1713     return -1;
1714
1715   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1716
1717   // Find the first non-undef value in the shuffle mask.
1718   unsigned i;
1719   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1720     /*search*/;
1721
1722   if (i == 4) return -1;  // all undef.
1723
1724   // Otherwise, check to see if the rest of the elements are consecutively
1725   // numbered from this value.
1726   unsigned ShiftAmt = SVOp->getMaskElt(i);
1727   if (ShiftAmt < i) return -1;
1728   ShiftAmt -= i;
1729
1730   // Check the rest of the elements to see if they are consecutive.
1731   for (++i; i != 4; ++i)
1732     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1733       return -1;
1734
1735   return ShiftAmt;
1736 }
1737
1738 //===----------------------------------------------------------------------===//
1739 //  Addressing Mode Selection
1740 //===----------------------------------------------------------------------===//
1741
1742 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1743 /// or 64-bit immediate, and if the value can be accurately represented as a
1744 /// sign extension from a 16-bit value.  If so, this returns true and the
1745 /// immediate.
1746 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1747   if (!isa<ConstantSDNode>(N))
1748     return false;
1749
1750   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1751   if (N->getValueType(0) == MVT::i32)
1752     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1753   else
1754     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1755 }
1756 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1757   return isIntS16Immediate(Op.getNode(), Imm);
1758 }
1759
1760 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1761 /// can be represented as an indexed [r+r] operation.  Returns false if it
1762 /// can be more efficiently represented with [r+imm].
1763 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1764                                             SDValue &Index,
1765                                             SelectionDAG &DAG) const {
1766   short imm = 0;
1767   if (N.getOpcode() == ISD::ADD) {
1768     if (isIntS16Immediate(N.getOperand(1), imm))
1769       return false;    // r+i
1770     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1771       return false;    // r+i
1772
1773     Base = N.getOperand(0);
1774     Index = N.getOperand(1);
1775     return true;
1776   } else if (N.getOpcode() == ISD::OR) {
1777     if (isIntS16Immediate(N.getOperand(1), imm))
1778       return false;    // r+i can fold it if we can.
1779
1780     // If this is an or of disjoint bitfields, we can codegen this as an add
1781     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1782     // disjoint.
1783     APInt LHSKnownZero, LHSKnownOne;
1784     APInt RHSKnownZero, RHSKnownOne;
1785     DAG.computeKnownBits(N.getOperand(0),
1786                          LHSKnownZero, LHSKnownOne);
1787
1788     if (LHSKnownZero.getBoolValue()) {
1789       DAG.computeKnownBits(N.getOperand(1),
1790                            RHSKnownZero, RHSKnownOne);
1791       // If all of the bits are known zero on the LHS or RHS, the add won't
1792       // carry.
1793       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1794         Base = N.getOperand(0);
1795         Index = N.getOperand(1);
1796         return true;
1797       }
1798     }
1799   }
1800
1801   return false;
1802 }
1803
1804 // If we happen to be doing an i64 load or store into a stack slot that has
1805 // less than a 4-byte alignment, then the frame-index elimination may need to
1806 // use an indexed load or store instruction (because the offset may not be a
1807 // multiple of 4). The extra register needed to hold the offset comes from the
1808 // register scavenger, and it is possible that the scavenger will need to use
1809 // an emergency spill slot. As a result, we need to make sure that a spill slot
1810 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1811 // stack slot.
1812 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1813   // FIXME: This does not handle the LWA case.
1814   if (VT != MVT::i64)
1815     return;
1816
1817   // NOTE: We'll exclude negative FIs here, which come from argument
1818   // lowering, because there are no known test cases triggering this problem
1819   // using packed structures (or similar). We can remove this exclusion if
1820   // we find such a test case. The reason why this is so test-case driven is
1821   // because this entire 'fixup' is only to prevent crashes (from the
1822   // register scavenger) on not-really-valid inputs. For example, if we have:
1823   //   %a = alloca i1
1824   //   %b = bitcast i1* %a to i64*
1825   //   store i64* a, i64 b
1826   // then the store should really be marked as 'align 1', but is not. If it
1827   // were marked as 'align 1' then the indexed form would have been
1828   // instruction-selected initially, and the problem this 'fixup' is preventing
1829   // won't happen regardless.
1830   if (FrameIdx < 0)
1831     return;
1832
1833   MachineFunction &MF = DAG.getMachineFunction();
1834   MachineFrameInfo *MFI = MF.getFrameInfo();
1835
1836   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1837   if (Align >= 4)
1838     return;
1839
1840   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1841   FuncInfo->setHasNonRISpills();
1842 }
1843
1844 /// Returns true if the address N can be represented by a base register plus
1845 /// a signed 16-bit displacement [r+imm], and if it is not better
1846 /// represented as reg+reg.  If Aligned is true, only accept displacements
1847 /// suitable for STD and friends, i.e. multiples of 4.
1848 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1849                                             SDValue &Base,
1850                                             SelectionDAG &DAG,
1851                                             bool Aligned) const {
1852   // FIXME dl should come from parent load or store, not from address
1853   SDLoc dl(N);
1854   // If this can be more profitably realized as r+r, fail.
1855   if (SelectAddressRegReg(N, Disp, Base, DAG))
1856     return false;
1857
1858   if (N.getOpcode() == ISD::ADD) {
1859     short imm = 0;
1860     if (isIntS16Immediate(N.getOperand(1), imm) &&
1861         (!Aligned || (imm & 3) == 0)) {
1862       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1863       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1864         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1865         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1866       } else {
1867         Base = N.getOperand(0);
1868       }
1869       return true; // [r+i]
1870     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1871       // Match LOAD (ADD (X, Lo(G))).
1872       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1873              && "Cannot handle constant offsets yet!");
1874       Disp = N.getOperand(1).getOperand(0);  // The global address.
1875       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1876              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1877              Disp.getOpcode() == ISD::TargetConstantPool ||
1878              Disp.getOpcode() == ISD::TargetJumpTable);
1879       Base = N.getOperand(0);
1880       return true;  // [&g+r]
1881     }
1882   } else if (N.getOpcode() == ISD::OR) {
1883     short imm = 0;
1884     if (isIntS16Immediate(N.getOperand(1), imm) &&
1885         (!Aligned || (imm & 3) == 0)) {
1886       // If this is an or of disjoint bitfields, we can codegen this as an add
1887       // (for better address arithmetic) if the LHS and RHS of the OR are
1888       // provably disjoint.
1889       APInt LHSKnownZero, LHSKnownOne;
1890       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1891
1892       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1893         // If all of the bits are known zero on the LHS or RHS, the add won't
1894         // carry.
1895         if (FrameIndexSDNode *FI =
1896               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1897           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1898           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1899         } else {
1900           Base = N.getOperand(0);
1901         }
1902         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1903         return true;
1904       }
1905     }
1906   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1907     // Loading from a constant address.
1908
1909     // If this address fits entirely in a 16-bit sext immediate field, codegen
1910     // this as "d, 0"
1911     short Imm;
1912     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1913       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1914       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1915                              CN->getValueType(0));
1916       return true;
1917     }
1918
1919     // Handle 32-bit sext immediates with LIS + addr mode.
1920     if ((CN->getValueType(0) == MVT::i32 ||
1921          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1922         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1923       int Addr = (int)CN->getZExtValue();
1924
1925       // Otherwise, break this down into an LIS + disp.
1926       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1927
1928       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1929                                    MVT::i32);
1930       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1931       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1932       return true;
1933     }
1934   }
1935
1936   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1937   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1938     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1939     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1940   } else
1941     Base = N;
1942   return true;      // [r+0]
1943 }
1944
1945 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1946 /// represented as an indexed [r+r] operation.
1947 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1948                                                 SDValue &Index,
1949                                                 SelectionDAG &DAG) const {
1950   // Check to see if we can easily represent this as an [r+r] address.  This
1951   // will fail if it thinks that the address is more profitably represented as
1952   // reg+imm, e.g. where imm = 0.
1953   if (SelectAddressRegReg(N, Base, Index, DAG))
1954     return true;
1955
1956   // If the operand is an addition, always emit this as [r+r], since this is
1957   // better (for code size, and execution, as the memop does the add for free)
1958   // than emitting an explicit add.
1959   if (N.getOpcode() == ISD::ADD) {
1960     Base = N.getOperand(0);
1961     Index = N.getOperand(1);
1962     return true;
1963   }
1964
1965   // Otherwise, do it the hard way, using R0 as the base register.
1966   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1967                          N.getValueType());
1968   Index = N;
1969   return true;
1970 }
1971
1972 /// getPreIndexedAddressParts - returns true by value, base pointer and
1973 /// offset pointer and addressing mode by reference if the node's address
1974 /// can be legally represented as pre-indexed load / store address.
1975 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1976                                                   SDValue &Offset,
1977                                                   ISD::MemIndexedMode &AM,
1978                                                   SelectionDAG &DAG) const {
1979   if (DisablePPCPreinc) return false;
1980
1981   bool isLoad = true;
1982   SDValue Ptr;
1983   EVT VT;
1984   unsigned Alignment;
1985   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1986     Ptr = LD->getBasePtr();
1987     VT = LD->getMemoryVT();
1988     Alignment = LD->getAlignment();
1989   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1990     Ptr = ST->getBasePtr();
1991     VT  = ST->getMemoryVT();
1992     Alignment = ST->getAlignment();
1993     isLoad = false;
1994   } else
1995     return false;
1996
1997   // PowerPC doesn't have preinc load/store instructions for vectors (except
1998   // for QPX, which does have preinc r+r forms).
1999   if (VT.isVector()) {
2000     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2001       return false;
2002     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2003       AM = ISD::PRE_INC;
2004       return true;
2005     }
2006   }
2007
2008   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2009
2010     // Common code will reject creating a pre-inc form if the base pointer
2011     // is a frame index, or if N is a store and the base pointer is either
2012     // the same as or a predecessor of the value being stored.  Check for
2013     // those situations here, and try with swapped Base/Offset instead.
2014     bool Swap = false;
2015
2016     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2017       Swap = true;
2018     else if (!isLoad) {
2019       SDValue Val = cast<StoreSDNode>(N)->getValue();
2020       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2021         Swap = true;
2022     }
2023
2024     if (Swap)
2025       std::swap(Base, Offset);
2026
2027     AM = ISD::PRE_INC;
2028     return true;
2029   }
2030
2031   // LDU/STU can only handle immediates that are a multiple of 4.
2032   if (VT != MVT::i64) {
2033     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2034       return false;
2035   } else {
2036     // LDU/STU need an address with at least 4-byte alignment.
2037     if (Alignment < 4)
2038       return false;
2039
2040     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2041       return false;
2042   }
2043
2044   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2045     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2046     // sext i32 to i64 when addr mode is r+i.
2047     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2048         LD->getExtensionType() == ISD::SEXTLOAD &&
2049         isa<ConstantSDNode>(Offset))
2050       return false;
2051   }
2052
2053   AM = ISD::PRE_INC;
2054   return true;
2055 }
2056
2057 //===----------------------------------------------------------------------===//
2058 //  LowerOperation implementation
2059 //===----------------------------------------------------------------------===//
2060
2061 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2062 /// and LoOpFlags to the target MO flags.
2063 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2064                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2065                                const GlobalValue *GV = nullptr) {
2066   HiOpFlags = PPCII::MO_HA;
2067   LoOpFlags = PPCII::MO_LO;
2068
2069   // Don't use the pic base if not in PIC relocation model.
2070   if (IsPIC) {
2071     HiOpFlags |= PPCII::MO_PIC_FLAG;
2072     LoOpFlags |= PPCII::MO_PIC_FLAG;
2073   }
2074
2075   // If this is a reference to a global value that requires a non-lazy-ptr, make
2076   // sure that instruction lowering adds it.
2077   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2078     HiOpFlags |= PPCII::MO_NLP_FLAG;
2079     LoOpFlags |= PPCII::MO_NLP_FLAG;
2080
2081     if (GV->hasHiddenVisibility()) {
2082       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2083       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2084     }
2085   }
2086 }
2087
2088 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2089                              SelectionDAG &DAG) {
2090   SDLoc DL(HiPart);
2091   EVT PtrVT = HiPart.getValueType();
2092   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2093
2094   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2095   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2096
2097   // With PIC, the first instruction is actually "GR+hi(&G)".
2098   if (isPIC)
2099     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2100                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2101
2102   // Generate non-pic code that has direct accesses to the constant pool.
2103   // The address of the global is just (hi(&g)+lo(&g)).
2104   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2105 }
2106
2107 static void setUsesTOCBasePtr(MachineFunction &MF) {
2108   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2109   FuncInfo->setUsesTOCBasePtr();
2110 }
2111
2112 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2113   setUsesTOCBasePtr(DAG.getMachineFunction());
2114 }
2115
2116 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2117                            SDValue GA) {
2118   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2119   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2120                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2121
2122   SDValue Ops[] = { GA, Reg };
2123   return DAG.getMemIntrinsicNode(
2124       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2125       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2126       false, 0);
2127 }
2128
2129 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2130                                              SelectionDAG &DAG) const {
2131   EVT PtrVT = Op.getValueType();
2132   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2133   const Constant *C = CP->getConstVal();
2134
2135   // 64-bit SVR4 ABI code is always position-independent.
2136   // The actual address of the GlobalValue is stored in the TOC.
2137   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2138     setUsesTOCBasePtr(DAG);
2139     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2140     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2141   }
2142
2143   unsigned MOHiFlag, MOLoFlag;
2144   bool IsPIC = isPositionIndependent();
2145   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2146
2147   if (IsPIC && Subtarget.isSVR4ABI()) {
2148     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2149                                            PPCII::MO_PIC_FLAG);
2150     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2151   }
2152
2153   SDValue CPIHi =
2154     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2155   SDValue CPILo =
2156     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2157   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2158 }
2159
2160 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2161   EVT PtrVT = Op.getValueType();
2162   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2163
2164   // 64-bit SVR4 ABI code is always position-independent.
2165   // The actual address of the GlobalValue is stored in the TOC.
2166   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2167     setUsesTOCBasePtr(DAG);
2168     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2169     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2170   }
2171
2172   unsigned MOHiFlag, MOLoFlag;
2173   bool IsPIC = isPositionIndependent();
2174   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2175
2176   if (IsPIC && Subtarget.isSVR4ABI()) {
2177     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2178                                         PPCII::MO_PIC_FLAG);
2179     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2180   }
2181
2182   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2183   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2184   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2185 }
2186
2187 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2188                                              SelectionDAG &DAG) const {
2189   EVT PtrVT = Op.getValueType();
2190   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2191   const BlockAddress *BA = BASDN->getBlockAddress();
2192
2193   // 64-bit SVR4 ABI code is always position-independent.
2194   // The actual BlockAddress is stored in the TOC.
2195   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2196     setUsesTOCBasePtr(DAG);
2197     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2198     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2199   }
2200
2201   unsigned MOHiFlag, MOLoFlag;
2202   bool IsPIC = isPositionIndependent();
2203   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2204   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2205   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2206   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2207 }
2208
2209 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2210                                               SelectionDAG &DAG) const {
2211
2212   // FIXME: TLS addresses currently use medium model code sequences,
2213   // which is the most useful form.  Eventually support for small and
2214   // large models could be added if users need it, at the cost of
2215   // additional complexity.
2216   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2217   if (DAG.getTarget().Options.EmulatedTLS)
2218     return LowerToTLSEmulatedModel(GA, DAG);
2219
2220   SDLoc dl(GA);
2221   const GlobalValue *GV = GA->getGlobal();
2222   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2223   bool is64bit = Subtarget.isPPC64();
2224   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2225   PICLevel::Level picLevel = M->getPICLevel();
2226
2227   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2228
2229   if (Model == TLSModel::LocalExec) {
2230     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2231                                                PPCII::MO_TPREL_HA);
2232     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2233                                                PPCII::MO_TPREL_LO);
2234     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2235                                      is64bit ? MVT::i64 : MVT::i32);
2236     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2237     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2238   }
2239
2240   if (Model == TLSModel::InitialExec) {
2241     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2242     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2243                                                 PPCII::MO_TLS);
2244     SDValue GOTPtr;
2245     if (is64bit) {
2246       setUsesTOCBasePtr(DAG);
2247       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2248       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2249                            PtrVT, GOTReg, TGA);
2250     } else
2251       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2252     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2253                                    PtrVT, TGA, GOTPtr);
2254     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2255   }
2256
2257   if (Model == TLSModel::GeneralDynamic) {
2258     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2259     SDValue GOTPtr;
2260     if (is64bit) {
2261       setUsesTOCBasePtr(DAG);
2262       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2263       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2264                                    GOTReg, TGA);
2265     } else {
2266       if (picLevel == PICLevel::SmallPIC)
2267         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2268       else
2269         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2270     }
2271     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2272                        GOTPtr, TGA, TGA);
2273   }
2274
2275   if (Model == TLSModel::LocalDynamic) {
2276     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2277     SDValue GOTPtr;
2278     if (is64bit) {
2279       setUsesTOCBasePtr(DAG);
2280       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2281       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2282                            GOTReg, TGA);
2283     } else {
2284       if (picLevel == PICLevel::SmallPIC)
2285         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2286       else
2287         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2288     }
2289     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2290                                   PtrVT, GOTPtr, TGA, TGA);
2291     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2292                                       PtrVT, TLSAddr, TGA);
2293     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2294   }
2295
2296   llvm_unreachable("Unknown TLS model!");
2297 }
2298
2299 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2300                                               SelectionDAG &DAG) const {
2301   EVT PtrVT = Op.getValueType();
2302   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2303   SDLoc DL(GSDN);
2304   const GlobalValue *GV = GSDN->getGlobal();
2305
2306   // 64-bit SVR4 ABI code is always position-independent.
2307   // The actual address of the GlobalValue is stored in the TOC.
2308   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2309     setUsesTOCBasePtr(DAG);
2310     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2311     return getTOCEntry(DAG, DL, true, GA);
2312   }
2313
2314   unsigned MOHiFlag, MOLoFlag;
2315   bool IsPIC = isPositionIndependent();
2316   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2317
2318   if (IsPIC && Subtarget.isSVR4ABI()) {
2319     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2320                                             GSDN->getOffset(),
2321                                             PPCII::MO_PIC_FLAG);
2322     return getTOCEntry(DAG, DL, false, GA);
2323   }
2324
2325   SDValue GAHi =
2326     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2327   SDValue GALo =
2328     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2329
2330   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2331
2332   // If the global reference is actually to a non-lazy-pointer, we have to do an
2333   // extra load to get the address of the global.
2334   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2335     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2336   return Ptr;
2337 }
2338
2339 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2340   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2341   SDLoc dl(Op);
2342
2343   if (Op.getValueType() == MVT::v2i64) {
2344     // When the operands themselves are v2i64 values, we need to do something
2345     // special because VSX has no underlying comparison operations for these.
2346     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2347       // Equality can be handled by casting to the legal type for Altivec
2348       // comparisons, everything else needs to be expanded.
2349       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2350         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2351                  DAG.getSetCC(dl, MVT::v4i32,
2352                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2353                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2354                    CC));
2355       }
2356
2357       return SDValue();
2358     }
2359
2360     // We handle most of these in the usual way.
2361     return Op;
2362   }
2363
2364   // If we're comparing for equality to zero, expose the fact that this is
2365   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2366   // fold the new nodes.
2367   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2368     if (C->isNullValue() && CC == ISD::SETEQ) {
2369       EVT VT = Op.getOperand(0).getValueType();
2370       SDValue Zext = Op.getOperand(0);
2371       if (VT.bitsLT(MVT::i32)) {
2372         VT = MVT::i32;
2373         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2374       }
2375       unsigned Log2b = Log2_32(VT.getSizeInBits());
2376       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2377       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2378                                 DAG.getConstant(Log2b, dl, MVT::i32));
2379       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2380     }
2381     // Leave comparisons against 0 and -1 alone for now, since they're usually
2382     // optimized.  FIXME: revisit this when we can custom lower all setcc
2383     // optimizations.
2384     if (C->isAllOnesValue() || C->isNullValue())
2385       return SDValue();
2386   }
2387
2388   // If we have an integer seteq/setne, turn it into a compare against zero
2389   // by xor'ing the rhs with the lhs, which is faster than setting a
2390   // condition register, reading it back out, and masking the correct bit.  The
2391   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2392   // the result to other bit-twiddling opportunities.
2393   EVT LHSVT = Op.getOperand(0).getValueType();
2394   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2395     EVT VT = Op.getValueType();
2396     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2397                                 Op.getOperand(1));
2398     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2399   }
2400   return SDValue();
2401 }
2402
2403 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2404   SDNode *Node = Op.getNode();
2405   EVT VT = Node->getValueType(0);
2406   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2407   SDValue InChain = Node->getOperand(0);
2408   SDValue VAListPtr = Node->getOperand(1);
2409   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2410   SDLoc dl(Node);
2411
2412   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2413
2414   // gpr_index
2415   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2416                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2417   InChain = GprIndex.getValue(1);
2418
2419   if (VT == MVT::i64) {
2420     // Check if GprIndex is even
2421     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2422                                  DAG.getConstant(1, dl, MVT::i32));
2423     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2424                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2425     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2426                                           DAG.getConstant(1, dl, MVT::i32));
2427     // Align GprIndex to be even if it isn't
2428     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2429                            GprIndex);
2430   }
2431
2432   // fpr index is 1 byte after gpr
2433   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2434                                DAG.getConstant(1, dl, MVT::i32));
2435
2436   // fpr
2437   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2438                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2439   InChain = FprIndex.getValue(1);
2440
2441   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2442                                        DAG.getConstant(8, dl, MVT::i32));
2443
2444   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2445                                         DAG.getConstant(4, dl, MVT::i32));
2446
2447   // areas
2448   SDValue OverflowArea =
2449       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2450   InChain = OverflowArea.getValue(1);
2451
2452   SDValue RegSaveArea =
2453       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2454   InChain = RegSaveArea.getValue(1);
2455
2456   // select overflow_area if index > 8
2457   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2458                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2459
2460   // adjustment constant gpr_index * 4/8
2461   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2462                                     VT.isInteger() ? GprIndex : FprIndex,
2463                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2464                                                     MVT::i32));
2465
2466   // OurReg = RegSaveArea + RegConstant
2467   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2468                                RegConstant);
2469
2470   // Floating types are 32 bytes into RegSaveArea
2471   if (VT.isFloatingPoint())
2472     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2473                          DAG.getConstant(32, dl, MVT::i32));
2474
2475   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2476   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2477                                    VT.isInteger() ? GprIndex : FprIndex,
2478                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2479                                                    MVT::i32));
2480
2481   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2482                               VT.isInteger() ? VAListPtr : FprPtr,
2483                               MachinePointerInfo(SV), MVT::i8);
2484
2485   // determine if we should load from reg_save_area or overflow_area
2486   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2487
2488   // increase overflow_area by 4/8 if gpr/fpr > 8
2489   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2490                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2491                                           dl, MVT::i32));
2492
2493   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2494                              OverflowAreaPlusN);
2495
2496   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2497                               MachinePointerInfo(), MVT::i32);
2498
2499   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2500 }
2501
2502 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2503   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2504
2505   // We have to copy the entire va_list struct:
2506   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2507   return DAG.getMemcpy(Op.getOperand(0), Op,
2508                        Op.getOperand(1), Op.getOperand(2),
2509                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2510                        false, MachinePointerInfo(), MachinePointerInfo());
2511 }
2512
2513 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2514                                                   SelectionDAG &DAG) const {
2515   return Op.getOperand(0);
2516 }
2517
2518 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2519                                                 SelectionDAG &DAG) const {
2520   SDValue Chain = Op.getOperand(0);
2521   SDValue Trmp = Op.getOperand(1); // trampoline
2522   SDValue FPtr = Op.getOperand(2); // nested function
2523   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2524   SDLoc dl(Op);
2525
2526   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2527   bool isPPC64 = (PtrVT == MVT::i64);
2528   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2529
2530   TargetLowering::ArgListTy Args;
2531   TargetLowering::ArgListEntry Entry;
2532
2533   Entry.Ty = IntPtrTy;
2534   Entry.Node = Trmp; Args.push_back(Entry);
2535
2536   // TrampSize == (isPPC64 ? 48 : 40);
2537   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2538                                isPPC64 ? MVT::i64 : MVT::i32);
2539   Args.push_back(Entry);
2540
2541   Entry.Node = FPtr; Args.push_back(Entry);
2542   Entry.Node = Nest; Args.push_back(Entry);
2543
2544   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2545   TargetLowering::CallLoweringInfo CLI(DAG);
2546   CLI.setDebugLoc(dl).setChain(Chain)
2547     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2548                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2549                std::move(Args));
2550
2551   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2552   return CallResult.second;
2553 }
2554
2555 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2556   MachineFunction &MF = DAG.getMachineFunction();
2557   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2558   EVT PtrVT = getPointerTy(MF.getDataLayout());
2559
2560   SDLoc dl(Op);
2561
2562   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2563     // vastart just stores the address of the VarArgsFrameIndex slot into the
2564     // memory location argument.
2565     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2566     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2567     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2568                         MachinePointerInfo(SV));
2569   }
2570
2571   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2572   // We suppose the given va_list is already allocated.
2573   //
2574   // typedef struct {
2575   //  char gpr;     /* index into the array of 8 GPRs
2576   //                 * stored in the register save area
2577   //                 * gpr=0 corresponds to r3,
2578   //                 * gpr=1 to r4, etc.
2579   //                 */
2580   //  char fpr;     /* index into the array of 8 FPRs
2581   //                 * stored in the register save area
2582   //                 * fpr=0 corresponds to f1,
2583   //                 * fpr=1 to f2, etc.
2584   //                 */
2585   //  char *overflow_arg_area;
2586   //                /* location on stack that holds
2587   //                 * the next overflow argument
2588   //                 */
2589   //  char *reg_save_area;
2590   //               /* where r3:r10 and f1:f8 (if saved)
2591   //                * are stored
2592   //                */
2593   // } va_list[1];
2594
2595   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2596   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2597   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2598                                             PtrVT);
2599   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2600                                  PtrVT);
2601
2602   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2603   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2604
2605   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2606   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2607
2608   uint64_t FPROffset = 1;
2609   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2610
2611   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2612
2613   // Store first byte : number of int regs
2614   SDValue firstStore =
2615       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2616                         MachinePointerInfo(SV), MVT::i8);
2617   uint64_t nextOffset = FPROffset;
2618   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2619                                   ConstFPROffset);
2620
2621   // Store second byte : number of float regs
2622   SDValue secondStore =
2623       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2624                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2625   nextOffset += StackOffset;
2626   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2627
2628   // Store second word : arguments given on stack
2629   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2630                                     MachinePointerInfo(SV, nextOffset));
2631   nextOffset += FrameOffset;
2632   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2633
2634   // Store third word : arguments given in registers
2635   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2636                       MachinePointerInfo(SV, nextOffset));
2637 }
2638
2639 #include "PPCGenCallingConv.inc"
2640
2641 // Function whose sole purpose is to kill compiler warnings
2642 // stemming from unused functions included from PPCGenCallingConv.inc.
2643 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2644   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2645 }
2646
2647 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2648                                       CCValAssign::LocInfo &LocInfo,
2649                                       ISD::ArgFlagsTy &ArgFlags,
2650                                       CCState &State) {
2651   return true;
2652 }
2653
2654 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2655                                              MVT &LocVT,
2656                                              CCValAssign::LocInfo &LocInfo,
2657                                              ISD::ArgFlagsTy &ArgFlags,
2658                                              CCState &State) {
2659   static const MCPhysReg ArgRegs[] = {
2660     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2661     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2662   };
2663   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2664
2665   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2666
2667   // Skip one register if the first unallocated register has an even register
2668   // number and there are still argument registers available which have not been
2669   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2670   // need to skip a register if RegNum is odd.
2671   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2672     State.AllocateReg(ArgRegs[RegNum]);
2673   }
2674
2675   // Always return false here, as this function only makes sure that the first
2676   // unallocated register has an odd register number and does not actually
2677   // allocate a register for the current argument.
2678   return false;
2679 }
2680
2681 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2682                                                MVT &LocVT,
2683                                                CCValAssign::LocInfo &LocInfo,
2684                                                ISD::ArgFlagsTy &ArgFlags,
2685                                                CCState &State) {
2686   static const MCPhysReg ArgRegs[] = {
2687     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2688     PPC::F8
2689   };
2690
2691   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2692
2693   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2694
2695   // If there is only one Floating-point register left we need to put both f64
2696   // values of a split ppc_fp128 value on the stack.
2697   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2698     State.AllocateReg(ArgRegs[RegNum]);
2699   }
2700
2701   // Always return false here, as this function only makes sure that the two f64
2702   // values a ppc_fp128 value is split into are both passed in registers or both
2703   // passed on the stack and does not actually allocate a register for the
2704   // current argument.
2705   return false;
2706 }
2707
2708 /// FPR - The set of FP registers that should be allocated for arguments,
2709 /// on Darwin.
2710 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2711                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2712                                 PPC::F11, PPC::F12, PPC::F13};
2713
2714 /// QFPR - The set of QPX registers that should be allocated for arguments.
2715 static const MCPhysReg QFPR[] = {
2716     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2717     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2718
2719 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2720 /// the stack.
2721 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2722                                        unsigned PtrByteSize) {
2723   unsigned ArgSize = ArgVT.getStoreSize();
2724   if (Flags.isByVal())
2725     ArgSize = Flags.getByValSize();
2726
2727   // Round up to multiples of the pointer size, except for array members,
2728   // which are always packed.
2729   if (!Flags.isInConsecutiveRegs())
2730     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2731
2732   return ArgSize;
2733 }
2734
2735 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2736 /// on the stack.
2737 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2738                                             ISD::ArgFlagsTy Flags,
2739                                             unsigned PtrByteSize) {
2740   unsigned Align = PtrByteSize;
2741
2742   // Altivec parameters are padded to a 16 byte boundary.
2743   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2744       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2745       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2746       ArgVT == MVT::v1i128)
2747     Align = 16;
2748   // QPX vector types stored in double-precision are padded to a 32 byte
2749   // boundary.
2750   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2751     Align = 32;
2752
2753   // ByVal parameters are aligned as requested.
2754   if (Flags.isByVal()) {
2755     unsigned BVAlign = Flags.getByValAlign();
2756     if (BVAlign > PtrByteSize) {
2757       if (BVAlign % PtrByteSize != 0)
2758           llvm_unreachable(
2759             "ByVal alignment is not a multiple of the pointer size");
2760
2761       Align = BVAlign;
2762     }
2763   }
2764
2765   // Array members are always packed to their original alignment.
2766   if (Flags.isInConsecutiveRegs()) {
2767     // If the array member was split into multiple registers, the first
2768     // needs to be aligned to the size of the full type.  (Except for
2769     // ppcf128, which is only aligned as its f64 components.)
2770     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2771       Align = OrigVT.getStoreSize();
2772     else
2773       Align = ArgVT.getStoreSize();
2774   }
2775
2776   return Align;
2777 }
2778
2779 /// CalculateStackSlotUsed - Return whether this argument will use its
2780 /// stack slot (instead of being passed in registers).  ArgOffset,
2781 /// AvailableFPRs, and AvailableVRs must hold the current argument
2782 /// position, and will be updated to account for this argument.
2783 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2784                                    ISD::ArgFlagsTy Flags,
2785                                    unsigned PtrByteSize,
2786                                    unsigned LinkageSize,
2787                                    unsigned ParamAreaSize,
2788                                    unsigned &ArgOffset,
2789                                    unsigned &AvailableFPRs,
2790                                    unsigned &AvailableVRs, bool HasQPX) {
2791   bool UseMemory = false;
2792
2793   // Respect alignment of argument on the stack.
2794   unsigned Align =
2795     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2796   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2797   // If there's no space left in the argument save area, we must
2798   // use memory (this check also catches zero-sized arguments).
2799   if (ArgOffset >= LinkageSize + ParamAreaSize)
2800     UseMemory = true;
2801
2802   // Allocate argument on the stack.
2803   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2804   if (Flags.isInConsecutiveRegsLast())
2805     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2806   // If we overran the argument save area, we must use memory
2807   // (this check catches arguments passed partially in memory)
2808   if (ArgOffset > LinkageSize + ParamAreaSize)
2809     UseMemory = true;
2810
2811   // However, if the argument is actually passed in an FPR or a VR,
2812   // we don't use memory after all.
2813   if (!Flags.isByVal()) {
2814     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2815         // QPX registers overlap with the scalar FP registers.
2816         (HasQPX && (ArgVT == MVT::v4f32 ||
2817                     ArgVT == MVT::v4f64 ||
2818                     ArgVT == MVT::v4i1)))
2819       if (AvailableFPRs > 0) {
2820         --AvailableFPRs;
2821         return false;
2822       }
2823     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2824         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2825         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2826         ArgVT == MVT::v1i128)
2827       if (AvailableVRs > 0) {
2828         --AvailableVRs;
2829         return false;
2830       }
2831   }
2832
2833   return UseMemory;
2834 }
2835
2836 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2837 /// ensure minimum alignment required for target.
2838 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2839                                      unsigned NumBytes) {
2840   unsigned TargetAlign = Lowering->getStackAlignment();
2841   unsigned AlignMask = TargetAlign - 1;
2842   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2843   return NumBytes;
2844 }
2845
2846 SDValue PPCTargetLowering::LowerFormalArguments(
2847     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2848     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2849     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2850   if (Subtarget.isSVR4ABI()) {
2851     if (Subtarget.isPPC64())
2852       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2853                                          dl, DAG, InVals);
2854     else
2855       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2856                                          dl, DAG, InVals);
2857   } else {
2858     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2859                                        dl, DAG, InVals);
2860   }
2861 }
2862
2863 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2864     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2865     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2866     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2867
2868   // 32-bit SVR4 ABI Stack Frame Layout:
2869   //              +-----------------------------------+
2870   //        +-->  |            Back chain             |
2871   //        |     +-----------------------------------+
2872   //        |     | Floating-point register save area |
2873   //        |     +-----------------------------------+
2874   //        |     |    General register save area     |
2875   //        |     +-----------------------------------+
2876   //        |     |          CR save word             |
2877   //        |     +-----------------------------------+
2878   //        |     |         VRSAVE save word          |
2879   //        |     +-----------------------------------+
2880   //        |     |         Alignment padding         |
2881   //        |     +-----------------------------------+
2882   //        |     |     Vector register save area     |
2883   //        |     +-----------------------------------+
2884   //        |     |       Local variable space        |
2885   //        |     +-----------------------------------+
2886   //        |     |        Parameter list area        |
2887   //        |     +-----------------------------------+
2888   //        |     |           LR save word            |
2889   //        |     +-----------------------------------+
2890   // SP-->  +---  |            Back chain             |
2891   //              +-----------------------------------+
2892   //
2893   // Specifications:
2894   //   System V Application Binary Interface PowerPC Processor Supplement
2895   //   AltiVec Technology Programming Interface Manual
2896
2897   MachineFunction &MF = DAG.getMachineFunction();
2898   MachineFrameInfo *MFI = MF.getFrameInfo();
2899   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2900
2901   EVT PtrVT = getPointerTy(MF.getDataLayout());
2902   // Potential tail calls could cause overwriting of argument stack slots.
2903   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2904                        (CallConv == CallingConv::Fast));
2905   unsigned PtrByteSize = 4;
2906
2907   // Assign locations to all of the incoming arguments.
2908   SmallVector<CCValAssign, 16> ArgLocs;
2909   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2910                  *DAG.getContext());
2911
2912   // Reserve space for the linkage area on the stack.
2913   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2914   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2915   if (useSoftFloat())
2916     CCInfo.PreAnalyzeFormalArguments(Ins);
2917
2918   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2919   CCInfo.clearWasPPCF128();
2920
2921   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2922     CCValAssign &VA = ArgLocs[i];
2923
2924     // Arguments stored in registers.
2925     if (VA.isRegLoc()) {
2926       const TargetRegisterClass *RC;
2927       EVT ValVT = VA.getValVT();
2928
2929       switch (ValVT.getSimpleVT().SimpleTy) {
2930         default:
2931           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2932         case MVT::i1:
2933         case MVT::i32:
2934           RC = &PPC::GPRCRegClass;
2935           break;
2936         case MVT::f32:
2937           if (Subtarget.hasP8Vector())
2938             RC = &PPC::VSSRCRegClass;
2939           else
2940             RC = &PPC::F4RCRegClass;
2941           break;
2942         case MVT::f64:
2943           if (Subtarget.hasVSX())
2944             RC = &PPC::VSFRCRegClass;
2945           else
2946             RC = &PPC::F8RCRegClass;
2947           break;
2948         case MVT::v16i8:
2949         case MVT::v8i16:
2950         case MVT::v4i32:
2951           RC = &PPC::VRRCRegClass;
2952           break;
2953         case MVT::v4f32:
2954           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2955           break;
2956         case MVT::v2f64:
2957         case MVT::v2i64:
2958           RC = &PPC::VSHRCRegClass;
2959           break;
2960         case MVT::v4f64:
2961           RC = &PPC::QFRCRegClass;
2962           break;
2963         case MVT::v4i1:
2964           RC = &PPC::QBRCRegClass;
2965           break;
2966       }
2967
2968       // Transform the arguments stored in physical registers into virtual ones.
2969       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2970       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2971                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2972
2973       if (ValVT == MVT::i1)
2974         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2975
2976       InVals.push_back(ArgValue);
2977     } else {
2978       // Argument stored in memory.
2979       assert(VA.isMemLoc());
2980
2981       unsigned ArgSize = VA.getLocVT().getStoreSize();
2982       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2983                                       isImmutable);
2984
2985       // Create load nodes to retrieve arguments from the stack.
2986       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2987       InVals.push_back(
2988           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
2989     }
2990   }
2991
2992   // Assign locations to all of the incoming aggregate by value arguments.
2993   // Aggregates passed by value are stored in the local variable space of the
2994   // caller's stack frame, right above the parameter list area.
2995   SmallVector<CCValAssign, 16> ByValArgLocs;
2996   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2997                       ByValArgLocs, *DAG.getContext());
2998
2999   // Reserve stack space for the allocations in CCInfo.
3000   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3001
3002   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3003
3004   // Area that is at least reserved in the caller of this function.
3005   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3006   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3007
3008   // Set the size that is at least reserved in caller of this function.  Tail
3009   // call optimized function's reserved stack space needs to be aligned so that
3010   // taking the difference between two stack areas will result in an aligned
3011   // stack.
3012   MinReservedArea =
3013       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3014   FuncInfo->setMinReservedArea(MinReservedArea);
3015
3016   SmallVector<SDValue, 8> MemOps;
3017
3018   // If the function takes variable number of arguments, make a frame index for
3019   // the start of the first vararg value... for expansion of llvm.va_start.
3020   if (isVarArg) {
3021     static const MCPhysReg GPArgRegs[] = {
3022       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3023       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3024     };
3025     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3026
3027     static const MCPhysReg FPArgRegs[] = {
3028       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3029       PPC::F8
3030     };
3031     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3032
3033     if (useSoftFloat())
3034        NumFPArgRegs = 0;
3035
3036     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3037     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3038
3039     // Make room for NumGPArgRegs and NumFPArgRegs.
3040     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3041                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3042
3043     FuncInfo->setVarArgsStackOffset(
3044       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3045                              CCInfo.getNextStackOffset(), true));
3046
3047     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
3048     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3049
3050     // The fixed integer arguments of a variadic function are stored to the
3051     // VarArgsFrameIndex on the stack so that they may be loaded by
3052     // dereferencing the result of va_next.
3053     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3054       // Get an existing live-in vreg, or add a new one.
3055       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3056       if (!VReg)
3057         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3058
3059       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3060       SDValue Store =
3061           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3062       MemOps.push_back(Store);
3063       // Increment the address by four for the next argument to store
3064       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3065       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3066     }
3067
3068     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3069     // is set.
3070     // The double arguments are stored to the VarArgsFrameIndex
3071     // on the stack.
3072     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3073       // Get an existing live-in vreg, or add a new one.
3074       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3075       if (!VReg)
3076         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3077
3078       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3079       SDValue Store =
3080           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3081       MemOps.push_back(Store);
3082       // Increment the address by eight for the next argument to store
3083       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3084                                          PtrVT);
3085       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3086     }
3087   }
3088
3089   if (!MemOps.empty())
3090     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3091
3092   return Chain;
3093 }
3094
3095 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3096 // value to MVT::i64 and then truncate to the correct register size.
3097 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3098                                              EVT ObjectVT, SelectionDAG &DAG,
3099                                              SDValue ArgVal,
3100                                              const SDLoc &dl) const {
3101   if (Flags.isSExt())
3102     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3103                          DAG.getValueType(ObjectVT));
3104   else if (Flags.isZExt())
3105     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3106                          DAG.getValueType(ObjectVT));
3107
3108   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3109 }
3110
3111 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3112     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3113     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3114     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3115   // TODO: add description of PPC stack frame format, or at least some docs.
3116   //
3117   bool isELFv2ABI = Subtarget.isELFv2ABI();
3118   bool isLittleEndian = Subtarget.isLittleEndian();
3119   MachineFunction &MF = DAG.getMachineFunction();
3120   MachineFrameInfo *MFI = MF.getFrameInfo();
3121   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3122
3123   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3124          "fastcc not supported on varargs functions");
3125
3126   EVT PtrVT = getPointerTy(MF.getDataLayout());
3127   // Potential tail calls could cause overwriting of argument stack slots.
3128   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3129                        (CallConv == CallingConv::Fast));
3130   unsigned PtrByteSize = 8;
3131   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3132
3133   static const MCPhysReg GPR[] = {
3134     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3135     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3136   };
3137   static const MCPhysReg VR[] = {
3138     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3139     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3140   };
3141   static const MCPhysReg VSRH[] = {
3142     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3143     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3144   };
3145
3146   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3147   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3148   const unsigned Num_VR_Regs  = array_lengthof(VR);
3149   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3150
3151   // Do a first pass over the arguments to determine whether the ABI
3152   // guarantees that our caller has allocated the parameter save area
3153   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3154   // in the ELFv2 ABI, it is true if this is a vararg function or if
3155   // any parameter is located in a stack slot.
3156
3157   bool HasParameterArea = !isELFv2ABI || isVarArg;
3158   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3159   unsigned NumBytes = LinkageSize;
3160   unsigned AvailableFPRs = Num_FPR_Regs;
3161   unsigned AvailableVRs = Num_VR_Regs;
3162   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3163     if (Ins[i].Flags.isNest())
3164       continue;
3165
3166     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3167                                PtrByteSize, LinkageSize, ParamAreaSize,
3168                                NumBytes, AvailableFPRs, AvailableVRs,
3169                                Subtarget.hasQPX()))
3170       HasParameterArea = true;
3171   }
3172
3173   // Add DAG nodes to load the arguments or copy them out of registers.  On
3174   // entry to a function on PPC, the arguments start after the linkage area,
3175   // although the first ones are often in registers.
3176
3177   unsigned ArgOffset = LinkageSize;
3178   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3179   unsigned &QFPR_idx = FPR_idx;
3180   SmallVector<SDValue, 8> MemOps;
3181   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3182   unsigned CurArgIdx = 0;
3183   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3184     SDValue ArgVal;
3185     bool needsLoad = false;
3186     EVT ObjectVT = Ins[ArgNo].VT;
3187     EVT OrigVT = Ins[ArgNo].ArgVT;
3188     unsigned ObjSize = ObjectVT.getStoreSize();
3189     unsigned ArgSize = ObjSize;
3190     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3191     if (Ins[ArgNo].isOrigArg()) {
3192       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3193       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3194     }
3195     // We re-align the argument offset for each argument, except when using the
3196     // fast calling convention, when we need to make sure we do that only when
3197     // we'll actually use a stack slot.
3198     unsigned CurArgOffset, Align;
3199     auto ComputeArgOffset = [&]() {
3200       /* Respect alignment of argument on the stack.  */
3201       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3202       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3203       CurArgOffset = ArgOffset;
3204     };
3205
3206     if (CallConv != CallingConv::Fast) {
3207       ComputeArgOffset();
3208
3209       /* Compute GPR index associated with argument offset.  */
3210       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3211       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3212     }
3213
3214     // FIXME the codegen can be much improved in some cases.
3215     // We do not have to keep everything in memory.
3216     if (Flags.isByVal()) {
3217       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3218
3219       if (CallConv == CallingConv::Fast)
3220         ComputeArgOffset();
3221
3222       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3223       ObjSize = Flags.getByValSize();
3224       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3225       // Empty aggregate parameters do not take up registers.  Examples:
3226       //   struct { } a;
3227       //   union  { } b;
3228       //   int c[0];
3229       // etc.  However, we have to provide a place-holder in InVals, so
3230       // pretend we have an 8-byte item at the current address for that
3231       // purpose.
3232       if (!ObjSize) {
3233         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3234         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3235         InVals.push_back(FIN);
3236         continue;
3237       }
3238
3239       // Create a stack object covering all stack doublewords occupied
3240       // by the argument.  If the argument is (fully or partially) on
3241       // the stack, or if the argument is fully in registers but the
3242       // caller has allocated the parameter save anyway, we can refer
3243       // directly to the caller's stack frame.  Otherwise, create a
3244       // local copy in our own frame.
3245       int FI;
3246       if (HasParameterArea ||
3247           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3248         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3249       else
3250         FI = MFI->CreateStackObject(ArgSize, Align, false);
3251       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3252
3253       // Handle aggregates smaller than 8 bytes.
3254       if (ObjSize < PtrByteSize) {
3255         // The value of the object is its address, which differs from the
3256         // address of the enclosing doubleword on big-endian systems.
3257         SDValue Arg = FIN;
3258         if (!isLittleEndian) {
3259           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3260           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3261         }
3262         InVals.push_back(Arg);
3263
3264         if (GPR_idx != Num_GPR_Regs) {
3265           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3266           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3267           SDValue Store;
3268
3269           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3270             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3271                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3272             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3273                                       MachinePointerInfo(&*FuncArg), ObjType);
3274           } else {
3275             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3276             // store the whole register as-is to the parameter save area
3277             // slot.
3278             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3279                                  MachinePointerInfo(&*FuncArg));
3280           }
3281
3282           MemOps.push_back(Store);
3283         }
3284         // Whether we copied from a register or not, advance the offset
3285         // into the parameter save area by a full doubleword.
3286         ArgOffset += PtrByteSize;
3287         continue;
3288       }
3289
3290       // The value of the object is its address, which is the address of
3291       // its first stack doubleword.
3292       InVals.push_back(FIN);
3293
3294       // Store whatever pieces of the object are in registers to memory.
3295       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3296         if (GPR_idx == Num_GPR_Regs)
3297           break;
3298
3299         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3300         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3301         SDValue Addr = FIN;
3302         if (j) {
3303           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3304           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3305         }
3306         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3307                                      MachinePointerInfo(&*FuncArg, j));
3308         MemOps.push_back(Store);
3309         ++GPR_idx;
3310       }
3311       ArgOffset += ArgSize;
3312       continue;
3313     }
3314
3315     switch (ObjectVT.getSimpleVT().SimpleTy) {
3316     default: llvm_unreachable("Unhandled argument type!");
3317     case MVT::i1:
3318     case MVT::i32:
3319     case MVT::i64:
3320       if (Flags.isNest()) {
3321         // The 'nest' parameter, if any, is passed in R11.
3322         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3323         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3324
3325         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3326           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3327
3328         break;
3329       }
3330
3331       // These can be scalar arguments or elements of an integer array type
3332       // passed directly.  Clang may use those instead of "byval" aggregate
3333       // types to avoid forcing arguments to memory unnecessarily.
3334       if (GPR_idx != Num_GPR_Regs) {
3335         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3336         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3337
3338         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3339           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3340           // value to MVT::i64 and then truncate to the correct register size.
3341           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3342       } else {
3343         if (CallConv == CallingConv::Fast)
3344           ComputeArgOffset();
3345
3346         needsLoad = true;
3347         ArgSize = PtrByteSize;
3348       }
3349       if (CallConv != CallingConv::Fast || needsLoad)
3350         ArgOffset += 8;
3351       break;
3352
3353     case MVT::f32:
3354     case MVT::f64:
3355       // These can be scalar arguments or elements of a float array type
3356       // passed directly.  The latter are used to implement ELFv2 homogenous
3357       // float aggregates.
3358       if (FPR_idx != Num_FPR_Regs) {
3359         unsigned VReg;
3360
3361         if (ObjectVT == MVT::f32)
3362           VReg = MF.addLiveIn(FPR[FPR_idx],
3363                               Subtarget.hasP8Vector()
3364                                   ? &PPC::VSSRCRegClass
3365                                   : &PPC::F4RCRegClass);
3366         else
3367           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3368                                                 ? &PPC::VSFRCRegClass
3369                                                 : &PPC::F8RCRegClass);
3370
3371         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3372         ++FPR_idx;
3373       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3374         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3375         // once we support fp <-> gpr moves.
3376
3377         // This can only ever happen in the presence of f32 array types,
3378         // since otherwise we never run out of FPRs before running out
3379         // of GPRs.
3380         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3381         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3382
3383         if (ObjectVT == MVT::f32) {
3384           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3385             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3386                                  DAG.getConstant(32, dl, MVT::i32));
3387           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3388         }
3389
3390         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3391       } else {
3392         if (CallConv == CallingConv::Fast)
3393           ComputeArgOffset();
3394
3395         needsLoad = true;
3396       }
3397
3398       // When passing an array of floats, the array occupies consecutive
3399       // space in the argument area; only round up to the next doubleword
3400       // at the end of the array.  Otherwise, each float takes 8 bytes.
3401       if (CallConv != CallingConv::Fast || needsLoad) {
3402         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3403         ArgOffset += ArgSize;
3404         if (Flags.isInConsecutiveRegsLast())
3405           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3406       }
3407       break;
3408     case MVT::v4f32:
3409     case MVT::v4i32:
3410     case MVT::v8i16:
3411     case MVT::v16i8:
3412     case MVT::v2f64:
3413     case MVT::v2i64:
3414     case MVT::v1i128:
3415       if (!Subtarget.hasQPX()) {
3416       // These can be scalar arguments or elements of a vector array type
3417       // passed directly.  The latter are used to implement ELFv2 homogenous
3418       // vector aggregates.
3419       if (VR_idx != Num_VR_Regs) {
3420         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3421                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3422                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3423         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3424         ++VR_idx;
3425       } else {
3426         if (CallConv == CallingConv::Fast)
3427           ComputeArgOffset();
3428
3429         needsLoad = true;
3430       }
3431       if (CallConv != CallingConv::Fast || needsLoad)
3432         ArgOffset += 16;
3433       break;
3434       } // not QPX
3435
3436       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3437              "Invalid QPX parameter type");
3438       /* fall through */
3439
3440     case MVT::v4f64:
3441     case MVT::v4i1:
3442       // QPX vectors are treated like their scalar floating-point subregisters
3443       // (except that they're larger).
3444       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3445       if (QFPR_idx != Num_QFPR_Regs) {
3446         const TargetRegisterClass *RC;
3447         switch (ObjectVT.getSimpleVT().SimpleTy) {
3448         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3449         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3450         default:         RC = &PPC::QBRCRegClass; break;
3451         }
3452
3453         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3454         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3455         ++QFPR_idx;
3456       } else {
3457         if (CallConv == CallingConv::Fast)
3458           ComputeArgOffset();
3459         needsLoad = true;
3460       }
3461       if (CallConv != CallingConv::Fast || needsLoad)
3462         ArgOffset += Sz;
3463       break;
3464     }
3465
3466     // We need to load the argument to a virtual register if we determined
3467     // above that we ran out of physical registers of the appropriate type.
3468     if (needsLoad) {
3469       if (ObjSize < ArgSize && !isLittleEndian)
3470         CurArgOffset += ArgSize - ObjSize;
3471       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3472       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3473       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3474     }
3475
3476     InVals.push_back(ArgVal);
3477   }
3478
3479   // Area that is at least reserved in the caller of this function.
3480   unsigned MinReservedArea;
3481   if (HasParameterArea)
3482     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3483   else
3484     MinReservedArea = LinkageSize;
3485
3486   // Set the size that is at least reserved in caller of this function.  Tail
3487   // call optimized functions' reserved stack space needs to be aligned so that
3488   // taking the difference between two stack areas will result in an aligned
3489   // stack.
3490   MinReservedArea =
3491       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3492   FuncInfo->setMinReservedArea(MinReservedArea);
3493
3494   // If the function takes variable number of arguments, make a frame index for
3495   // the start of the first vararg value... for expansion of llvm.va_start.
3496   if (isVarArg) {
3497     int Depth = ArgOffset;
3498
3499     FuncInfo->setVarArgsFrameIndex(
3500       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3501     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3502
3503     // If this function is vararg, store any remaining integer argument regs
3504     // to their spots on the stack so that they may be loaded by dereferencing
3505     // the result of va_next.
3506     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3507          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3508       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3509       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3510       SDValue Store =
3511           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3512       MemOps.push_back(Store);
3513       // Increment the address by four for the next argument to store
3514       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3515       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3516     }
3517   }
3518
3519   if (!MemOps.empty())
3520     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3521
3522   return Chain;
3523 }
3524
3525 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3526     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3527     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3528     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3529   // TODO: add description of PPC stack frame format, or at least some docs.
3530   //
3531   MachineFunction &MF = DAG.getMachineFunction();
3532   MachineFrameInfo *MFI = MF.getFrameInfo();
3533   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3534
3535   EVT PtrVT = getPointerTy(MF.getDataLayout());
3536   bool isPPC64 = PtrVT == MVT::i64;
3537   // Potential tail calls could cause overwriting of argument stack slots.
3538   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3539                        (CallConv == CallingConv::Fast));
3540   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3541   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3542   unsigned ArgOffset = LinkageSize;
3543   // Area that is at least reserved in caller of this function.
3544   unsigned MinReservedArea = ArgOffset;
3545
3546   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3547     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3548     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3549   };
3550   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3551     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3552     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3553   };
3554   static const MCPhysReg VR[] = {
3555     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3556     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3557   };
3558
3559   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3560   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3561   const unsigned Num_VR_Regs  = array_lengthof( VR);
3562
3563   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3564
3565   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3566
3567   // In 32-bit non-varargs functions, the stack space for vectors is after the
3568   // stack space for non-vectors.  We do not use this space unless we have
3569   // too many vectors to fit in registers, something that only occurs in
3570   // constructed examples:), but we have to walk the arglist to figure
3571   // that out...for the pathological case, compute VecArgOffset as the
3572   // start of the vector parameter area.  Computing VecArgOffset is the
3573   // entire point of the following loop.
3574   unsigned VecArgOffset = ArgOffset;
3575   if (!isVarArg && !isPPC64) {
3576     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3577          ++ArgNo) {
3578       EVT ObjectVT = Ins[ArgNo].VT;
3579       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3580
3581       if (Flags.isByVal()) {
3582         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3583         unsigned ObjSize = Flags.getByValSize();
3584         unsigned ArgSize =
3585                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3586         VecArgOffset += ArgSize;
3587         continue;
3588       }
3589
3590       switch(ObjectVT.getSimpleVT().SimpleTy) {
3591       default: llvm_unreachable("Unhandled argument type!");
3592       case MVT::i1:
3593       case MVT::i32:
3594       case MVT::f32:
3595         VecArgOffset += 4;
3596         break;
3597       case MVT::i64:  // PPC64
3598       case MVT::f64:
3599         // FIXME: We are guaranteed to be !isPPC64 at this point.
3600         // Does MVT::i64 apply?
3601         VecArgOffset += 8;
3602         break;
3603       case MVT::v4f32:
3604       case MVT::v4i32:
3605       case MVT::v8i16:
3606       case MVT::v16i8:
3607         // Nothing to do, we're only looking at Nonvector args here.
3608         break;
3609       }
3610     }
3611   }
3612   // We've found where the vector parameter area in memory is.  Skip the
3613   // first 12 parameters; these don't use that memory.
3614   VecArgOffset = ((VecArgOffset+15)/16)*16;
3615   VecArgOffset += 12*16;
3616
3617   // Add DAG nodes to load the arguments or copy them out of registers.  On
3618   // entry to a function on PPC, the arguments start after the linkage area,
3619   // although the first ones are often in registers.
3620
3621   SmallVector<SDValue, 8> MemOps;
3622   unsigned nAltivecParamsAtEnd = 0;
3623   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3624   unsigned CurArgIdx = 0;
3625   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3626     SDValue ArgVal;
3627     bool needsLoad = false;
3628     EVT ObjectVT = Ins[ArgNo].VT;
3629     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3630     unsigned ArgSize = ObjSize;
3631     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3632     if (Ins[ArgNo].isOrigArg()) {
3633       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3634       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3635     }
3636     unsigned CurArgOffset = ArgOffset;
3637
3638     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3639     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3640         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3641       if (isVarArg || isPPC64) {
3642         MinReservedArea = ((MinReservedArea+15)/16)*16;
3643         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3644                                                   Flags,
3645                                                   PtrByteSize);
3646       } else  nAltivecParamsAtEnd++;
3647     } else
3648       // Calculate min reserved area.
3649       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3650                                                 Flags,
3651                                                 PtrByteSize);
3652
3653     // FIXME the codegen can be much improved in some cases.
3654     // We do not have to keep everything in memory.
3655     if (Flags.isByVal()) {
3656       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3657
3658       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3659       ObjSize = Flags.getByValSize();
3660       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3661       // Objects of size 1 and 2 are right justified, everything else is
3662       // left justified.  This means the memory address is adjusted forwards.
3663       if (ObjSize==1 || ObjSize==2) {
3664         CurArgOffset = CurArgOffset + (4 - ObjSize);
3665       }
3666       // The value of the object is its address.
3667       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3668       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3669       InVals.push_back(FIN);
3670       if (ObjSize==1 || ObjSize==2) {
3671         if (GPR_idx != Num_GPR_Regs) {
3672           unsigned VReg;
3673           if (isPPC64)
3674             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3675           else
3676             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3677           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3678           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3679           SDValue Store =
3680               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3681                                 MachinePointerInfo(&*FuncArg), ObjType);
3682           MemOps.push_back(Store);
3683           ++GPR_idx;
3684         }
3685
3686         ArgOffset += PtrByteSize;
3687
3688         continue;
3689       }
3690       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3691         // Store whatever pieces of the object are in registers
3692         // to memory.  ArgOffset will be the address of the beginning
3693         // of the object.
3694         if (GPR_idx != Num_GPR_Regs) {
3695           unsigned VReg;
3696           if (isPPC64)
3697             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3698           else
3699             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3700           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3701           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3702           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3703           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3704                                        MachinePointerInfo(&*FuncArg, j));
3705           MemOps.push_back(Store);
3706           ++GPR_idx;
3707           ArgOffset += PtrByteSize;
3708         } else {
3709           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3710           break;
3711         }
3712       }
3713       continue;
3714     }
3715
3716     switch (ObjectVT.getSimpleVT().SimpleTy) {
3717     default: llvm_unreachable("Unhandled argument type!");
3718     case MVT::i1:
3719     case MVT::i32:
3720       if (!isPPC64) {
3721         if (GPR_idx != Num_GPR_Regs) {
3722           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3723           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3724
3725           if (ObjectVT == MVT::i1)
3726             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3727
3728           ++GPR_idx;
3729         } else {
3730           needsLoad = true;
3731           ArgSize = PtrByteSize;
3732         }
3733         // All int arguments reserve stack space in the Darwin ABI.
3734         ArgOffset += PtrByteSize;
3735         break;
3736       }
3737       // FALLTHROUGH
3738     case MVT::i64:  // PPC64
3739       if (GPR_idx != Num_GPR_Regs) {
3740         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3741         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3742
3743         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3744           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3745           // value to MVT::i64 and then truncate to the correct register size.
3746           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3747
3748         ++GPR_idx;
3749       } else {
3750         needsLoad = true;
3751         ArgSize = PtrByteSize;
3752       }
3753       // All int arguments reserve stack space in the Darwin ABI.
3754       ArgOffset += 8;
3755       break;
3756
3757     case MVT::f32:
3758     case MVT::f64:
3759       // Every 4 bytes of argument space consumes one of the GPRs available for
3760       // argument passing.
3761       if (GPR_idx != Num_GPR_Regs) {
3762         ++GPR_idx;
3763         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3764           ++GPR_idx;
3765       }
3766       if (FPR_idx != Num_FPR_Regs) {
3767         unsigned VReg;
3768
3769         if (ObjectVT == MVT::f32)
3770           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3771         else
3772           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3773
3774         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3775         ++FPR_idx;
3776       } else {
3777         needsLoad = true;
3778       }
3779
3780       // All FP arguments reserve stack space in the Darwin ABI.
3781       ArgOffset += isPPC64 ? 8 : ObjSize;
3782       break;
3783     case MVT::v4f32:
3784     case MVT::v4i32:
3785     case MVT::v8i16:
3786     case MVT::v16i8:
3787       // Note that vector arguments in registers don't reserve stack space,
3788       // except in varargs functions.
3789       if (VR_idx != Num_VR_Regs) {
3790         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3791         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3792         if (isVarArg) {
3793           while ((ArgOffset % 16) != 0) {
3794             ArgOffset += PtrByteSize;
3795             if (GPR_idx != Num_GPR_Regs)
3796               GPR_idx++;
3797           }
3798           ArgOffset += 16;
3799           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3800         }
3801         ++VR_idx;
3802       } else {
3803         if (!isVarArg && !isPPC64) {
3804           // Vectors go after all the nonvectors.
3805           CurArgOffset = VecArgOffset;
3806           VecArgOffset += 16;
3807         } else {
3808           // Vectors are aligned.
3809           ArgOffset = ((ArgOffset+15)/16)*16;
3810           CurArgOffset = ArgOffset;
3811           ArgOffset += 16;
3812         }
3813         needsLoad = true;
3814       }
3815       break;
3816     }
3817
3818     // We need to load the argument to a virtual register if we determined above
3819     // that we ran out of physical registers of the appropriate type.
3820     if (needsLoad) {
3821       int FI = MFI->CreateFixedObject(ObjSize,
3822                                       CurArgOffset + (ArgSize - ObjSize),
3823                                       isImmutable);
3824       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3825       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3826     }
3827
3828     InVals.push_back(ArgVal);
3829   }
3830
3831   // Allow for Altivec parameters at the end, if needed.
3832   if (nAltivecParamsAtEnd) {
3833     MinReservedArea = ((MinReservedArea+15)/16)*16;
3834     MinReservedArea += 16*nAltivecParamsAtEnd;
3835   }
3836
3837   // Area that is at least reserved in the caller of this function.
3838   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3839
3840   // Set the size that is at least reserved in caller of this function.  Tail
3841   // call optimized functions' reserved stack space needs to be aligned so that
3842   // taking the difference between two stack areas will result in an aligned
3843   // stack.
3844   MinReservedArea =
3845       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3846   FuncInfo->setMinReservedArea(MinReservedArea);
3847
3848   // If the function takes variable number of arguments, make a frame index for
3849   // the start of the first vararg value... for expansion of llvm.va_start.
3850   if (isVarArg) {
3851     int Depth = ArgOffset;
3852
3853     FuncInfo->setVarArgsFrameIndex(
3854       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3855                              Depth, true));
3856     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3857
3858     // If this function is vararg, store any remaining integer argument regs
3859     // to their spots on the stack so that they may be loaded by dereferencing
3860     // the result of va_next.
3861     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3862       unsigned VReg;
3863
3864       if (isPPC64)
3865         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3866       else
3867         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3868
3869       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3870       SDValue Store =
3871           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3872       MemOps.push_back(Store);
3873       // Increment the address by four for the next argument to store
3874       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3875       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3876     }
3877   }
3878
3879   if (!MemOps.empty())
3880     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3881
3882   return Chain;
3883 }
3884
3885 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3886 /// adjusted to accommodate the arguments for the tailcall.
3887 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3888                                    unsigned ParamSize) {
3889
3890   if (!isTailCall) return 0;
3891
3892   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3893   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3894   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3895   // Remember only if the new adjustement is bigger.
3896   if (SPDiff < FI->getTailCallSPDelta())
3897     FI->setTailCallSPDelta(SPDiff);
3898
3899   return SPDiff;
3900 }
3901
3902 static bool isFunctionGlobalAddress(SDValue Callee);
3903
3904 static bool
3905 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3906   // If !G, Callee can be an external symbol.
3907   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3908   if (!G) return false;
3909
3910   const GlobalValue *GV = G->getGlobal();
3911
3912   if (GV->isDeclaration()) return false;
3913
3914   switch(GV->getLinkage()) {
3915   default: llvm_unreachable("unknow linkage type");
3916   case GlobalValue::AvailableExternallyLinkage:
3917   case GlobalValue::ExternalWeakLinkage:
3918     return false;
3919
3920   // Callee with weak linkage is allowed if it has hidden or protected
3921   // visibility
3922   case GlobalValue::LinkOnceAnyLinkage:
3923   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3924   case GlobalValue::WeakAnyLinkage:
3925   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3926     if (GV->hasDefaultVisibility())
3927       return false;
3928
3929   case GlobalValue::ExternalLinkage:
3930   case GlobalValue::InternalLinkage:
3931   case GlobalValue::PrivateLinkage:
3932     break;
3933   }
3934
3935   // With '-fPIC', calling default visiblity function need insert 'nop' after
3936   // function call, no matter that function resides in same module or not, so
3937   // we treat it as in different module.
3938   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3939     return false;
3940
3941   return true;
3942 }
3943
3944 static bool
3945 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3946                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3947   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3948
3949   const unsigned PtrByteSize = 8;
3950   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3951
3952   static const MCPhysReg GPR[] = {
3953     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3954     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3955   };
3956   static const MCPhysReg VR[] = {
3957     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3958     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3959   };
3960
3961   const unsigned NumGPRs = array_lengthof(GPR);
3962   const unsigned NumFPRs = 13;
3963   const unsigned NumVRs = array_lengthof(VR);
3964   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3965
3966   unsigned NumBytes = LinkageSize;
3967   unsigned AvailableFPRs = NumFPRs;
3968   unsigned AvailableVRs = NumVRs;
3969
3970   for (const ISD::OutputArg& Param : Outs) {
3971     if (Param.Flags.isNest()) continue;
3972
3973     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3974                                PtrByteSize, LinkageSize, ParamAreaSize,
3975                                NumBytes, AvailableFPRs, AvailableVRs,
3976                                Subtarget.hasQPX()))
3977       return true;
3978   }
3979   return false;
3980 }
3981
3982 static bool
3983 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
3984   if (CS->arg_size() != CallerFn->getArgumentList().size())
3985     return false;
3986
3987   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
3988   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
3989   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
3990
3991   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
3992     const Value* CalleeArg = *CalleeArgIter;
3993     const Value* CallerArg = &(*CallerArgIter);
3994     if (CalleeArg == CallerArg)
3995       continue;
3996
3997     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
3998     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
3999     //      }
4000     // 1st argument of callee is undef and has the same type as caller.
4001     if (CalleeArg->getType() == CallerArg->getType() &&
4002         isa<UndefValue>(CalleeArg))
4003       continue;
4004
4005     return false;
4006   }
4007
4008   return true;
4009 }
4010
4011 bool
4012 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4013                                     SDValue Callee,
4014                                     CallingConv::ID CalleeCC,
4015                                     ImmutableCallSite *CS,
4016                                     bool isVarArg,
4017                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4018                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4019                                     SelectionDAG& DAG) const {
4020   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4021
4022   if (DisableSCO && !TailCallOpt) return false;
4023
4024   // Variadic argument functions are not supported.
4025   if (isVarArg) return false;
4026
4027   MachineFunction &MF = DAG.getMachineFunction();
4028   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4029
4030   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4031   // the same calling convention
4032   if (CallerCC != CalleeCC) return false;
4033
4034   // SCO support C calling convention
4035   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4036     return false;
4037
4038   // Caller contains any byval parameter is not supported.
4039   if (std::any_of(Ins.begin(), Ins.end(),
4040                   [](const ISD::InputArg& IA) { return IA.Flags.isByVal(); }))
4041     return false;
4042
4043   // Callee contains any byval parameter is not supported, too.
4044   // Note: This is a quick work around, because in some cases, e.g.
4045   // caller's stack size > callee's stack size, we are still able to apply
4046   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4047   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4048     return false;
4049
4050   // No TCO/SCO on indirect call because Caller have to restore its TOC
4051   if (!isFunctionGlobalAddress(Callee) &&
4052       !isa<ExternalSymbolSDNode>(Callee))
4053     return false;
4054
4055   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
4056   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4057   // module.
4058   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4059   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
4060     return false;
4061
4062   // TCO allows altering callee ABI, so we don't have to check further.
4063   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4064     return true;
4065
4066   if (DisableSCO) return false;
4067
4068   // If callee use the same argument list that caller is using, then we can
4069   // apply SCO on this case. If it is not, then we need to check if callee needs
4070   // stack for passing arguments.
4071   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4072       needStackSlotPassParameters(Subtarget, Outs)) {
4073     return false;
4074   }
4075
4076   return true;
4077 }
4078
4079 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4080 /// for tail call optimization. Targets which want to do tail call
4081 /// optimization should implement this function.
4082 bool
4083 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4084                                                      CallingConv::ID CalleeCC,
4085                                                      bool isVarArg,
4086                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4087                                                      SelectionDAG& DAG) const {
4088   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4089     return false;
4090
4091   // Variable argument functions are not supported.
4092   if (isVarArg)
4093     return false;
4094
4095   MachineFunction &MF = DAG.getMachineFunction();
4096   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4097   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4098     // Functions containing by val parameters are not supported.
4099     for (unsigned i = 0; i != Ins.size(); i++) {
4100        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4101        if (Flags.isByVal()) return false;
4102     }
4103
4104     // Non-PIC/GOT tail calls are supported.
4105     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4106       return true;
4107
4108     // At the moment we can only do local tail calls (in same module, hidden
4109     // or protected) if we are generating PIC.
4110     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4111       return G->getGlobal()->hasHiddenVisibility()
4112           || G->getGlobal()->hasProtectedVisibility();
4113   }
4114
4115   return false;
4116 }
4117
4118 /// isCallCompatibleAddress - Return the immediate to use if the specified
4119 /// 32-bit value is representable in the immediate field of a BxA instruction.
4120 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4121   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4122   if (!C) return nullptr;
4123
4124   int Addr = C->getZExtValue();
4125   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4126       SignExtend32<26>(Addr) != Addr)
4127     return nullptr;  // Top 6 bits have to be sext of immediate.
4128
4129   return DAG
4130       .getConstant(
4131           (int)C->getZExtValue() >> 2, SDLoc(Op),
4132           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4133       .getNode();
4134 }
4135
4136 namespace {
4137
4138 struct TailCallArgumentInfo {
4139   SDValue Arg;
4140   SDValue FrameIdxOp;
4141   int       FrameIdx;
4142
4143   TailCallArgumentInfo() : FrameIdx(0) {}
4144 };
4145 }
4146
4147 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4148 static void StoreTailCallArgumentsToStackSlot(
4149     SelectionDAG &DAG, SDValue Chain,
4150     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4151     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4152   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4153     SDValue Arg = TailCallArgs[i].Arg;
4154     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4155     int FI = TailCallArgs[i].FrameIdx;
4156     // Store relative to framepointer.
4157     MemOpChains.push_back(DAG.getStore(
4158         Chain, dl, Arg, FIN,
4159         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4160   }
4161 }
4162
4163 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4164 /// the appropriate stack slot for the tail call optimized function call.
4165 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4166                                              SDValue OldRetAddr, SDValue OldFP,
4167                                              int SPDiff, const SDLoc &dl) {
4168   if (SPDiff) {
4169     // Calculate the new stack slot for the return address.
4170     MachineFunction &MF = DAG.getMachineFunction();
4171     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4172     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4173     bool isPPC64 = Subtarget.isPPC64();
4174     int SlotSize = isPPC64 ? 8 : 4;
4175     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4176     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
4177                                                           NewRetAddrLoc, true);
4178     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4179     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4180     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4181                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4182
4183     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4184     // slot as the FP is never overwritten.
4185     if (Subtarget.isDarwinABI()) {
4186       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4187       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
4188                                                           true);
4189       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4190       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4191                            MachinePointerInfo::getFixedStack(
4192                                DAG.getMachineFunction(), NewFPIdx));
4193     }
4194   }
4195   return Chain;
4196 }
4197
4198 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4199 /// the position of the argument.
4200 static void
4201 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4202                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4203                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4204   int Offset = ArgOffset + SPDiff;
4205   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
4206   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
4207   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4208   SDValue FIN = DAG.getFrameIndex(FI, VT);
4209   TailCallArgumentInfo Info;
4210   Info.Arg = Arg;
4211   Info.FrameIdxOp = FIN;
4212   Info.FrameIdx = FI;
4213   TailCallArguments.push_back(Info);
4214 }
4215
4216 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4217 /// stack slot. Returns the chain as result and the loaded frame pointers in
4218 /// LROpOut/FPOpout. Used when tail calling.
4219 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4220     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4221     SDValue &FPOpOut, const SDLoc &dl) const {
4222   if (SPDiff) {
4223     // Load the LR and FP stack slot for later adjusting.
4224     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4225     LROpOut = getReturnAddrFrameIndex(DAG);
4226     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4227     Chain = SDValue(LROpOut.getNode(), 1);
4228
4229     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4230     // slot as the FP is never overwritten.
4231     if (Subtarget.isDarwinABI()) {
4232       FPOpOut = getFramePointerFrameIndex(DAG);
4233       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4234       Chain = SDValue(FPOpOut.getNode(), 1);
4235     }
4236   }
4237   return Chain;
4238 }
4239
4240 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4241 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4242 /// specified by the specific parameter attribute. The copy will be passed as
4243 /// a byval function parameter.
4244 /// Sometimes what we are copying is the end of a larger object, the part that
4245 /// does not fit in registers.
4246 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4247                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4248                                          SelectionDAG &DAG, const SDLoc &dl) {
4249   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4250   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4251                        false, false, false, MachinePointerInfo(),
4252                        MachinePointerInfo());
4253 }
4254
4255 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4256 /// tail calls.
4257 static void LowerMemOpCallTo(
4258     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4259     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4260     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4261     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4262   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4263   if (!isTailCall) {
4264     if (isVector) {
4265       SDValue StackPtr;
4266       if (isPPC64)
4267         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4268       else
4269         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4270       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4271                            DAG.getConstant(ArgOffset, dl, PtrVT));
4272     }
4273     MemOpChains.push_back(
4274         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4275     // Calculate and remember argument location.
4276   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4277                                   TailCallArguments);
4278 }
4279
4280 static void
4281 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4282                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4283                 SDValue FPOp,
4284                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4285   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4286   // might overwrite each other in case of tail call optimization.
4287   SmallVector<SDValue, 8> MemOpChains2;
4288   // Do not flag preceding copytoreg stuff together with the following stuff.
4289   InFlag = SDValue();
4290   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4291                                     MemOpChains2, dl);
4292   if (!MemOpChains2.empty())
4293     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4294
4295   // Store the return address to the appropriate stack slot.
4296   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4297
4298   // Emit callseq_end just before tailcall node.
4299   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4300                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4301   InFlag = Chain.getValue(1);
4302 }
4303
4304 // Is this global address that of a function that can be called by name? (as
4305 // opposed to something that must hold a descriptor for an indirect call).
4306 static bool isFunctionGlobalAddress(SDValue Callee) {
4307   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4308     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4309         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4310       return false;
4311
4312     return G->getGlobal()->getValueType()->isFunctionTy();
4313   }
4314
4315   return false;
4316 }
4317
4318 static unsigned
4319 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4320             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4321             bool isPatchPoint, bool hasNest,
4322             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4323             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4324             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4325
4326   bool isPPC64 = Subtarget.isPPC64();
4327   bool isSVR4ABI = Subtarget.isSVR4ABI();
4328   bool isELFv2ABI = Subtarget.isELFv2ABI();
4329
4330   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4331   NodeTys.push_back(MVT::Other);   // Returns a chain
4332   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4333
4334   unsigned CallOpc = PPCISD::CALL;
4335
4336   bool needIndirectCall = true;
4337   if (!isSVR4ABI || !isPPC64)
4338     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4339       // If this is an absolute destination address, use the munged value.
4340       Callee = SDValue(Dest, 0);
4341       needIndirectCall = false;
4342     }
4343
4344   // PC-relative references to external symbols should go through $stub, unless
4345   // we're building with the leopard linker or later, which automatically
4346   // synthesizes these stubs.
4347   const TargetMachine &TM = DAG.getTarget();
4348   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4349   const GlobalValue *GV = nullptr;
4350   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4351     GV = G->getGlobal();
4352   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4353   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4354
4355   if (isFunctionGlobalAddress(Callee)) {
4356     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4357     // A call to a TLS address is actually an indirect call to a
4358     // thread-specific pointer.
4359     unsigned OpFlags = 0;
4360     if (UsePlt)
4361       OpFlags = PPCII::MO_PLT;
4362
4363     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4364     // every direct call is) turn it into a TargetGlobalAddress /
4365     // TargetExternalSymbol node so that legalize doesn't hack it.
4366     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4367                                         Callee.getValueType(), 0, OpFlags);
4368     needIndirectCall = false;
4369   }
4370
4371   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4372     unsigned char OpFlags = 0;
4373
4374     if (UsePlt)
4375       OpFlags = PPCII::MO_PLT;
4376
4377     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4378                                          OpFlags);
4379     needIndirectCall = false;
4380   }
4381
4382   if (isPatchPoint) {
4383     // We'll form an invalid direct call when lowering a patchpoint; the full
4384     // sequence for an indirect call is complicated, and many of the
4385     // instructions introduced might have side effects (and, thus, can't be
4386     // removed later). The call itself will be removed as soon as the
4387     // argument/return lowering is complete, so the fact that it has the wrong
4388     // kind of operands should not really matter.
4389     needIndirectCall = false;
4390   }
4391
4392   if (needIndirectCall) {
4393     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4394     // to do the call, we can't use PPCISD::CALL.
4395     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4396
4397     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4398       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4399       // entry point, but to the function descriptor (the function entry point
4400       // address is part of the function descriptor though).
4401       // The function descriptor is a three doubleword structure with the
4402       // following fields: function entry point, TOC base address and
4403       // environment pointer.
4404       // Thus for a call through a function pointer, the following actions need
4405       // to be performed:
4406       //   1. Save the TOC of the caller in the TOC save area of its stack
4407       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4408       //   2. Load the address of the function entry point from the function
4409       //      descriptor.
4410       //   3. Load the TOC of the callee from the function descriptor into r2.
4411       //   4. Load the environment pointer from the function descriptor into
4412       //      r11.
4413       //   5. Branch to the function entry point address.
4414       //   6. On return of the callee, the TOC of the caller needs to be
4415       //      restored (this is done in FinishCall()).
4416       //
4417       // The loads are scheduled at the beginning of the call sequence, and the
4418       // register copies are flagged together to ensure that no other
4419       // operations can be scheduled in between. E.g. without flagging the
4420       // copies together, a TOC access in the caller could be scheduled between
4421       // the assignment of the callee TOC and the branch to the callee, which
4422       // results in the TOC access going through the TOC of the callee instead
4423       // of going through the TOC of the caller, which leads to incorrect code.
4424
4425       // Load the address of the function entry point from the function
4426       // descriptor.
4427       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4428       if (LDChain.getValueType() == MVT::Glue)
4429         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4430
4431       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4432                           ? MachineMemOperand::MOInvariant
4433                           : MachineMemOperand::MONone;
4434
4435       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4436       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4437                                         /* Alignment = */ 8, MMOFlags);
4438
4439       // Load environment pointer into r11.
4440       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4441       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4442       SDValue LoadEnvPtr =
4443           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4444                       /* Alignment = */ 8, MMOFlags);
4445
4446       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4447       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4448       SDValue TOCPtr =
4449           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4450                       /* Alignment = */ 8, MMOFlags);
4451
4452       setUsesTOCBasePtr(DAG);
4453       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4454                                         InFlag);
4455       Chain = TOCVal.getValue(0);
4456       InFlag = TOCVal.getValue(1);
4457
4458       // If the function call has an explicit 'nest' parameter, it takes the
4459       // place of the environment pointer.
4460       if (!hasNest) {
4461         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4462                                           InFlag);
4463
4464         Chain = EnvVal.getValue(0);
4465         InFlag = EnvVal.getValue(1);
4466       }
4467
4468       MTCTROps[0] = Chain;
4469       MTCTROps[1] = LoadFuncPtr;
4470       MTCTROps[2] = InFlag;
4471     }
4472
4473     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4474                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4475     InFlag = Chain.getValue(1);
4476
4477     NodeTys.clear();
4478     NodeTys.push_back(MVT::Other);
4479     NodeTys.push_back(MVT::Glue);
4480     Ops.push_back(Chain);
4481     CallOpc = PPCISD::BCTRL;
4482     Callee.setNode(nullptr);
4483     // Add use of X11 (holding environment pointer)
4484     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4485       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4486     // Add CTR register as callee so a bctr can be emitted later.
4487     if (isTailCall)
4488       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4489   }
4490
4491   // If this is a direct call, pass the chain and the callee.
4492   if (Callee.getNode()) {
4493     Ops.push_back(Chain);
4494     Ops.push_back(Callee);
4495   }
4496   // If this is a tail call add stack pointer delta.
4497   if (isTailCall)
4498     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4499
4500   // Add argument registers to the end of the list so that they are known live
4501   // into the call.
4502   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4503     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4504                                   RegsToPass[i].second.getValueType()));
4505
4506   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4507   // into the call.
4508   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4509     setUsesTOCBasePtr(DAG);
4510     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4511   }
4512
4513   return CallOpc;
4514 }
4515
4516 static
4517 bool isLocalCall(const SDValue &Callee)
4518 {
4519   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4520     return G->getGlobal()->isStrongDefinitionForLinker();
4521   return false;
4522 }
4523
4524 SDValue PPCTargetLowering::LowerCallResult(
4525     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4526     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4527     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4528
4529   SmallVector<CCValAssign, 16> RVLocs;
4530   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4531                     *DAG.getContext());
4532   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4533
4534   // Copy all of the result registers out of their specified physreg.
4535   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4536     CCValAssign &VA = RVLocs[i];
4537     assert(VA.isRegLoc() && "Can only return in registers!");
4538
4539     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4540                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4541     Chain = Val.getValue(1);
4542     InFlag = Val.getValue(2);
4543
4544     switch (VA.getLocInfo()) {
4545     default: llvm_unreachable("Unknown loc info!");
4546     case CCValAssign::Full: break;
4547     case CCValAssign::AExt:
4548       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4549       break;
4550     case CCValAssign::ZExt:
4551       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4552                         DAG.getValueType(VA.getValVT()));
4553       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4554       break;
4555     case CCValAssign::SExt:
4556       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4557                         DAG.getValueType(VA.getValVT()));
4558       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4559       break;
4560     }
4561
4562     InVals.push_back(Val);
4563   }
4564
4565   return Chain;
4566 }
4567
4568 SDValue PPCTargetLowering::FinishCall(
4569     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4570     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4571     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4572     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4573     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4574     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4575
4576   std::vector<EVT> NodeTys;
4577   SmallVector<SDValue, 8> Ops;
4578   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4579                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4580                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4581
4582   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4583   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4584     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4585
4586   // When performing tail call optimization the callee pops its arguments off
4587   // the stack. Account for this here so these bytes can be pushed back on in
4588   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4589   int BytesCalleePops =
4590     (CallConv == CallingConv::Fast &&
4591      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4592
4593   // Add a register mask operand representing the call-preserved registers.
4594   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4595   const uint32_t *Mask =
4596       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4597   assert(Mask && "Missing call preserved mask for calling convention");
4598   Ops.push_back(DAG.getRegisterMask(Mask));
4599
4600   if (InFlag.getNode())
4601     Ops.push_back(InFlag);
4602
4603   // Emit tail call.
4604   if (isTailCall) {
4605     assert(((Callee.getOpcode() == ISD::Register &&
4606              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4607             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4608             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4609             isa<ConstantSDNode>(Callee)) &&
4610     "Expecting an global address, external symbol, absolute value or register");
4611
4612     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4613     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4614   }
4615
4616   // Add a NOP immediately after the branch instruction when using the 64-bit
4617   // SVR4 ABI. At link time, if caller and callee are in a different module and
4618   // thus have a different TOC, the call will be replaced with a call to a stub
4619   // function which saves the current TOC, loads the TOC of the callee and
4620   // branches to the callee. The NOP will be replaced with a load instruction
4621   // which restores the TOC of the caller from the TOC save slot of the current
4622   // stack frame. If caller and callee belong to the same module (and have the
4623   // same TOC), the NOP will remain unchanged.
4624
4625   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4626       !isPatchPoint) {
4627     if (CallOpc == PPCISD::BCTRL) {
4628       // This is a call through a function pointer.
4629       // Restore the caller TOC from the save area into R2.
4630       // See PrepareCall() for more information about calls through function
4631       // pointers in the 64-bit SVR4 ABI.
4632       // We are using a target-specific load with r2 hard coded, because the
4633       // result of a target-independent load would never go directly into r2,
4634       // since r2 is a reserved register (which prevents the register allocator
4635       // from allocating it), resulting in an additional register being
4636       // allocated and an unnecessary move instruction being generated.
4637       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4638
4639       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4640       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4641       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4642       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4643       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4644
4645       // The address needs to go after the chain input but before the flag (or
4646       // any other variadic arguments).
4647       Ops.insert(std::next(Ops.begin()), AddTOC);
4648     } else if ((CallOpc == PPCISD::CALL) &&
4649                (!isLocalCall(Callee) ||
4650                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4651       // Otherwise insert NOP for non-local calls.
4652       CallOpc = PPCISD::CALL_NOP;
4653   }
4654
4655   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4656   InFlag = Chain.getValue(1);
4657
4658   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4659                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4660                              InFlag, dl);
4661   if (!Ins.empty())
4662     InFlag = Chain.getValue(1);
4663
4664   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4665                          Ins, dl, DAG, InVals);
4666 }
4667
4668 SDValue
4669 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4670                              SmallVectorImpl<SDValue> &InVals) const {
4671   SelectionDAG &DAG                     = CLI.DAG;
4672   SDLoc &dl                             = CLI.DL;
4673   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4674   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4675   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4676   SDValue Chain                         = CLI.Chain;
4677   SDValue Callee                        = CLI.Callee;
4678   bool &isTailCall                      = CLI.IsTailCall;
4679   CallingConv::ID CallConv              = CLI.CallConv;
4680   bool isVarArg                         = CLI.IsVarArg;
4681   bool isPatchPoint                     = CLI.IsPatchPoint;
4682   ImmutableCallSite *CS                 = CLI.CS;
4683
4684   if (isTailCall) {
4685     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4686       isTailCall = false;
4687     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4688       isTailCall =
4689         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4690                                                  isVarArg, Outs, Ins, DAG);
4691     else
4692       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4693                                                      Ins, DAG);
4694     if (isTailCall) {
4695       ++NumTailCalls;
4696       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4697         ++NumSiblingCalls;
4698
4699       assert(isa<GlobalAddressSDNode>(Callee) &&
4700              "Callee should be an llvm::Function object.");
4701       DEBUG(
4702         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4703         const unsigned Width = 80 - strlen("TCO caller: ")
4704                                   - strlen(", callee linkage: 0, 0");
4705         dbgs() << "TCO caller: "
4706                << left_justify(DAG.getMachineFunction().getName(), Width)
4707                << ", callee linkage: "
4708                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4709       );
4710     }
4711   }
4712
4713   if (!isTailCall && CS && CS->isMustTailCall())
4714     report_fatal_error("failed to perform tail call elimination on a call "
4715                        "site marked musttail");
4716
4717   // When long calls (i.e. indirect calls) are always used, calls are always
4718   // made via function pointer. If we have a function name, first translate it
4719   // into a pointer.
4720   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4721       !isTailCall)
4722     Callee = LowerGlobalAddress(Callee, DAG);
4723
4724   if (Subtarget.isSVR4ABI()) {
4725     if (Subtarget.isPPC64())
4726       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4727                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4728                               dl, DAG, InVals, CS);
4729     else
4730       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4731                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4732                               dl, DAG, InVals, CS);
4733   }
4734
4735   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4736                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4737                           dl, DAG, InVals, CS);
4738 }
4739
4740 SDValue PPCTargetLowering::LowerCall_32SVR4(
4741     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4742     bool isTailCall, bool isPatchPoint,
4743     const SmallVectorImpl<ISD::OutputArg> &Outs,
4744     const SmallVectorImpl<SDValue> &OutVals,
4745     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4746     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4747     ImmutableCallSite *CS) const {
4748   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4749   // of the 32-bit SVR4 ABI stack frame layout.
4750
4751   assert((CallConv == CallingConv::C ||
4752           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4753
4754   unsigned PtrByteSize = 4;
4755
4756   MachineFunction &MF = DAG.getMachineFunction();
4757
4758   // Mark this function as potentially containing a function that contains a
4759   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4760   // and restoring the callers stack pointer in this functions epilog. This is
4761   // done because by tail calling the called function might overwrite the value
4762   // in this function's (MF) stack pointer stack slot 0(SP).
4763   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4764       CallConv == CallingConv::Fast)
4765     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4766
4767   // Count how many bytes are to be pushed on the stack, including the linkage
4768   // area, parameter list area and the part of the local variable space which
4769   // contains copies of aggregates which are passed by value.
4770
4771   // Assign locations to all of the outgoing arguments.
4772   SmallVector<CCValAssign, 16> ArgLocs;
4773   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4774
4775   // Reserve space for the linkage area on the stack.
4776   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4777                        PtrByteSize);
4778   if (useSoftFloat())
4779     CCInfo.PreAnalyzeCallOperands(Outs);
4780
4781   if (isVarArg) {
4782     // Handle fixed and variable vector arguments differently.
4783     // Fixed vector arguments go into registers as long as registers are
4784     // available. Variable vector arguments always go into memory.
4785     unsigned NumArgs = Outs.size();
4786
4787     for (unsigned i = 0; i != NumArgs; ++i) {
4788       MVT ArgVT = Outs[i].VT;
4789       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4790       bool Result;
4791
4792       if (Outs[i].IsFixed) {
4793         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4794                                CCInfo);
4795       } else {
4796         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4797                                       ArgFlags, CCInfo);
4798       }
4799
4800       if (Result) {
4801 #ifndef NDEBUG
4802         errs() << "Call operand #" << i << " has unhandled type "
4803              << EVT(ArgVT).getEVTString() << "\n";
4804 #endif
4805         llvm_unreachable(nullptr);
4806       }
4807     }
4808   } else {
4809     // All arguments are treated the same.
4810     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4811   }
4812   CCInfo.clearWasPPCF128();
4813
4814   // Assign locations to all of the outgoing aggregate by value arguments.
4815   SmallVector<CCValAssign, 16> ByValArgLocs;
4816   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4817
4818   // Reserve stack space for the allocations in CCInfo.
4819   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4820
4821   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4822
4823   // Size of the linkage area, parameter list area and the part of the local
4824   // space variable where copies of aggregates which are passed by value are
4825   // stored.
4826   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4827
4828   // Calculate by how many bytes the stack has to be adjusted in case of tail
4829   // call optimization.
4830   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4831
4832   // Adjust the stack pointer for the new arguments...
4833   // These operations are automatically eliminated by the prolog/epilog pass
4834   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4835                                dl);
4836   SDValue CallSeqStart = Chain;
4837
4838   // Load the return address and frame pointer so it can be moved somewhere else
4839   // later.
4840   SDValue LROp, FPOp;
4841   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4842
4843   // Set up a copy of the stack pointer for use loading and storing any
4844   // arguments that may not fit in the registers available for argument
4845   // passing.
4846   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4847
4848   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4849   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4850   SmallVector<SDValue, 8> MemOpChains;
4851
4852   bool seenFloatArg = false;
4853   // Walk the register/memloc assignments, inserting copies/loads.
4854   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4855        i != e;
4856        ++i) {
4857     CCValAssign &VA = ArgLocs[i];
4858     SDValue Arg = OutVals[i];
4859     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4860
4861     if (Flags.isByVal()) {
4862       // Argument is an aggregate which is passed by value, thus we need to
4863       // create a copy of it in the local variable space of the current stack
4864       // frame (which is the stack frame of the caller) and pass the address of
4865       // this copy to the callee.
4866       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4867       CCValAssign &ByValVA = ByValArgLocs[j++];
4868       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4869
4870       // Memory reserved in the local variable space of the callers stack frame.
4871       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4872
4873       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4874       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4875                            StackPtr, PtrOff);
4876
4877       // Create a copy of the argument in the local area of the current
4878       // stack frame.
4879       SDValue MemcpyCall =
4880         CreateCopyOfByValArgument(Arg, PtrOff,
4881                                   CallSeqStart.getNode()->getOperand(0),
4882                                   Flags, DAG, dl);
4883
4884       // This must go outside the CALLSEQ_START..END.
4885       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4886                            CallSeqStart.getNode()->getOperand(1),
4887                            SDLoc(MemcpyCall));
4888       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4889                              NewCallSeqStart.getNode());
4890       Chain = CallSeqStart = NewCallSeqStart;
4891
4892       // Pass the address of the aggregate copy on the stack either in a
4893       // physical register or in the parameter list area of the current stack
4894       // frame to the callee.
4895       Arg = PtrOff;
4896     }
4897
4898     if (VA.isRegLoc()) {
4899       if (Arg.getValueType() == MVT::i1)
4900         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4901
4902       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4903       // Put argument in a physical register.
4904       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4905     } else {
4906       // Put argument in the parameter list area of the current stack frame.
4907       assert(VA.isMemLoc());
4908       unsigned LocMemOffset = VA.getLocMemOffset();
4909
4910       if (!isTailCall) {
4911         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4912         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4913                              StackPtr, PtrOff);
4914
4915         MemOpChains.push_back(
4916             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4917       } else {
4918         // Calculate and remember argument location.
4919         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4920                                  TailCallArguments);
4921       }
4922     }
4923   }
4924
4925   if (!MemOpChains.empty())
4926     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4927
4928   // Build a sequence of copy-to-reg nodes chained together with token chain
4929   // and flag operands which copy the outgoing args into the appropriate regs.
4930   SDValue InFlag;
4931   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4932     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4933                              RegsToPass[i].second, InFlag);
4934     InFlag = Chain.getValue(1);
4935   }
4936
4937   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4938   // registers.
4939   if (isVarArg) {
4940     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4941     SDValue Ops[] = { Chain, InFlag };
4942
4943     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4944                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4945
4946     InFlag = Chain.getValue(1);
4947   }
4948
4949   if (isTailCall)
4950     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
4951                     TailCallArguments);
4952
4953   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
4954                     /* unused except on PPC64 ELFv1 */ false, DAG,
4955                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4956                     NumBytes, Ins, InVals, CS);
4957 }
4958
4959 // Copy an argument into memory, being careful to do this outside the
4960 // call sequence for the call to which the argument belongs.
4961 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
4962     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
4963     SelectionDAG &DAG, const SDLoc &dl) const {
4964   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4965                         CallSeqStart.getNode()->getOperand(0),
4966                         Flags, DAG, dl);
4967   // The MEMCPY must go outside the CALLSEQ_START..END.
4968   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4969                              CallSeqStart.getNode()->getOperand(1),
4970                              SDLoc(MemcpyCall));
4971   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4972                          NewCallSeqStart.getNode());
4973   return NewCallSeqStart;
4974 }
4975
4976 SDValue PPCTargetLowering::LowerCall_64SVR4(
4977     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4978     bool isTailCall, bool isPatchPoint,
4979     const SmallVectorImpl<ISD::OutputArg> &Outs,
4980     const SmallVectorImpl<SDValue> &OutVals,
4981     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4982     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4983     ImmutableCallSite *CS) const {
4984
4985   bool isELFv2ABI = Subtarget.isELFv2ABI();
4986   bool isLittleEndian = Subtarget.isLittleEndian();
4987   unsigned NumOps = Outs.size();
4988   bool hasNest = false;
4989   bool IsSibCall = false;
4990
4991   EVT PtrVT = getPointerTy(DAG.getDataLayout());
4992   unsigned PtrByteSize = 8;
4993
4994   MachineFunction &MF = DAG.getMachineFunction();
4995
4996   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
4997     IsSibCall = true;
4998
4999   // Mark this function as potentially containing a function that contains a
5000   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5001   // and restoring the callers stack pointer in this functions epilog. This is
5002   // done because by tail calling the called function might overwrite the value
5003   // in this function's (MF) stack pointer stack slot 0(SP).
5004   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5005       CallConv == CallingConv::Fast)
5006     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5007
5008   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5009          "fastcc not supported on varargs functions");
5010
5011   // Count how many bytes are to be pushed on the stack, including the linkage
5012   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5013   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5014   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5015   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5016   unsigned NumBytes = LinkageSize;
5017   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5018   unsigned &QFPR_idx = FPR_idx;
5019
5020   static const MCPhysReg GPR[] = {
5021     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5022     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5023   };
5024   static const MCPhysReg VR[] = {
5025     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5026     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5027   };
5028   static const MCPhysReg VSRH[] = {
5029     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
5030     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
5031   };
5032
5033   const unsigned NumGPRs = array_lengthof(GPR);
5034   const unsigned NumFPRs = 13;
5035   const unsigned NumVRs  = array_lengthof(VR);
5036   const unsigned NumQFPRs = NumFPRs;
5037
5038   // When using the fast calling convention, we don't provide backing for
5039   // arguments that will be in registers.
5040   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5041
5042   // Add up all the space actually used.
5043   for (unsigned i = 0; i != NumOps; ++i) {
5044     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5045     EVT ArgVT = Outs[i].VT;
5046     EVT OrigVT = Outs[i].ArgVT;
5047
5048     if (Flags.isNest())
5049       continue;
5050
5051     if (CallConv == CallingConv::Fast) {
5052       if (Flags.isByVal())
5053         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5054       else
5055         switch (ArgVT.getSimpleVT().SimpleTy) {
5056         default: llvm_unreachable("Unexpected ValueType for argument!");
5057         case MVT::i1:
5058         case MVT::i32:
5059         case MVT::i64:
5060           if (++NumGPRsUsed <= NumGPRs)
5061             continue;
5062           break;
5063         case MVT::v4i32:
5064         case MVT::v8i16:
5065         case MVT::v16i8:
5066         case MVT::v2f64:
5067         case MVT::v2i64:
5068         case MVT::v1i128:
5069           if (++NumVRsUsed <= NumVRs)
5070             continue;
5071           break;
5072         case MVT::v4f32:
5073           // When using QPX, this is handled like a FP register, otherwise, it
5074           // is an Altivec register.
5075           if (Subtarget.hasQPX()) {
5076             if (++NumFPRsUsed <= NumFPRs)
5077               continue;
5078           } else {
5079             if (++NumVRsUsed <= NumVRs)
5080               continue;
5081           }
5082           break;
5083         case MVT::f32:
5084         case MVT::f64:
5085         case MVT::v4f64: // QPX
5086         case MVT::v4i1:  // QPX
5087           if (++NumFPRsUsed <= NumFPRs)
5088             continue;
5089           break;
5090         }
5091     }
5092
5093     /* Respect alignment of argument on the stack.  */
5094     unsigned Align =
5095       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5096     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5097
5098     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5099     if (Flags.isInConsecutiveRegsLast())
5100       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5101   }
5102
5103   unsigned NumBytesActuallyUsed = NumBytes;
5104
5105   // The prolog code of the callee may store up to 8 GPR argument registers to
5106   // the stack, allowing va_start to index over them in memory if its varargs.
5107   // Because we cannot tell if this is needed on the caller side, we have to
5108   // conservatively assume that it is needed.  As such, make sure we have at
5109   // least enough stack space for the caller to store the 8 GPRs.
5110   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5111   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5112
5113   // Tail call needs the stack to be aligned.
5114   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5115       CallConv == CallingConv::Fast)
5116     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5117
5118   int SPDiff = 0;
5119
5120   // Calculate by how many bytes the stack has to be adjusted in case of tail
5121   // call optimization.
5122   if (!IsSibCall)
5123     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5124
5125   // To protect arguments on the stack from being clobbered in a tail call,
5126   // force all the loads to happen before doing any other lowering.
5127   if (isTailCall)
5128     Chain = DAG.getStackArgumentTokenFactor(Chain);
5129
5130   // Adjust the stack pointer for the new arguments...
5131   // These operations are automatically eliminated by the prolog/epilog pass
5132   if (!IsSibCall)
5133     Chain = DAG.getCALLSEQ_START(Chain,
5134                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5135   SDValue CallSeqStart = Chain;
5136
5137   // Load the return address and frame pointer so it can be move somewhere else
5138   // later.
5139   SDValue LROp, FPOp;
5140   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5141
5142   // Set up a copy of the stack pointer for use loading and storing any
5143   // arguments that may not fit in the registers available for argument
5144   // passing.
5145   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5146
5147   // Figure out which arguments are going to go in registers, and which in
5148   // memory.  Also, if this is a vararg function, floating point operations
5149   // must be stored to our stack, and loaded into integer regs as well, if
5150   // any integer regs are available for argument passing.
5151   unsigned ArgOffset = LinkageSize;
5152
5153   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5154   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5155
5156   SmallVector<SDValue, 8> MemOpChains;
5157   for (unsigned i = 0; i != NumOps; ++i) {
5158     SDValue Arg = OutVals[i];
5159     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5160     EVT ArgVT = Outs[i].VT;
5161     EVT OrigVT = Outs[i].ArgVT;
5162
5163     // PtrOff will be used to store the current argument to the stack if a
5164     // register cannot be found for it.
5165     SDValue PtrOff;
5166
5167     // We re-align the argument offset for each argument, except when using the
5168     // fast calling convention, when we need to make sure we do that only when
5169     // we'll actually use a stack slot.
5170     auto ComputePtrOff = [&]() {
5171       /* Respect alignment of argument on the stack.  */
5172       unsigned Align =
5173         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5174       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5175
5176       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5177
5178       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5179     };
5180
5181     if (CallConv != CallingConv::Fast) {
5182       ComputePtrOff();
5183
5184       /* Compute GPR index associated with argument offset.  */
5185       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5186       GPR_idx = std::min(GPR_idx, NumGPRs);
5187     }
5188
5189     // Promote integers to 64-bit values.
5190     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5191       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5192       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5193       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5194     }
5195
5196     // FIXME memcpy is used way more than necessary.  Correctness first.
5197     // Note: "by value" is code for passing a structure by value, not
5198     // basic types.
5199     if (Flags.isByVal()) {
5200       // Note: Size includes alignment padding, so
5201       //   struct x { short a; char b; }
5202       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5203       // These are the proper values we need for right-justifying the
5204       // aggregate in a parameter register.
5205       unsigned Size = Flags.getByValSize();
5206
5207       // An empty aggregate parameter takes up no storage and no
5208       // registers.
5209       if (Size == 0)
5210         continue;
5211
5212       if (CallConv == CallingConv::Fast)
5213         ComputePtrOff();
5214
5215       // All aggregates smaller than 8 bytes must be passed right-justified.
5216       if (Size==1 || Size==2 || Size==4) {
5217         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5218         if (GPR_idx != NumGPRs) {
5219           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5220                                         MachinePointerInfo(), VT);
5221           MemOpChains.push_back(Load.getValue(1));
5222           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5223
5224           ArgOffset += PtrByteSize;
5225           continue;
5226         }
5227       }
5228
5229       if (GPR_idx == NumGPRs && Size < 8) {
5230         SDValue AddPtr = PtrOff;
5231         if (!isLittleEndian) {
5232           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5233                                           PtrOff.getValueType());
5234           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5235         }
5236         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5237                                                           CallSeqStart,
5238                                                           Flags, DAG, dl);
5239         ArgOffset += PtrByteSize;
5240         continue;
5241       }
5242       // Copy entire object into memory.  There are cases where gcc-generated
5243       // code assumes it is there, even if it could be put entirely into
5244       // registers.  (This is not what the doc says.)
5245
5246       // FIXME: The above statement is likely due to a misunderstanding of the
5247       // documents.  All arguments must be copied into the parameter area BY
5248       // THE CALLEE in the event that the callee takes the address of any
5249       // formal argument.  That has not yet been implemented.  However, it is
5250       // reasonable to use the stack area as a staging area for the register
5251       // load.
5252
5253       // Skip this for small aggregates, as we will use the same slot for a
5254       // right-justified copy, below.
5255       if (Size >= 8)
5256         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5257                                                           CallSeqStart,
5258                                                           Flags, DAG, dl);
5259
5260       // When a register is available, pass a small aggregate right-justified.
5261       if (Size < 8 && GPR_idx != NumGPRs) {
5262         // The easiest way to get this right-justified in a register
5263         // is to copy the structure into the rightmost portion of a
5264         // local variable slot, then load the whole slot into the
5265         // register.
5266         // FIXME: The memcpy seems to produce pretty awful code for
5267         // small aggregates, particularly for packed ones.
5268         // FIXME: It would be preferable to use the slot in the
5269         // parameter save area instead of a new local variable.
5270         SDValue AddPtr = PtrOff;
5271         if (!isLittleEndian) {
5272           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5273           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5274         }
5275         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5276                                                           CallSeqStart,
5277                                                           Flags, DAG, dl);
5278
5279         // Load the slot into the register.
5280         SDValue Load =
5281             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5282         MemOpChains.push_back(Load.getValue(1));
5283         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5284
5285         // Done with this argument.
5286         ArgOffset += PtrByteSize;
5287         continue;
5288       }
5289
5290       // For aggregates larger than PtrByteSize, copy the pieces of the
5291       // object that fit into registers from the parameter save area.
5292       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5293         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5294         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5295         if (GPR_idx != NumGPRs) {
5296           SDValue Load =
5297               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5298           MemOpChains.push_back(Load.getValue(1));
5299           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5300           ArgOffset += PtrByteSize;
5301         } else {
5302           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5303           break;
5304         }
5305       }
5306       continue;
5307     }
5308
5309     switch (Arg.getSimpleValueType().SimpleTy) {
5310     default: llvm_unreachable("Unexpected ValueType for argument!");
5311     case MVT::i1:
5312     case MVT::i32:
5313     case MVT::i64:
5314       if (Flags.isNest()) {
5315         // The 'nest' parameter, if any, is passed in R11.
5316         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5317         hasNest = true;
5318         break;
5319       }
5320
5321       // These can be scalar arguments or elements of an integer array type
5322       // passed directly.  Clang may use those instead of "byval" aggregate
5323       // types to avoid forcing arguments to memory unnecessarily.
5324       if (GPR_idx != NumGPRs) {
5325         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5326       } else {
5327         if (CallConv == CallingConv::Fast)
5328           ComputePtrOff();
5329
5330         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5331                          true, isTailCall, false, MemOpChains,
5332                          TailCallArguments, dl);
5333         if (CallConv == CallingConv::Fast)
5334           ArgOffset += PtrByteSize;
5335       }
5336       if (CallConv != CallingConv::Fast)
5337         ArgOffset += PtrByteSize;
5338       break;
5339     case MVT::f32:
5340     case MVT::f64: {
5341       // These can be scalar arguments or elements of a float array type
5342       // passed directly.  The latter are used to implement ELFv2 homogenous
5343       // float aggregates.
5344
5345       // Named arguments go into FPRs first, and once they overflow, the
5346       // remaining arguments go into GPRs and then the parameter save area.
5347       // Unnamed arguments for vararg functions always go to GPRs and
5348       // then the parameter save area.  For now, put all arguments to vararg
5349       // routines always in both locations (FPR *and* GPR or stack slot).
5350       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5351       bool NeededLoad = false;
5352
5353       // First load the argument into the next available FPR.
5354       if (FPR_idx != NumFPRs)
5355         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5356
5357       // Next, load the argument into GPR or stack slot if needed.
5358       if (!NeedGPROrStack)
5359         ;
5360       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5361         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5362         // once we support fp <-> gpr moves.
5363
5364         // In the non-vararg case, this can only ever happen in the
5365         // presence of f32 array types, since otherwise we never run
5366         // out of FPRs before running out of GPRs.
5367         SDValue ArgVal;
5368
5369         // Double values are always passed in a single GPR.
5370         if (Arg.getValueType() != MVT::f32) {
5371           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5372
5373         // Non-array float values are extended and passed in a GPR.
5374         } else if (!Flags.isInConsecutiveRegs()) {
5375           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5376           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5377
5378         // If we have an array of floats, we collect every odd element
5379         // together with its predecessor into one GPR.
5380         } else if (ArgOffset % PtrByteSize != 0) {
5381           SDValue Lo, Hi;
5382           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5383           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5384           if (!isLittleEndian)
5385             std::swap(Lo, Hi);
5386           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5387
5388         // The final element, if even, goes into the first half of a GPR.
5389         } else if (Flags.isInConsecutiveRegsLast()) {
5390           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5391           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5392           if (!isLittleEndian)
5393             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5394                                  DAG.getConstant(32, dl, MVT::i32));
5395
5396         // Non-final even elements are skipped; they will be handled
5397         // together the with subsequent argument on the next go-around.
5398         } else
5399           ArgVal = SDValue();
5400
5401         if (ArgVal.getNode())
5402           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5403       } else {
5404         if (CallConv == CallingConv::Fast)
5405           ComputePtrOff();
5406
5407         // Single-precision floating-point values are mapped to the
5408         // second (rightmost) word of the stack doubleword.
5409         if (Arg.getValueType() == MVT::f32 &&
5410             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5411           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5412           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5413         }
5414
5415         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5416                          true, isTailCall, false, MemOpChains,
5417                          TailCallArguments, dl);
5418
5419         NeededLoad = true;
5420       }
5421       // When passing an array of floats, the array occupies consecutive
5422       // space in the argument area; only round up to the next doubleword
5423       // at the end of the array.  Otherwise, each float takes 8 bytes.
5424       if (CallConv != CallingConv::Fast || NeededLoad) {
5425         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5426                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5427         if (Flags.isInConsecutiveRegsLast())
5428           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5429       }
5430       break;
5431     }
5432     case MVT::v4f32:
5433     case MVT::v4i32:
5434     case MVT::v8i16:
5435     case MVT::v16i8:
5436     case MVT::v2f64:
5437     case MVT::v2i64:
5438     case MVT::v1i128:
5439       if (!Subtarget.hasQPX()) {
5440       // These can be scalar arguments or elements of a vector array type
5441       // passed directly.  The latter are used to implement ELFv2 homogenous
5442       // vector aggregates.
5443
5444       // For a varargs call, named arguments go into VRs or on the stack as
5445       // usual; unnamed arguments always go to the stack or the corresponding
5446       // GPRs when within range.  For now, we always put the value in both
5447       // locations (or even all three).
5448       if (isVarArg) {
5449         // We could elide this store in the case where the object fits
5450         // entirely in R registers.  Maybe later.
5451         SDValue Store =
5452             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5453         MemOpChains.push_back(Store);
5454         if (VR_idx != NumVRs) {
5455           SDValue Load =
5456               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5457           MemOpChains.push_back(Load.getValue(1));
5458
5459           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5460                            Arg.getSimpleValueType() == MVT::v2i64) ?
5461                           VSRH[VR_idx] : VR[VR_idx];
5462           ++VR_idx;
5463
5464           RegsToPass.push_back(std::make_pair(VReg, Load));
5465         }
5466         ArgOffset += 16;
5467         for (unsigned i=0; i<16; i+=PtrByteSize) {
5468           if (GPR_idx == NumGPRs)
5469             break;
5470           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5471                                    DAG.getConstant(i, dl, PtrVT));
5472           SDValue Load =
5473               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5474           MemOpChains.push_back(Load.getValue(1));
5475           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5476         }
5477         break;
5478       }
5479
5480       // Non-varargs Altivec params go into VRs or on the stack.
5481       if (VR_idx != NumVRs) {
5482         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5483                          Arg.getSimpleValueType() == MVT::v2i64) ?
5484                         VSRH[VR_idx] : VR[VR_idx];
5485         ++VR_idx;
5486
5487         RegsToPass.push_back(std::make_pair(VReg, Arg));
5488       } else {
5489         if (CallConv == CallingConv::Fast)
5490           ComputePtrOff();
5491
5492         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5493                          true, isTailCall, true, MemOpChains,
5494                          TailCallArguments, dl);
5495         if (CallConv == CallingConv::Fast)
5496           ArgOffset += 16;
5497       }
5498
5499       if (CallConv != CallingConv::Fast)
5500         ArgOffset += 16;
5501       break;
5502       } // not QPX
5503
5504       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5505              "Invalid QPX parameter type");
5506
5507       /* fall through */
5508     case MVT::v4f64:
5509     case MVT::v4i1: {
5510       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5511       if (isVarArg) {
5512         // We could elide this store in the case where the object fits
5513         // entirely in R registers.  Maybe later.
5514         SDValue Store =
5515             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5516         MemOpChains.push_back(Store);
5517         if (QFPR_idx != NumQFPRs) {
5518           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5519                                      PtrOff, MachinePointerInfo());
5520           MemOpChains.push_back(Load.getValue(1));
5521           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5522         }
5523         ArgOffset += (IsF32 ? 16 : 32);
5524         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5525           if (GPR_idx == NumGPRs)
5526             break;
5527           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5528                                    DAG.getConstant(i, dl, PtrVT));
5529           SDValue Load =
5530               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5531           MemOpChains.push_back(Load.getValue(1));
5532           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5533         }
5534         break;
5535       }
5536
5537       // Non-varargs QPX params go into registers or on the stack.
5538       if (QFPR_idx != NumQFPRs) {
5539         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5540       } else {
5541         if (CallConv == CallingConv::Fast)
5542           ComputePtrOff();
5543
5544         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5545                          true, isTailCall, true, MemOpChains,
5546                          TailCallArguments, dl);
5547         if (CallConv == CallingConv::Fast)
5548           ArgOffset += (IsF32 ? 16 : 32);
5549       }
5550
5551       if (CallConv != CallingConv::Fast)
5552         ArgOffset += (IsF32 ? 16 : 32);
5553       break;
5554       }
5555     }
5556   }
5557
5558   assert(NumBytesActuallyUsed == ArgOffset);
5559   (void)NumBytesActuallyUsed;
5560
5561   if (!MemOpChains.empty())
5562     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5563
5564   // Check if this is an indirect call (MTCTR/BCTRL).
5565   // See PrepareCall() for more information about calls through function
5566   // pointers in the 64-bit SVR4 ABI.
5567   if (!isTailCall && !isPatchPoint &&
5568       !isFunctionGlobalAddress(Callee) &&
5569       !isa<ExternalSymbolSDNode>(Callee)) {
5570     // Load r2 into a virtual register and store it to the TOC save area.
5571     setUsesTOCBasePtr(DAG);
5572     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5573     // TOC save area offset.
5574     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5575     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5576     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5577     Chain = DAG.getStore(
5578         Val.getValue(1), dl, Val, AddPtr,
5579         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5580     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5581     // This does not mean the MTCTR instruction must use R12; it's easier
5582     // to model this as an extra parameter, so do that.
5583     if (isELFv2ABI && !isPatchPoint)
5584       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5585   }
5586
5587   // Build a sequence of copy-to-reg nodes chained together with token chain
5588   // and flag operands which copy the outgoing args into the appropriate regs.
5589   SDValue InFlag;
5590   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5591     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5592                              RegsToPass[i].second, InFlag);
5593     InFlag = Chain.getValue(1);
5594   }
5595
5596   if (isTailCall && !IsSibCall)
5597     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5598                     TailCallArguments);
5599
5600   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5601                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5602                     SPDiff, NumBytes, Ins, InVals, CS);
5603 }
5604
5605 SDValue PPCTargetLowering::LowerCall_Darwin(
5606     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5607     bool isTailCall, bool isPatchPoint,
5608     const SmallVectorImpl<ISD::OutputArg> &Outs,
5609     const SmallVectorImpl<SDValue> &OutVals,
5610     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5611     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5612     ImmutableCallSite *CS) const {
5613
5614   unsigned NumOps = Outs.size();
5615
5616   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5617   bool isPPC64 = PtrVT == MVT::i64;
5618   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5619
5620   MachineFunction &MF = DAG.getMachineFunction();
5621
5622   // Mark this function as potentially containing a function that contains a
5623   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5624   // and restoring the callers stack pointer in this functions epilog. This is
5625   // done because by tail calling the called function might overwrite the value
5626   // in this function's (MF) stack pointer stack slot 0(SP).
5627   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5628       CallConv == CallingConv::Fast)
5629     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5630
5631   // Count how many bytes are to be pushed on the stack, including the linkage
5632   // area, and parameter passing area.  We start with 24/48 bytes, which is
5633   // prereserved space for [SP][CR][LR][3 x unused].
5634   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5635   unsigned NumBytes = LinkageSize;
5636
5637   // Add up all the space actually used.
5638   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5639   // they all go in registers, but we must reserve stack space for them for
5640   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5641   // assigned stack space in order, with padding so Altivec parameters are
5642   // 16-byte aligned.
5643   unsigned nAltivecParamsAtEnd = 0;
5644   for (unsigned i = 0; i != NumOps; ++i) {
5645     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5646     EVT ArgVT = Outs[i].VT;
5647     // Varargs Altivec parameters are padded to a 16 byte boundary.
5648     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5649         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5650         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5651       if (!isVarArg && !isPPC64) {
5652         // Non-varargs Altivec parameters go after all the non-Altivec
5653         // parameters; handle those later so we know how much padding we need.
5654         nAltivecParamsAtEnd++;
5655         continue;
5656       }
5657       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5658       NumBytes = ((NumBytes+15)/16)*16;
5659     }
5660     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5661   }
5662
5663   // Allow for Altivec parameters at the end, if needed.
5664   if (nAltivecParamsAtEnd) {
5665     NumBytes = ((NumBytes+15)/16)*16;
5666     NumBytes += 16*nAltivecParamsAtEnd;
5667   }
5668
5669   // The prolog code of the callee may store up to 8 GPR argument registers to
5670   // the stack, allowing va_start to index over them in memory if its varargs.
5671   // Because we cannot tell if this is needed on the caller side, we have to
5672   // conservatively assume that it is needed.  As such, make sure we have at
5673   // least enough stack space for the caller to store the 8 GPRs.
5674   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5675
5676   // Tail call needs the stack to be aligned.
5677   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5678       CallConv == CallingConv::Fast)
5679     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5680
5681   // Calculate by how many bytes the stack has to be adjusted in case of tail
5682   // call optimization.
5683   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5684
5685   // To protect arguments on the stack from being clobbered in a tail call,
5686   // force all the loads to happen before doing any other lowering.
5687   if (isTailCall)
5688     Chain = DAG.getStackArgumentTokenFactor(Chain);
5689
5690   // Adjust the stack pointer for the new arguments...
5691   // These operations are automatically eliminated by the prolog/epilog pass
5692   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5693                                dl);
5694   SDValue CallSeqStart = Chain;
5695
5696   // Load the return address and frame pointer so it can be move somewhere else
5697   // later.
5698   SDValue LROp, FPOp;
5699   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5700
5701   // Set up a copy of the stack pointer for use loading and storing any
5702   // arguments that may not fit in the registers available for argument
5703   // passing.
5704   SDValue StackPtr;
5705   if (isPPC64)
5706     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5707   else
5708     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5709
5710   // Figure out which arguments are going to go in registers, and which in
5711   // memory.  Also, if this is a vararg function, floating point operations
5712   // must be stored to our stack, and loaded into integer regs as well, if
5713   // any integer regs are available for argument passing.
5714   unsigned ArgOffset = LinkageSize;
5715   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5716
5717   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5718     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5719     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5720   };
5721   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5722     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5723     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5724   };
5725   static const MCPhysReg VR[] = {
5726     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5727     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5728   };
5729   const unsigned NumGPRs = array_lengthof(GPR_32);
5730   const unsigned NumFPRs = 13;
5731   const unsigned NumVRs  = array_lengthof(VR);
5732
5733   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5734
5735   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5736   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5737
5738   SmallVector<SDValue, 8> MemOpChains;
5739   for (unsigned i = 0; i != NumOps; ++i) {
5740     SDValue Arg = OutVals[i];
5741     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5742
5743     // PtrOff will be used to store the current argument to the stack if a
5744     // register cannot be found for it.
5745     SDValue PtrOff;
5746
5747     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5748
5749     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5750
5751     // On PPC64, promote integers to 64-bit values.
5752     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5753       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5754       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5755       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5756     }
5757
5758     // FIXME memcpy is used way more than necessary.  Correctness first.
5759     // Note: "by value" is code for passing a structure by value, not
5760     // basic types.
5761     if (Flags.isByVal()) {
5762       unsigned Size = Flags.getByValSize();
5763       // Very small objects are passed right-justified.  Everything else is
5764       // passed left-justified.
5765       if (Size==1 || Size==2) {
5766         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5767         if (GPR_idx != NumGPRs) {
5768           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5769                                         MachinePointerInfo(), VT);
5770           MemOpChains.push_back(Load.getValue(1));
5771           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5772
5773           ArgOffset += PtrByteSize;
5774         } else {
5775           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5776                                           PtrOff.getValueType());
5777           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5778           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5779                                                             CallSeqStart,
5780                                                             Flags, DAG, dl);
5781           ArgOffset += PtrByteSize;
5782         }
5783         continue;
5784       }
5785       // Copy entire object into memory.  There are cases where gcc-generated
5786       // code assumes it is there, even if it could be put entirely into
5787       // registers.  (This is not what the doc says.)
5788       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5789                                                         CallSeqStart,
5790                                                         Flags, DAG, dl);
5791
5792       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5793       // copy the pieces of the object that fit into registers from the
5794       // parameter save area.
5795       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5796         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5797         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5798         if (GPR_idx != NumGPRs) {
5799           SDValue Load =
5800               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5801           MemOpChains.push_back(Load.getValue(1));
5802           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5803           ArgOffset += PtrByteSize;
5804         } else {
5805           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5806           break;
5807         }
5808       }
5809       continue;
5810     }
5811
5812     switch (Arg.getSimpleValueType().SimpleTy) {
5813     default: llvm_unreachable("Unexpected ValueType for argument!");
5814     case MVT::i1:
5815     case MVT::i32:
5816     case MVT::i64:
5817       if (GPR_idx != NumGPRs) {
5818         if (Arg.getValueType() == MVT::i1)
5819           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5820
5821         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5822       } else {
5823         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5824                          isPPC64, isTailCall, false, MemOpChains,
5825                          TailCallArguments, dl);
5826       }
5827       ArgOffset += PtrByteSize;
5828       break;
5829     case MVT::f32:
5830     case MVT::f64:
5831       if (FPR_idx != NumFPRs) {
5832         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5833
5834         if (isVarArg) {
5835           SDValue Store =
5836               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5837           MemOpChains.push_back(Store);
5838
5839           // Float varargs are always shadowed in available integer registers
5840           if (GPR_idx != NumGPRs) {
5841             SDValue Load =
5842                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5843             MemOpChains.push_back(Load.getValue(1));
5844             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5845           }
5846           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5847             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5848             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5849             SDValue Load =
5850                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5851             MemOpChains.push_back(Load.getValue(1));
5852             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5853           }
5854         } else {
5855           // If we have any FPRs remaining, we may also have GPRs remaining.
5856           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5857           // GPRs.
5858           if (GPR_idx != NumGPRs)
5859             ++GPR_idx;
5860           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5861               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5862             ++GPR_idx;
5863         }
5864       } else
5865         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5866                          isPPC64, isTailCall, false, MemOpChains,
5867                          TailCallArguments, dl);
5868       if (isPPC64)
5869         ArgOffset += 8;
5870       else
5871         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5872       break;
5873     case MVT::v4f32:
5874     case MVT::v4i32:
5875     case MVT::v8i16:
5876     case MVT::v16i8:
5877       if (isVarArg) {
5878         // These go aligned on the stack, or in the corresponding R registers
5879         // when within range.  The Darwin PPC ABI doc claims they also go in
5880         // V registers; in fact gcc does this only for arguments that are
5881         // prototyped, not for those that match the ...  We do it for all
5882         // arguments, seems to work.
5883         while (ArgOffset % 16 !=0) {
5884           ArgOffset += PtrByteSize;
5885           if (GPR_idx != NumGPRs)
5886             GPR_idx++;
5887         }
5888         // We could elide this store in the case where the object fits
5889         // entirely in R registers.  Maybe later.
5890         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5891                              DAG.getConstant(ArgOffset, dl, PtrVT));
5892         SDValue Store =
5893             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5894         MemOpChains.push_back(Store);
5895         if (VR_idx != NumVRs) {
5896           SDValue Load =
5897               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5898           MemOpChains.push_back(Load.getValue(1));
5899           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5900         }
5901         ArgOffset += 16;
5902         for (unsigned i=0; i<16; i+=PtrByteSize) {
5903           if (GPR_idx == NumGPRs)
5904             break;
5905           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5906                                    DAG.getConstant(i, dl, PtrVT));
5907           SDValue Load =
5908               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5909           MemOpChains.push_back(Load.getValue(1));
5910           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5911         }
5912         break;
5913       }
5914
5915       // Non-varargs Altivec params generally go in registers, but have
5916       // stack space allocated at the end.
5917       if (VR_idx != NumVRs) {
5918         // Doesn't have GPR space allocated.
5919         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5920       } else if (nAltivecParamsAtEnd==0) {
5921         // We are emitting Altivec params in order.
5922         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5923                          isPPC64, isTailCall, true, MemOpChains,
5924                          TailCallArguments, dl);
5925         ArgOffset += 16;
5926       }
5927       break;
5928     }
5929   }
5930   // If all Altivec parameters fit in registers, as they usually do,
5931   // they get stack space following the non-Altivec parameters.  We
5932   // don't track this here because nobody below needs it.
5933   // If there are more Altivec parameters than fit in registers emit
5934   // the stores here.
5935   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5936     unsigned j = 0;
5937     // Offset is aligned; skip 1st 12 params which go in V registers.
5938     ArgOffset = ((ArgOffset+15)/16)*16;
5939     ArgOffset += 12*16;
5940     for (unsigned i = 0; i != NumOps; ++i) {
5941       SDValue Arg = OutVals[i];
5942       EVT ArgType = Outs[i].VT;
5943       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5944           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5945         if (++j > NumVRs) {
5946           SDValue PtrOff;
5947           // We are emitting Altivec params in order.
5948           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5949                            isPPC64, isTailCall, true, MemOpChains,
5950                            TailCallArguments, dl);
5951           ArgOffset += 16;
5952         }
5953       }
5954     }
5955   }
5956
5957   if (!MemOpChains.empty())
5958     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5959
5960   // On Darwin, R12 must contain the address of an indirect callee.  This does
5961   // not mean the MTCTR instruction must use R12; it's easier to model this as
5962   // an extra parameter, so do that.
5963   if (!isTailCall &&
5964       !isFunctionGlobalAddress(Callee) &&
5965       !isa<ExternalSymbolSDNode>(Callee) &&
5966       !isBLACompatibleAddress(Callee, DAG))
5967     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5968                                                    PPC::R12), Callee));
5969
5970   // Build a sequence of copy-to-reg nodes chained together with token chain
5971   // and flag operands which copy the outgoing args into the appropriate regs.
5972   SDValue InFlag;
5973   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5974     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5975                              RegsToPass[i].second, InFlag);
5976     InFlag = Chain.getValue(1);
5977   }
5978
5979   if (isTailCall)
5980     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5981                     TailCallArguments);
5982
5983   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5984                     /* unused except on PPC64 ELFv1 */ false, DAG,
5985                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5986                     NumBytes, Ins, InVals, CS);
5987 }
5988
5989 bool
5990 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5991                                   MachineFunction &MF, bool isVarArg,
5992                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5993                                   LLVMContext &Context) const {
5994   SmallVector<CCValAssign, 16> RVLocs;
5995   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5996   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5997 }
5998
5999 SDValue
6000 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6001                                bool isVarArg,
6002                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6003                                const SmallVectorImpl<SDValue> &OutVals,
6004                                const SDLoc &dl, SelectionDAG &DAG) const {
6005
6006   SmallVector<CCValAssign, 16> RVLocs;
6007   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6008                  *DAG.getContext());
6009   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6010
6011   SDValue Flag;
6012   SmallVector<SDValue, 4> RetOps(1, Chain);
6013
6014   // Copy the result values into the output registers.
6015   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6016     CCValAssign &VA = RVLocs[i];
6017     assert(VA.isRegLoc() && "Can only return in registers!");
6018
6019     SDValue Arg = OutVals[i];
6020
6021     switch (VA.getLocInfo()) {
6022     default: llvm_unreachable("Unknown loc info!");
6023     case CCValAssign::Full: break;
6024     case CCValAssign::AExt:
6025       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6026       break;
6027     case CCValAssign::ZExt:
6028       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6029       break;
6030     case CCValAssign::SExt:
6031       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6032       break;
6033     }
6034
6035     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6036     Flag = Chain.getValue(1);
6037     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6038   }
6039
6040   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6041   const MCPhysReg *I =
6042     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6043   if (I) {
6044     for (; *I; ++I) {
6045
6046       if (PPC::G8RCRegClass.contains(*I))
6047         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6048       else if (PPC::F8RCRegClass.contains(*I))
6049         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6050       else if (PPC::CRRCRegClass.contains(*I))
6051         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6052       else if (PPC::VRRCRegClass.contains(*I))
6053         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6054       else
6055         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6056     }
6057   }
6058
6059   RetOps[0] = Chain;  // Update chain.
6060
6061   // Add the flag if we have it.
6062   if (Flag.getNode())
6063     RetOps.push_back(Flag);
6064
6065   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6066 }
6067
6068 SDValue
6069 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6070                                                 SelectionDAG &DAG) const {
6071   SDLoc dl(Op);
6072
6073   // Get the corect type for integers.
6074   EVT IntVT = Op.getValueType();
6075
6076   // Get the inputs.
6077   SDValue Chain = Op.getOperand(0);
6078   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6079   // Build a DYNAREAOFFSET node.
6080   SDValue Ops[2] = {Chain, FPSIdx};
6081   SDVTList VTs = DAG.getVTList(IntVT);
6082   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6083 }
6084
6085 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6086                                              SelectionDAG &DAG) const {
6087   // When we pop the dynamic allocation we need to restore the SP link.
6088   SDLoc dl(Op);
6089
6090   // Get the corect type for pointers.
6091   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6092
6093   // Construct the stack pointer operand.
6094   bool isPPC64 = Subtarget.isPPC64();
6095   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6096   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6097
6098   // Get the operands for the STACKRESTORE.
6099   SDValue Chain = Op.getOperand(0);
6100   SDValue SaveSP = Op.getOperand(1);
6101
6102   // Load the old link SP.
6103   SDValue LoadLinkSP =
6104       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6105
6106   // Restore the stack pointer.
6107   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6108
6109   // Store the old link SP.
6110   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6111 }
6112
6113 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6114   MachineFunction &MF = DAG.getMachineFunction();
6115   bool isPPC64 = Subtarget.isPPC64();
6116   EVT PtrVT = getPointerTy(MF.getDataLayout());
6117
6118   // Get current frame pointer save index.  The users of this index will be
6119   // primarily DYNALLOC instructions.
6120   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6121   int RASI = FI->getReturnAddrSaveIndex();
6122
6123   // If the frame pointer save index hasn't been defined yet.
6124   if (!RASI) {
6125     // Find out what the fix offset of the frame pointer save area.
6126     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6127     // Allocate the frame index for frame pointer save area.
6128     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6129     // Save the result.
6130     FI->setReturnAddrSaveIndex(RASI);
6131   }
6132   return DAG.getFrameIndex(RASI, PtrVT);
6133 }
6134
6135 SDValue
6136 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6137   MachineFunction &MF = DAG.getMachineFunction();
6138   bool isPPC64 = Subtarget.isPPC64();
6139   EVT PtrVT = getPointerTy(MF.getDataLayout());
6140
6141   // Get current frame pointer save index.  The users of this index will be
6142   // primarily DYNALLOC instructions.
6143   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6144   int FPSI = FI->getFramePointerSaveIndex();
6145
6146   // If the frame pointer save index hasn't been defined yet.
6147   if (!FPSI) {
6148     // Find out what the fix offset of the frame pointer save area.
6149     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6150     // Allocate the frame index for frame pointer save area.
6151     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6152     // Save the result.
6153     FI->setFramePointerSaveIndex(FPSI);
6154   }
6155   return DAG.getFrameIndex(FPSI, PtrVT);
6156 }
6157
6158 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6159                                                    SelectionDAG &DAG) const {
6160   // Get the inputs.
6161   SDValue Chain = Op.getOperand(0);
6162   SDValue Size  = Op.getOperand(1);
6163   SDLoc dl(Op);
6164
6165   // Get the corect type for pointers.
6166   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6167   // Negate the size.
6168   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6169                                 DAG.getConstant(0, dl, PtrVT), Size);
6170   // Construct a node for the frame pointer save index.
6171   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6172   // Build a DYNALLOC node.
6173   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6174   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6175   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6176 }
6177
6178 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6179                                                      SelectionDAG &DAG) const {
6180   MachineFunction &MF = DAG.getMachineFunction();
6181
6182   bool isPPC64 = Subtarget.isPPC64();
6183   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6184
6185   int FI = MF.getFrameInfo()->CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6186   return DAG.getFrameIndex(FI, PtrVT);
6187 }
6188
6189 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6190                                                SelectionDAG &DAG) const {
6191   SDLoc DL(Op);
6192   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6193                      DAG.getVTList(MVT::i32, MVT::Other),
6194                      Op.getOperand(0), Op.getOperand(1));
6195 }
6196
6197 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6198                                                 SelectionDAG &DAG) const {
6199   SDLoc DL(Op);
6200   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6201                      Op.getOperand(0), Op.getOperand(1));
6202 }
6203
6204 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6205   if (Op.getValueType().isVector())
6206     return LowerVectorLoad(Op, DAG);
6207
6208   assert(Op.getValueType() == MVT::i1 &&
6209          "Custom lowering only for i1 loads");
6210
6211   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6212
6213   SDLoc dl(Op);
6214   LoadSDNode *LD = cast<LoadSDNode>(Op);
6215
6216   SDValue Chain = LD->getChain();
6217   SDValue BasePtr = LD->getBasePtr();
6218   MachineMemOperand *MMO = LD->getMemOperand();
6219
6220   SDValue NewLD =
6221       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6222                      BasePtr, MVT::i8, MMO);
6223   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6224
6225   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6226   return DAG.getMergeValues(Ops, dl);
6227 }
6228
6229 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6230   if (Op.getOperand(1).getValueType().isVector())
6231     return LowerVectorStore(Op, DAG);
6232
6233   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6234          "Custom lowering only for i1 stores");
6235
6236   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6237
6238   SDLoc dl(Op);
6239   StoreSDNode *ST = cast<StoreSDNode>(Op);
6240
6241   SDValue Chain = ST->getChain();
6242   SDValue BasePtr = ST->getBasePtr();
6243   SDValue Value = ST->getValue();
6244   MachineMemOperand *MMO = ST->getMemOperand();
6245
6246   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6247                       Value);
6248   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6249 }
6250
6251 // FIXME: Remove this once the ANDI glue bug is fixed:
6252 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6253   assert(Op.getValueType() == MVT::i1 &&
6254          "Custom lowering only for i1 results");
6255
6256   SDLoc DL(Op);
6257   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6258                      Op.getOperand(0));
6259 }
6260
6261 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6262 /// possible.
6263 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6264   // Not FP? Not a fsel.
6265   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6266       !Op.getOperand(2).getValueType().isFloatingPoint())
6267     return Op;
6268
6269   // We might be able to do better than this under some circumstances, but in
6270   // general, fsel-based lowering of select is a finite-math-only optimization.
6271   // For more information, see section F.3 of the 2.06 ISA specification.
6272   if (!DAG.getTarget().Options.NoInfsFPMath ||
6273       !DAG.getTarget().Options.NoNaNsFPMath)
6274     return Op;
6275   // TODO: Propagate flags from the select rather than global settings.
6276   SDNodeFlags Flags;
6277   Flags.setNoInfs(true);
6278   Flags.setNoNaNs(true);
6279
6280   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6281
6282   EVT ResVT = Op.getValueType();
6283   EVT CmpVT = Op.getOperand(0).getValueType();
6284   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6285   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6286   SDLoc dl(Op);
6287
6288   // If the RHS of the comparison is a 0.0, we don't need to do the
6289   // subtraction at all.
6290   SDValue Sel1;
6291   if (isFloatingPointZero(RHS))
6292     switch (CC) {
6293     default: break;       // SETUO etc aren't handled by fsel.
6294     case ISD::SETNE:
6295       std::swap(TV, FV);
6296     case ISD::SETEQ:
6297       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6298         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6299       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6300       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6301         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6302       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6303                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6304     case ISD::SETULT:
6305     case ISD::SETLT:
6306       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6307     case ISD::SETOGE:
6308     case ISD::SETGE:
6309       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6310         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6311       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6312     case ISD::SETUGT:
6313     case ISD::SETGT:
6314       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6315     case ISD::SETOLE:
6316     case ISD::SETLE:
6317       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6318         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6319       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6320                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6321     }
6322
6323   SDValue Cmp;
6324   switch (CC) {
6325   default: break;       // SETUO etc aren't handled by fsel.
6326   case ISD::SETNE:
6327     std::swap(TV, FV);
6328   case ISD::SETEQ:
6329     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6330     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6331       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6332     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6333     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6334       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6335     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6336                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6337   case ISD::SETULT:
6338   case ISD::SETLT:
6339     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6340     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6341       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6342     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6343   case ISD::SETOGE:
6344   case ISD::SETGE:
6345     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6346     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6347       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6348     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6349   case ISD::SETUGT:
6350   case ISD::SETGT:
6351     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6352     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6353       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6354     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6355   case ISD::SETOLE:
6356   case ISD::SETLE:
6357     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6358     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6359       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6360     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6361   }
6362   return Op;
6363 }
6364
6365 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6366                                                SelectionDAG &DAG,
6367                                                const SDLoc &dl) const {
6368   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6369   SDValue Src = Op.getOperand(0);
6370   if (Src.getValueType() == MVT::f32)
6371     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6372
6373   SDValue Tmp;
6374   switch (Op.getSimpleValueType().SimpleTy) {
6375   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6376   case MVT::i32:
6377     Tmp = DAG.getNode(
6378         Op.getOpcode() == ISD::FP_TO_SINT
6379             ? PPCISD::FCTIWZ
6380             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6381         dl, MVT::f64, Src);
6382     break;
6383   case MVT::i64:
6384     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6385            "i64 FP_TO_UINT is supported only with FPCVT");
6386     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6387                                                         PPCISD::FCTIDUZ,
6388                       dl, MVT::f64, Src);
6389     break;
6390   }
6391
6392   // Convert the FP value to an int value through memory.
6393   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6394     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6395   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6396   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6397   MachinePointerInfo MPI =
6398       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6399
6400   // Emit a store to the stack slot.
6401   SDValue Chain;
6402   if (i32Stack) {
6403     MachineFunction &MF = DAG.getMachineFunction();
6404     MachineMemOperand *MMO =
6405       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6406     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6407     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6408               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6409   } else
6410     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6411
6412   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6413   // add in a bias on big endian.
6414   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6415     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6416                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6417     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6418   }
6419
6420   RLI.Chain = Chain;
6421   RLI.Ptr = FIPtr;
6422   RLI.MPI = MPI;
6423 }
6424
6425 /// \brief Custom lowers floating point to integer conversions to use
6426 /// the direct move instructions available in ISA 2.07 to avoid the
6427 /// need for load/store combinations.
6428 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6429                                                     SelectionDAG &DAG,
6430                                                     const SDLoc &dl) const {
6431   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6432   SDValue Src = Op.getOperand(0);
6433
6434   if (Src.getValueType() == MVT::f32)
6435     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6436
6437   SDValue Tmp;
6438   switch (Op.getSimpleValueType().SimpleTy) {
6439   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6440   case MVT::i32:
6441     Tmp = DAG.getNode(
6442         Op.getOpcode() == ISD::FP_TO_SINT
6443             ? PPCISD::FCTIWZ
6444             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6445         dl, MVT::f64, Src);
6446     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6447     break;
6448   case MVT::i64:
6449     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6450            "i64 FP_TO_UINT is supported only with FPCVT");
6451     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6452                                                         PPCISD::FCTIDUZ,
6453                       dl, MVT::f64, Src);
6454     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6455     break;
6456   }
6457   return Tmp;
6458 }
6459
6460 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6461                                           const SDLoc &dl) const {
6462   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6463     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6464
6465   ReuseLoadInfo RLI;
6466   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6467
6468   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6469                      RLI.Alignment,
6470                      RLI.IsInvariant ? MachineMemOperand::MOInvariant
6471                                      : MachineMemOperand::MONone,
6472                      RLI.AAInfo, RLI.Ranges);
6473 }
6474
6475 // We're trying to insert a regular store, S, and then a load, L. If the
6476 // incoming value, O, is a load, we might just be able to have our load use the
6477 // address used by O. However, we don't know if anything else will store to
6478 // that address before we can load from it. To prevent this situation, we need
6479 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6480 // the same chain operand as O, we create a token factor from the chain results
6481 // of O and L, and we replace all uses of O's chain result with that token
6482 // factor (see spliceIntoChain below for this last part).
6483 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6484                                             ReuseLoadInfo &RLI,
6485                                             SelectionDAG &DAG,
6486                                             ISD::LoadExtType ET) const {
6487   SDLoc dl(Op);
6488   if (ET == ISD::NON_EXTLOAD &&
6489       (Op.getOpcode() == ISD::FP_TO_UINT ||
6490        Op.getOpcode() == ISD::FP_TO_SINT) &&
6491       isOperationLegalOrCustom(Op.getOpcode(),
6492                                Op.getOperand(0).getValueType())) {
6493
6494     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6495     return true;
6496   }
6497
6498   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6499   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6500       LD->isNonTemporal())
6501     return false;
6502   if (LD->getMemoryVT() != MemVT)
6503     return false;
6504
6505   RLI.Ptr = LD->getBasePtr();
6506   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6507     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6508            "Non-pre-inc AM on PPC?");
6509     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6510                           LD->getOffset());
6511   }
6512
6513   RLI.Chain = LD->getChain();
6514   RLI.MPI = LD->getPointerInfo();
6515   RLI.IsInvariant = LD->isInvariant();
6516   RLI.Alignment = LD->getAlignment();
6517   RLI.AAInfo = LD->getAAInfo();
6518   RLI.Ranges = LD->getRanges();
6519
6520   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6521   return true;
6522 }
6523
6524 // Given the head of the old chain, ResChain, insert a token factor containing
6525 // it and NewResChain, and make users of ResChain now be users of that token
6526 // factor.
6527 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6528                                         SDValue NewResChain,
6529                                         SelectionDAG &DAG) const {
6530   if (!ResChain)
6531     return;
6532
6533   SDLoc dl(NewResChain);
6534
6535   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6536                            NewResChain, DAG.getUNDEF(MVT::Other));
6537   assert(TF.getNode() != NewResChain.getNode() &&
6538          "A new TF really is required here");
6539
6540   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6541   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6542 }
6543
6544 /// \brief Analyze profitability of direct move
6545 /// prefer float load to int load plus direct move
6546 /// when there is no integer use of int load
6547 static bool directMoveIsProfitable(const SDValue &Op) {
6548   SDNode *Origin = Op.getOperand(0).getNode();
6549   if (Origin->getOpcode() != ISD::LOAD)
6550     return true;
6551
6552   for (SDNode::use_iterator UI = Origin->use_begin(),
6553                             UE = Origin->use_end();
6554        UI != UE; ++UI) {
6555
6556     // Only look at the users of the loaded value.
6557     if (UI.getUse().get().getResNo() != 0)
6558       continue;
6559
6560     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6561         UI->getOpcode() != ISD::UINT_TO_FP)
6562       return true;
6563   }
6564
6565   return false;
6566 }
6567
6568 /// \brief Custom lowers integer to floating point conversions to use
6569 /// the direct move instructions available in ISA 2.07 to avoid the
6570 /// need for load/store combinations.
6571 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6572                                                     SelectionDAG &DAG,
6573                                                     const SDLoc &dl) const {
6574   assert((Op.getValueType() == MVT::f32 ||
6575           Op.getValueType() == MVT::f64) &&
6576          "Invalid floating point type as target of conversion");
6577   assert(Subtarget.hasFPCVT() &&
6578          "Int to FP conversions with direct moves require FPCVT");
6579   SDValue FP;
6580   SDValue Src = Op.getOperand(0);
6581   bool SinglePrec = Op.getValueType() == MVT::f32;
6582   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6583   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6584   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6585                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6586
6587   if (WordInt) {
6588     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6589                      dl, MVT::f64, Src);
6590     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6591   }
6592   else {
6593     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6594     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6595   }
6596
6597   return FP;
6598 }
6599
6600 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6601                                           SelectionDAG &DAG) const {
6602   SDLoc dl(Op);
6603
6604   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6605     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6606       return SDValue();
6607
6608     SDValue Value = Op.getOperand(0);
6609     // The values are now known to be -1 (false) or 1 (true). To convert this
6610     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6611     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6612     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6613
6614     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6615
6616     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6617
6618     if (Op.getValueType() != MVT::v4f64)
6619       Value = DAG.getNode(ISD::FP_ROUND, dl,
6620                           Op.getValueType(), Value,
6621                           DAG.getIntPtrConstant(1, dl));
6622     return Value;
6623   }
6624
6625   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6626   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6627     return SDValue();
6628
6629   if (Op.getOperand(0).getValueType() == MVT::i1)
6630     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6631                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6632                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6633
6634   // If we have direct moves, we can do all the conversion, skip the store/load
6635   // however, without FPCVT we can't do most conversions.
6636   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6637       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6638     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6639
6640   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6641          "UINT_TO_FP is supported only with FPCVT");
6642
6643   // If we have FCFIDS, then use it when converting to single-precision.
6644   // Otherwise, convert to double-precision and then round.
6645   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6646                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6647                                                             : PPCISD::FCFIDS)
6648                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6649                                                             : PPCISD::FCFID);
6650   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6651                   ? MVT::f32
6652                   : MVT::f64;
6653
6654   if (Op.getOperand(0).getValueType() == MVT::i64) {
6655     SDValue SINT = Op.getOperand(0);
6656     // When converting to single-precision, we actually need to convert
6657     // to double-precision first and then round to single-precision.
6658     // To avoid double-rounding effects during that operation, we have
6659     // to prepare the input operand.  Bits that might be truncated when
6660     // converting to double-precision are replaced by a bit that won't
6661     // be lost at this stage, but is below the single-precision rounding
6662     // position.
6663     //
6664     // However, if -enable-unsafe-fp-math is in effect, accept double
6665     // rounding to avoid the extra overhead.
6666     if (Op.getValueType() == MVT::f32 &&
6667         !Subtarget.hasFPCVT() &&
6668         !DAG.getTarget().Options.UnsafeFPMath) {
6669
6670       // Twiddle input to make sure the low 11 bits are zero.  (If this
6671       // is the case, we are guaranteed the value will fit into the 53 bit
6672       // mantissa of an IEEE double-precision value without rounding.)
6673       // If any of those low 11 bits were not zero originally, make sure
6674       // bit 12 (value 2048) is set instead, so that the final rounding
6675       // to single-precision gets the correct result.
6676       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6677                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6678       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6679                           Round, DAG.getConstant(2047, dl, MVT::i64));
6680       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6681       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6682                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6683
6684       // However, we cannot use that value unconditionally: if the magnitude
6685       // of the input value is small, the bit-twiddling we did above might
6686       // end up visibly changing the output.  Fortunately, in that case, we
6687       // don't need to twiddle bits since the original input will convert
6688       // exactly to double-precision floating-point already.  Therefore,
6689       // construct a conditional to use the original value if the top 11
6690       // bits are all sign-bit copies, and use the rounded value computed
6691       // above otherwise.
6692       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6693                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6694       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6695                          Cond, DAG.getConstant(1, dl, MVT::i64));
6696       Cond = DAG.getSetCC(dl, MVT::i32,
6697                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6698
6699       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6700     }
6701
6702     ReuseLoadInfo RLI;
6703     SDValue Bits;
6704
6705     MachineFunction &MF = DAG.getMachineFunction();
6706     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6707       Bits =
6708           DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, RLI.Alignment,
6709                       RLI.IsInvariant ? MachineMemOperand::MOInvariant
6710                                       : MachineMemOperand::MONone,
6711                       RLI.AAInfo, RLI.Ranges);
6712       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6713     } else if (Subtarget.hasLFIWAX() &&
6714                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6715       MachineMemOperand *MMO =
6716         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6717                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6718       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6719       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6720                                      DAG.getVTList(MVT::f64, MVT::Other),
6721                                      Ops, MVT::i32, MMO);
6722       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6723     } else if (Subtarget.hasFPCVT() &&
6724                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6725       MachineMemOperand *MMO =
6726         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6727                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6728       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6729       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6730                                      DAG.getVTList(MVT::f64, MVT::Other),
6731                                      Ops, MVT::i32, MMO);
6732       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6733     } else if (((Subtarget.hasLFIWAX() &&
6734                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6735                 (Subtarget.hasFPCVT() &&
6736                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6737                SINT.getOperand(0).getValueType() == MVT::i32) {
6738       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6739       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6740
6741       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6742       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6743
6744       SDValue Store =
6745           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6746                        MachinePointerInfo::getFixedStack(
6747                            DAG.getMachineFunction(), FrameIdx));
6748
6749       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6750              "Expected an i32 store");
6751
6752       RLI.Ptr = FIdx;
6753       RLI.Chain = Store;
6754       RLI.MPI =
6755           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6756       RLI.Alignment = 4;
6757
6758       MachineMemOperand *MMO =
6759         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6760                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6761       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6762       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6763                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6764                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6765                                      Ops, MVT::i32, MMO);
6766     } else
6767       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6768
6769     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6770
6771     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6772       FP = DAG.getNode(ISD::FP_ROUND, dl,
6773                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6774     return FP;
6775   }
6776
6777   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6778          "Unhandled INT_TO_FP type in custom expander!");
6779   // Since we only generate this in 64-bit mode, we can take advantage of
6780   // 64-bit registers.  In particular, sign extend the input value into the
6781   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6782   // then lfd it and fcfid it.
6783   MachineFunction &MF = DAG.getMachineFunction();
6784   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6785   EVT PtrVT = getPointerTy(MF.getDataLayout());
6786
6787   SDValue Ld;
6788   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6789     ReuseLoadInfo RLI;
6790     bool ReusingLoad;
6791     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6792                                             DAG))) {
6793       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6794       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6795
6796       SDValue Store =
6797           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6798                        MachinePointerInfo::getFixedStack(
6799                            DAG.getMachineFunction(), FrameIdx));
6800
6801       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6802              "Expected an i32 store");
6803
6804       RLI.Ptr = FIdx;
6805       RLI.Chain = Store;
6806       RLI.MPI =
6807           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6808       RLI.Alignment = 4;
6809     }
6810
6811     MachineMemOperand *MMO =
6812       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6813                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6814     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6815     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6816                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6817                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6818                                  Ops, MVT::i32, MMO);
6819     if (ReusingLoad)
6820       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6821   } else {
6822     assert(Subtarget.isPPC64() &&
6823            "i32->FP without LFIWAX supported only on PPC64");
6824
6825     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6826     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6827
6828     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6829                                 Op.getOperand(0));
6830
6831     // STD the extended value into the stack slot.
6832     SDValue Store = DAG.getStore(
6833         DAG.getEntryNode(), dl, Ext64, FIdx,
6834         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6835
6836     // Load the value as a double.
6837     Ld = DAG.getLoad(
6838         MVT::f64, dl, Store, FIdx,
6839         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6840   }
6841
6842   // FCFID it and return it.
6843   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6844   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6845     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6846                      DAG.getIntPtrConstant(0, dl));
6847   return FP;
6848 }
6849
6850 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6851                                             SelectionDAG &DAG) const {
6852   SDLoc dl(Op);
6853   /*
6854    The rounding mode is in bits 30:31 of FPSR, and has the following
6855    settings:
6856      00 Round to nearest
6857      01 Round to 0
6858      10 Round to +inf
6859      11 Round to -inf
6860
6861   FLT_ROUNDS, on the other hand, expects the following:
6862     -1 Undefined
6863      0 Round to 0
6864      1 Round to nearest
6865      2 Round to +inf
6866      3 Round to -inf
6867
6868   To perform the conversion, we do:
6869     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6870   */
6871
6872   MachineFunction &MF = DAG.getMachineFunction();
6873   EVT VT = Op.getValueType();
6874   EVT PtrVT = getPointerTy(MF.getDataLayout());
6875
6876   // Save FP Control Word to register
6877   EVT NodeTys[] = {
6878     MVT::f64,    // return register
6879     MVT::Glue    // unused in this context
6880   };
6881   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6882
6883   // Save FP register to stack slot
6884   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6885   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6886   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
6887                                MachinePointerInfo());
6888
6889   // Load FP Control Word from low 32 bits of stack slot.
6890   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6891   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6892   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
6893
6894   // Transform as necessary
6895   SDValue CWD1 =
6896     DAG.getNode(ISD::AND, dl, MVT::i32,
6897                 CWD, DAG.getConstant(3, dl, MVT::i32));
6898   SDValue CWD2 =
6899     DAG.getNode(ISD::SRL, dl, MVT::i32,
6900                 DAG.getNode(ISD::AND, dl, MVT::i32,
6901                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6902                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6903                             DAG.getConstant(3, dl, MVT::i32)),
6904                 DAG.getConstant(1, dl, MVT::i32));
6905
6906   SDValue RetVal =
6907     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6908
6909   return DAG.getNode((VT.getSizeInBits() < 16 ?
6910                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6911 }
6912
6913 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6914   EVT VT = Op.getValueType();
6915   unsigned BitWidth = VT.getSizeInBits();
6916   SDLoc dl(Op);
6917   assert(Op.getNumOperands() == 3 &&
6918          VT == Op.getOperand(1).getValueType() &&
6919          "Unexpected SHL!");
6920
6921   // Expand into a bunch of logical ops.  Note that these ops
6922   // depend on the PPC behavior for oversized shift amounts.
6923   SDValue Lo = Op.getOperand(0);
6924   SDValue Hi = Op.getOperand(1);
6925   SDValue Amt = Op.getOperand(2);
6926   EVT AmtVT = Amt.getValueType();
6927
6928   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6929                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6930   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6931   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6932   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6933   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6934                              DAG.getConstant(-BitWidth, dl, AmtVT));
6935   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6936   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6937   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6938   SDValue OutOps[] = { OutLo, OutHi };
6939   return DAG.getMergeValues(OutOps, dl);
6940 }
6941
6942 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6943   EVT VT = Op.getValueType();
6944   SDLoc dl(Op);
6945   unsigned BitWidth = VT.getSizeInBits();
6946   assert(Op.getNumOperands() == 3 &&
6947          VT == Op.getOperand(1).getValueType() &&
6948          "Unexpected SRL!");
6949
6950   // Expand into a bunch of logical ops.  Note that these ops
6951   // depend on the PPC behavior for oversized shift amounts.
6952   SDValue Lo = Op.getOperand(0);
6953   SDValue Hi = Op.getOperand(1);
6954   SDValue Amt = Op.getOperand(2);
6955   EVT AmtVT = Amt.getValueType();
6956
6957   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6958                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6959   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6960   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6961   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6962   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6963                              DAG.getConstant(-BitWidth, dl, AmtVT));
6964   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6965   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6966   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6967   SDValue OutOps[] = { OutLo, OutHi };
6968   return DAG.getMergeValues(OutOps, dl);
6969 }
6970
6971 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6972   SDLoc dl(Op);
6973   EVT VT = Op.getValueType();
6974   unsigned BitWidth = VT.getSizeInBits();
6975   assert(Op.getNumOperands() == 3 &&
6976          VT == Op.getOperand(1).getValueType() &&
6977          "Unexpected SRA!");
6978
6979   // Expand into a bunch of logical ops, followed by a select_cc.
6980   SDValue Lo = Op.getOperand(0);
6981   SDValue Hi = Op.getOperand(1);
6982   SDValue Amt = Op.getOperand(2);
6983   EVT AmtVT = Amt.getValueType();
6984
6985   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6986                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6987   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6988   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6989   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6990   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6991                              DAG.getConstant(-BitWidth, dl, AmtVT));
6992   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6993   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6994   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6995                                   Tmp4, Tmp6, ISD::SETLE);
6996   SDValue OutOps[] = { OutLo, OutHi };
6997   return DAG.getMergeValues(OutOps, dl);
6998 }
6999
7000 //===----------------------------------------------------------------------===//
7001 // Vector related lowering.
7002 //
7003
7004 /// BuildSplatI - Build a canonical splati of Val with an element size of
7005 /// SplatSize.  Cast the result to VT.
7006 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7007                            SelectionDAG &DAG, const SDLoc &dl) {
7008   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7009
7010   static const MVT VTys[] = { // canonical VT to use for each size.
7011     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7012   };
7013
7014   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7015
7016   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7017   if (Val == -1)
7018     SplatSize = 1;
7019
7020   EVT CanonicalVT = VTys[SplatSize-1];
7021
7022   // Build a canonical splat for this value.
7023   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7024 }
7025
7026 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7027 /// specified intrinsic ID.
7028 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7029                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7030   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7031   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7032                      DAG.getConstant(IID, dl, MVT::i32), Op);
7033 }
7034
7035 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7036 /// specified intrinsic ID.
7037 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7038                                 SelectionDAG &DAG, const SDLoc &dl,
7039                                 EVT DestVT = MVT::Other) {
7040   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7041   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7042                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7043 }
7044
7045 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7046 /// specified intrinsic ID.
7047 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7048                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7049                                 EVT DestVT = MVT::Other) {
7050   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7051   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7052                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7053 }
7054
7055 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7056 /// amount.  The result has the specified value type.
7057 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7058                            SelectionDAG &DAG, const SDLoc &dl) {
7059   // Force LHS/RHS to be the right type.
7060   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7061   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7062
7063   int Ops[16];
7064   for (unsigned i = 0; i != 16; ++i)
7065     Ops[i] = i + Amt;
7066   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7067   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7068 }
7069
7070 // If this is a case we can't handle, return null and let the default
7071 // expansion code take care of it.  If we CAN select this case, and if it
7072 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7073 // this case more efficiently than a constant pool load, lower it to the
7074 // sequence of ops that should be used.
7075 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7076                                              SelectionDAG &DAG) const {
7077   SDLoc dl(Op);
7078   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7079   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7080
7081   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7082     // We first build an i32 vector, load it into a QPX register,
7083     // then convert it to a floating-point vector and compare it
7084     // to a zero vector to get the boolean result.
7085     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7086     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7087     MachinePointerInfo PtrInfo =
7088         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7089     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7090     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7091
7092     assert(BVN->getNumOperands() == 4 &&
7093       "BUILD_VECTOR for v4i1 does not have 4 operands");
7094
7095     bool IsConst = true;
7096     for (unsigned i = 0; i < 4; ++i) {
7097       if (BVN->getOperand(i).isUndef()) continue;
7098       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7099         IsConst = false;
7100         break;
7101       }
7102     }
7103
7104     if (IsConst) {
7105       Constant *One =
7106         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7107       Constant *NegOne =
7108         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7109
7110       Constant *CV[4];
7111       for (unsigned i = 0; i < 4; ++i) {
7112         if (BVN->getOperand(i).isUndef())
7113           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7114         else if (isNullConstant(BVN->getOperand(i)))
7115           CV[i] = NegOne;
7116         else
7117           CV[i] = One;
7118       }
7119
7120       Constant *CP = ConstantVector::get(CV);
7121       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7122                                           16 /* alignment */);
7123
7124       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7125       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7126       return DAG.getMemIntrinsicNode(
7127           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7128           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7129     }
7130
7131     SmallVector<SDValue, 4> Stores;
7132     for (unsigned i = 0; i < 4; ++i) {
7133       if (BVN->getOperand(i).isUndef()) continue;
7134
7135       unsigned Offset = 4*i;
7136       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7137       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7138
7139       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7140       if (StoreSize > 4) {
7141         Stores.push_back(
7142             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7143                               PtrInfo.getWithOffset(Offset), MVT::i32));
7144       } else {
7145         SDValue StoreValue = BVN->getOperand(i);
7146         if (StoreSize < 4)
7147           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7148
7149         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7150                                       PtrInfo.getWithOffset(Offset)));
7151       }
7152     }
7153
7154     SDValue StoreChain;
7155     if (!Stores.empty())
7156       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7157     else
7158       StoreChain = DAG.getEntryNode();
7159
7160     // Now load from v4i32 into the QPX register; this will extend it to
7161     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7162     // is typed as v4f64 because the QPX register integer states are not
7163     // explicitly represented.
7164
7165     SDValue Ops[] = {StoreChain,
7166                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7167                      FIdx};
7168     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7169
7170     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7171       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7172     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7173       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7174       LoadedVect);
7175
7176     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7177
7178     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7179   }
7180
7181   // All other QPX vectors are handled by generic code.
7182   if (Subtarget.hasQPX())
7183     return SDValue();
7184
7185   // Check if this is a splat of a constant value.
7186   APInt APSplatBits, APSplatUndef;
7187   unsigned SplatBitSize;
7188   bool HasAnyUndefs;
7189   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7190                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7191       SplatBitSize > 32)
7192     return SDValue();
7193
7194   unsigned SplatBits = APSplatBits.getZExtValue();
7195   unsigned SplatUndef = APSplatUndef.getZExtValue();
7196   unsigned SplatSize = SplatBitSize / 8;
7197
7198   // First, handle single instruction cases.
7199
7200   // All zeros?
7201   if (SplatBits == 0) {
7202     // Canonicalize all zero vectors to be v4i32.
7203     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7204       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7205       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7206     }
7207     return Op;
7208   }
7209
7210   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7211   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7212                     (32-SplatBitSize));
7213   if (SextVal >= -16 && SextVal <= 15)
7214     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7215
7216   // Two instruction sequences.
7217
7218   // If this value is in the range [-32,30] and is even, use:
7219   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7220   // If this value is in the range [17,31] and is odd, use:
7221   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7222   // If this value is in the range [-31,-17] and is odd, use:
7223   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7224   // Note the last two are three-instruction sequences.
7225   if (SextVal >= -32 && SextVal <= 31) {
7226     // To avoid having these optimizations undone by constant folding,
7227     // we convert to a pseudo that will be expanded later into one of
7228     // the above forms.
7229     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7230     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7231               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7232     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7233     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7234     if (VT == Op.getValueType())
7235       return RetVal;
7236     else
7237       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7238   }
7239
7240   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7241   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7242   // for fneg/fabs.
7243   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7244     // Make -1 and vspltisw -1:
7245     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7246
7247     // Make the VSLW intrinsic, computing 0x8000_0000.
7248     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7249                                    OnesV, DAG, dl);
7250
7251     // xor by OnesV to invert it.
7252     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7253     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7254   }
7255
7256   // Check to see if this is a wide variety of vsplti*, binop self cases.
7257   static const signed char SplatCsts[] = {
7258     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7259     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7260   };
7261
7262   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7263     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7264     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7265     int i = SplatCsts[idx];
7266
7267     // Figure out what shift amount will be used by altivec if shifted by i in
7268     // this splat size.
7269     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7270
7271     // vsplti + shl self.
7272     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7273       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7274       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7275         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7276         Intrinsic::ppc_altivec_vslw
7277       };
7278       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7279       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7280     }
7281
7282     // vsplti + srl self.
7283     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7284       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7285       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7286         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7287         Intrinsic::ppc_altivec_vsrw
7288       };
7289       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7290       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7291     }
7292
7293     // vsplti + sra self.
7294     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7295       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7296       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7297         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7298         Intrinsic::ppc_altivec_vsraw
7299       };
7300       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7301       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7302     }
7303
7304     // vsplti + rol self.
7305     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7306                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7307       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7308       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7309         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7310         Intrinsic::ppc_altivec_vrlw
7311       };
7312       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7313       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7314     }
7315
7316     // t = vsplti c, result = vsldoi t, t, 1
7317     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7318       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7319       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7320       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7321     }
7322     // t = vsplti c, result = vsldoi t, t, 2
7323     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7324       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7325       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7326       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7327     }
7328     // t = vsplti c, result = vsldoi t, t, 3
7329     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7330       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7331       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7332       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7333     }
7334   }
7335
7336   return SDValue();
7337 }
7338
7339 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7340 /// the specified operations to build the shuffle.
7341 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7342                                       SDValue RHS, SelectionDAG &DAG,
7343                                       const SDLoc &dl) {
7344   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7345   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7346   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7347
7348   enum {
7349     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7350     OP_VMRGHW,
7351     OP_VMRGLW,
7352     OP_VSPLTISW0,
7353     OP_VSPLTISW1,
7354     OP_VSPLTISW2,
7355     OP_VSPLTISW3,
7356     OP_VSLDOI4,
7357     OP_VSLDOI8,
7358     OP_VSLDOI12
7359   };
7360
7361   if (OpNum == OP_COPY) {
7362     if (LHSID == (1*9+2)*9+3) return LHS;
7363     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7364     return RHS;
7365   }
7366
7367   SDValue OpLHS, OpRHS;
7368   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7369   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7370
7371   int ShufIdxs[16];
7372   switch (OpNum) {
7373   default: llvm_unreachable("Unknown i32 permute!");
7374   case OP_VMRGHW:
7375     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7376     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7377     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7378     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7379     break;
7380   case OP_VMRGLW:
7381     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7382     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7383     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7384     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7385     break;
7386   case OP_VSPLTISW0:
7387     for (unsigned i = 0; i != 16; ++i)
7388       ShufIdxs[i] = (i&3)+0;
7389     break;
7390   case OP_VSPLTISW1:
7391     for (unsigned i = 0; i != 16; ++i)
7392       ShufIdxs[i] = (i&3)+4;
7393     break;
7394   case OP_VSPLTISW2:
7395     for (unsigned i = 0; i != 16; ++i)
7396       ShufIdxs[i] = (i&3)+8;
7397     break;
7398   case OP_VSPLTISW3:
7399     for (unsigned i = 0; i != 16; ++i)
7400       ShufIdxs[i] = (i&3)+12;
7401     break;
7402   case OP_VSLDOI4:
7403     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7404   case OP_VSLDOI8:
7405     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7406   case OP_VSLDOI12:
7407     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7408   }
7409   EVT VT = OpLHS.getValueType();
7410   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7411   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7412   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7413   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7414 }
7415
7416 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7417 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7418 /// return the code it can be lowered into.  Worst case, it can always be
7419 /// lowered into a vperm.
7420 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7421                                                SelectionDAG &DAG) const {
7422   SDLoc dl(Op);
7423   SDValue V1 = Op.getOperand(0);
7424   SDValue V2 = Op.getOperand(1);
7425   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7426   EVT VT = Op.getValueType();
7427   bool isLittleEndian = Subtarget.isLittleEndian();
7428
7429   unsigned ShiftElts, InsertAtByte;
7430   bool Swap;
7431   if (Subtarget.hasP9Vector() &&
7432       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7433                            isLittleEndian)) {
7434     if (Swap)
7435       std::swap(V1, V2);
7436     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7437     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7438     if (ShiftElts) {
7439       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7440                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7441       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7442                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7443       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7444     }
7445     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7446                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7447     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7448   }
7449
7450   if (Subtarget.hasVSX()) {
7451     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7452       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7453       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7454       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7455                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7456       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7457     }
7458
7459     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7460     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7461       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7462       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7463       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7464     }
7465
7466   }
7467
7468   if (Subtarget.hasQPX()) {
7469     if (VT.getVectorNumElements() != 4)
7470       return SDValue();
7471
7472     if (V2.isUndef()) V2 = V1;
7473
7474     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7475     if (AlignIdx != -1) {
7476       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7477                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7478     } else if (SVOp->isSplat()) {
7479       int SplatIdx = SVOp->getSplatIndex();
7480       if (SplatIdx >= 4) {
7481         std::swap(V1, V2);
7482         SplatIdx -= 4;
7483       }
7484
7485       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7486                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7487     }
7488
7489     // Lower this into a qvgpci/qvfperm pair.
7490
7491     // Compute the qvgpci literal
7492     unsigned idx = 0;
7493     for (unsigned i = 0; i < 4; ++i) {
7494       int m = SVOp->getMaskElt(i);
7495       unsigned mm = m >= 0 ? (unsigned) m : i;
7496       idx |= mm << (3-i)*3;
7497     }
7498
7499     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7500                              DAG.getConstant(idx, dl, MVT::i32));
7501     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7502   }
7503
7504   // Cases that are handled by instructions that take permute immediates
7505   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7506   // selected by the instruction selector.
7507   if (V2.isUndef()) {
7508     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7509         PPC::isSplatShuffleMask(SVOp, 2) ||
7510         PPC::isSplatShuffleMask(SVOp, 4) ||
7511         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7512         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7513         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7514         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7515         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7516         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7517         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7518         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7519         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7520         (Subtarget.hasP8Altivec() && (
7521          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7522          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7523          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7524       return Op;
7525     }
7526   }
7527
7528   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7529   // and produce a fixed permutation.  If any of these match, do not lower to
7530   // VPERM.
7531   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7532   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7533       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7534       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7535       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7536       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7537       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7538       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7539       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7540       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7541       (Subtarget.hasP8Altivec() && (
7542        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7543        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7544        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7545     return Op;
7546
7547   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7548   // perfect shuffle table to emit an optimal matching sequence.
7549   ArrayRef<int> PermMask = SVOp->getMask();
7550
7551   unsigned PFIndexes[4];
7552   bool isFourElementShuffle = true;
7553   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7554     unsigned EltNo = 8;   // Start out undef.
7555     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7556       if (PermMask[i*4+j] < 0)
7557         continue;   // Undef, ignore it.
7558
7559       unsigned ByteSource = PermMask[i*4+j];
7560       if ((ByteSource & 3) != j) {
7561         isFourElementShuffle = false;
7562         break;
7563       }
7564
7565       if (EltNo == 8) {
7566         EltNo = ByteSource/4;
7567       } else if (EltNo != ByteSource/4) {
7568         isFourElementShuffle = false;
7569         break;
7570       }
7571     }
7572     PFIndexes[i] = EltNo;
7573   }
7574
7575   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7576   // perfect shuffle vector to determine if it is cost effective to do this as
7577   // discrete instructions, or whether we should use a vperm.
7578   // For now, we skip this for little endian until such time as we have a
7579   // little-endian perfect shuffle table.
7580   if (isFourElementShuffle && !isLittleEndian) {
7581     // Compute the index in the perfect shuffle table.
7582     unsigned PFTableIndex =
7583       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7584
7585     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7586     unsigned Cost  = (PFEntry >> 30);
7587
7588     // Determining when to avoid vperm is tricky.  Many things affect the cost
7589     // of vperm, particularly how many times the perm mask needs to be computed.
7590     // For example, if the perm mask can be hoisted out of a loop or is already
7591     // used (perhaps because there are multiple permutes with the same shuffle
7592     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7593     // the loop requires an extra register.
7594     //
7595     // As a compromise, we only emit discrete instructions if the shuffle can be
7596     // generated in 3 or fewer operations.  When we have loop information
7597     // available, if this block is within a loop, we should avoid using vperm
7598     // for 3-operation perms and use a constant pool load instead.
7599     if (Cost < 3)
7600       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7601   }
7602
7603   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7604   // vector that will get spilled to the constant pool.
7605   if (V2.isUndef()) V2 = V1;
7606
7607   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7608   // that it is in input element units, not in bytes.  Convert now.
7609
7610   // For little endian, the order of the input vectors is reversed, and
7611   // the permutation mask is complemented with respect to 31.  This is
7612   // necessary to produce proper semantics with the big-endian-biased vperm
7613   // instruction.
7614   EVT EltVT = V1.getValueType().getVectorElementType();
7615   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7616
7617   SmallVector<SDValue, 16> ResultMask;
7618   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7619     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7620
7621     for (unsigned j = 0; j != BytesPerElement; ++j)
7622       if (isLittleEndian)
7623         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7624                                              dl, MVT::i32));
7625       else
7626         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7627                                              MVT::i32));
7628   }
7629
7630   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7631   if (isLittleEndian)
7632     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7633                        V2, V1, VPermMask);
7634   else
7635     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7636                        V1, V2, VPermMask);
7637 }
7638
7639 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7640 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7641 /// information about the intrinsic.
7642 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7643                                  bool &isDot, const PPCSubtarget &Subtarget) {
7644   unsigned IntrinsicID =
7645     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7646   CompareOpc = -1;
7647   isDot = false;
7648   switch (IntrinsicID) {
7649   default: return false;
7650     // Comparison predicates.
7651   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7652   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7653   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7654   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7655   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7656   case Intrinsic::ppc_altivec_vcmpequd_p:
7657     if (Subtarget.hasP8Altivec()) {
7658       CompareOpc = 199;
7659       isDot = 1;
7660     } else
7661       return false;
7662
7663     break;
7664   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7665   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7666   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7667   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7668   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7669   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7670     if (Subtarget.hasP8Altivec()) {
7671       CompareOpc = 967;
7672       isDot = 1;
7673     } else
7674       return false;
7675
7676     break;
7677   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7678   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7679   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7680   case Intrinsic::ppc_altivec_vcmpgtud_p:
7681     if (Subtarget.hasP8Altivec()) {
7682       CompareOpc = 711;
7683       isDot = 1;
7684     } else
7685       return false;
7686
7687     break;
7688     // VSX predicate comparisons use the same infrastructure
7689   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7690   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7691   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7692   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7693   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7694   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7695     if (Subtarget.hasVSX()) {
7696       switch (IntrinsicID) {
7697       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7698       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7699       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7700       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7701       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7702       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7703       }
7704       isDot = 1;
7705     }
7706     else
7707       return false;
7708
7709     break;
7710
7711     // Normal Comparisons.
7712   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7713   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7714   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7715   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7716   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7717   case Intrinsic::ppc_altivec_vcmpequd:
7718     if (Subtarget.hasP8Altivec()) {
7719       CompareOpc = 199;
7720       isDot = 0;
7721     } else
7722       return false;
7723
7724     break;
7725   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7726   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7727   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7728   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7729   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7730   case Intrinsic::ppc_altivec_vcmpgtsd:
7731     if (Subtarget.hasP8Altivec()) {
7732       CompareOpc = 967;
7733       isDot = 0;
7734     } else
7735       return false;
7736
7737     break;
7738   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7739   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7740   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7741   case Intrinsic::ppc_altivec_vcmpgtud:
7742     if (Subtarget.hasP8Altivec()) {
7743       CompareOpc = 711;
7744       isDot = 0;
7745     } else
7746       return false;
7747
7748     break;
7749   }
7750   return true;
7751 }
7752
7753 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7754 /// lower, do it, otherwise return null.
7755 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7756                                                    SelectionDAG &DAG) const {
7757   unsigned IntrinsicID =
7758     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7759
7760   if (IntrinsicID == Intrinsic::thread_pointer) {
7761     // Reads the thread pointer register, used for __builtin_thread_pointer.
7762     bool is64bit = Subtarget.isPPC64();
7763     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7764                            is64bit ? MVT::i64 : MVT::i32);
7765   }
7766
7767   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7768   // opcode number of the comparison.
7769   SDLoc dl(Op);
7770   int CompareOpc;
7771   bool isDot;
7772   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7773     return SDValue();    // Don't custom lower most intrinsics.
7774
7775   // If this is a non-dot comparison, make the VCMP node and we are done.
7776   if (!isDot) {
7777     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7778                               Op.getOperand(1), Op.getOperand(2),
7779                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7780     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7781   }
7782
7783   // Create the PPCISD altivec 'dot' comparison node.
7784   SDValue Ops[] = {
7785     Op.getOperand(2),  // LHS
7786     Op.getOperand(3),  // RHS
7787     DAG.getConstant(CompareOpc, dl, MVT::i32)
7788   };
7789   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7790   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7791
7792   // Now that we have the comparison, emit a copy from the CR to a GPR.
7793   // This is flagged to the above dot comparison.
7794   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7795                                 DAG.getRegister(PPC::CR6, MVT::i32),
7796                                 CompNode.getValue(1));
7797
7798   // Unpack the result based on how the target uses it.
7799   unsigned BitNo;   // Bit # of CR6.
7800   bool InvertBit;   // Invert result?
7801   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7802   default:  // Can't happen, don't crash on invalid number though.
7803   case 0:   // Return the value of the EQ bit of CR6.
7804     BitNo = 0; InvertBit = false;
7805     break;
7806   case 1:   // Return the inverted value of the EQ bit of CR6.
7807     BitNo = 0; InvertBit = true;
7808     break;
7809   case 2:   // Return the value of the LT bit of CR6.
7810     BitNo = 2; InvertBit = false;
7811     break;
7812   case 3:   // Return the inverted value of the LT bit of CR6.
7813     BitNo = 2; InvertBit = true;
7814     break;
7815   }
7816
7817   // Shift the bit into the low position.
7818   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7819                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7820   // Isolate the bit.
7821   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7822                       DAG.getConstant(1, dl, MVT::i32));
7823
7824   // If we are supposed to, toggle the bit.
7825   if (InvertBit)
7826     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7827                         DAG.getConstant(1, dl, MVT::i32));
7828   return Flags;
7829 }
7830
7831 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7832                                                   SelectionDAG &DAG) const {
7833   SDLoc dl(Op);
7834   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7835   // instructions), but for smaller types, we need to first extend up to v2i32
7836   // before doing going farther.
7837   if (Op.getValueType() == MVT::v2i64) {
7838     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7839     if (ExtVT != MVT::v2i32) {
7840       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7841       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7842                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7843                                         ExtVT.getVectorElementType(), 4)));
7844       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7845       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7846                        DAG.getValueType(MVT::v2i32));
7847     }
7848
7849     return Op;
7850   }
7851
7852   return SDValue();
7853 }
7854
7855 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7856                                                    SelectionDAG &DAG) const {
7857   SDLoc dl(Op);
7858   // Create a stack slot that is 16-byte aligned.
7859   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7860   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7861   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7862   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7863
7864   // Store the input value into Value#0 of the stack slot.
7865   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7866                                MachinePointerInfo());
7867   // Load it out.
7868   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
7869 }
7870
7871 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7872                                                    SelectionDAG &DAG) const {
7873   SDLoc dl(Op);
7874   SDNode *N = Op.getNode();
7875
7876   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7877          "Unknown extract_vector_elt type");
7878
7879   SDValue Value = N->getOperand(0);
7880
7881   // The first part of this is like the store lowering except that we don't
7882   // need to track the chain.
7883
7884   // The values are now known to be -1 (false) or 1 (true). To convert this
7885   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7886   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7887   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7888
7889   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7890   // understand how to form the extending load.
7891   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7892
7893   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7894
7895   // Now convert to an integer and store.
7896   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7897     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7898     Value);
7899
7900   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7901   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7902   MachinePointerInfo PtrInfo =
7903       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7904   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7905   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7906
7907   SDValue StoreChain = DAG.getEntryNode();
7908   SDValue Ops[] = {StoreChain,
7909                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
7910                    Value, FIdx};
7911   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
7912
7913   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7914     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7915
7916   // Extract the value requested.
7917   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7918   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7919   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7920
7921   SDValue IntVal =
7922       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
7923
7924   if (!Subtarget.useCRBits())
7925     return IntVal;
7926
7927   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7928 }
7929
7930 /// Lowering for QPX v4i1 loads
7931 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7932                                            SelectionDAG &DAG) const {
7933   SDLoc dl(Op);
7934   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7935   SDValue LoadChain = LN->getChain();
7936   SDValue BasePtr = LN->getBasePtr();
7937
7938   if (Op.getValueType() == MVT::v4f64 ||
7939       Op.getValueType() == MVT::v4f32) {
7940     EVT MemVT = LN->getMemoryVT();
7941     unsigned Alignment = LN->getAlignment();
7942
7943     // If this load is properly aligned, then it is legal.
7944     if (Alignment >= MemVT.getStoreSize())
7945       return Op;
7946
7947     EVT ScalarVT = Op.getValueType().getScalarType(),
7948         ScalarMemVT = MemVT.getScalarType();
7949     unsigned Stride = ScalarMemVT.getStoreSize();
7950
7951     SDValue Vals[4], LoadChains[4];
7952     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7953       SDValue Load;
7954       if (ScalarVT != ScalarMemVT)
7955         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7956                               BasePtr,
7957                               LN->getPointerInfo().getWithOffset(Idx * Stride),
7958                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
7959                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
7960       else
7961         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7962                            LN->getPointerInfo().getWithOffset(Idx * Stride),
7963                            MinAlign(Alignment, Idx * Stride),
7964                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
7965
7966       if (Idx == 0 && LN->isIndexed()) {
7967         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7968                "Unknown addressing mode on vector load");
7969         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7970                                   LN->getAddressingMode());
7971       }
7972
7973       Vals[Idx] = Load;
7974       LoadChains[Idx] = Load.getValue(1);
7975
7976       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7977                             DAG.getConstant(Stride, dl,
7978                                             BasePtr.getValueType()));
7979     }
7980
7981     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7982     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
7983
7984     if (LN->isIndexed()) {
7985       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7986       return DAG.getMergeValues(RetOps, dl);
7987     }
7988
7989     SDValue RetOps[] = { Value, TF };
7990     return DAG.getMergeValues(RetOps, dl);
7991   }
7992
7993   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7994   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7995
7996   // To lower v4i1 from a byte array, we load the byte elements of the
7997   // vector and then reuse the BUILD_VECTOR logic.
7998
7999   SDValue VectElmts[4], VectElmtChains[4];
8000   for (unsigned i = 0; i < 4; ++i) {
8001     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8002     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8003
8004     VectElmts[i] = DAG.getExtLoad(
8005         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8006         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8007         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8008     VectElmtChains[i] = VectElmts[i].getValue(1);
8009   }
8010
8011   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8012   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8013
8014   SDValue RVals[] = { Value, LoadChain };
8015   return DAG.getMergeValues(RVals, dl);
8016 }
8017
8018 /// Lowering for QPX v4i1 stores
8019 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8020                                             SelectionDAG &DAG) const {
8021   SDLoc dl(Op);
8022   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8023   SDValue StoreChain = SN->getChain();
8024   SDValue BasePtr = SN->getBasePtr();
8025   SDValue Value = SN->getValue();
8026
8027   if (Value.getValueType() == MVT::v4f64 ||
8028       Value.getValueType() == MVT::v4f32) {
8029     EVT MemVT = SN->getMemoryVT();
8030     unsigned Alignment = SN->getAlignment();
8031
8032     // If this store is properly aligned, then it is legal.
8033     if (Alignment >= MemVT.getStoreSize())
8034       return Op;
8035
8036     EVT ScalarVT = Value.getValueType().getScalarType(),
8037         ScalarMemVT = MemVT.getScalarType();
8038     unsigned Stride = ScalarMemVT.getStoreSize();
8039
8040     SDValue Stores[4];
8041     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8042       SDValue Ex = DAG.getNode(
8043           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8044           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8045       SDValue Store;
8046       if (ScalarVT != ScalarMemVT)
8047         Store =
8048             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8049                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8050                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8051                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8052       else
8053         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8054                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8055                              MinAlign(Alignment, Idx * Stride),
8056                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8057
8058       if (Idx == 0 && SN->isIndexed()) {
8059         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8060                "Unknown addressing mode on vector store");
8061         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8062                                     SN->getAddressingMode());
8063       }
8064
8065       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8066                             DAG.getConstant(Stride, dl,
8067                                             BasePtr.getValueType()));
8068       Stores[Idx] = Store;
8069     }
8070
8071     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8072
8073     if (SN->isIndexed()) {
8074       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8075       return DAG.getMergeValues(RetOps, dl);
8076     }
8077
8078     return TF;
8079   }
8080
8081   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8082   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8083
8084   // The values are now known to be -1 (false) or 1 (true). To convert this
8085   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8086   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8087   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8088
8089   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8090   // understand how to form the extending load.
8091   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8092
8093   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8094
8095   // Now convert to an integer and store.
8096   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8097     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8098     Value);
8099
8100   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
8101   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
8102   MachinePointerInfo PtrInfo =
8103       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8104   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8105   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8106
8107   SDValue Ops[] = {StoreChain,
8108                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8109                    Value, FIdx};
8110   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8111
8112   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8113     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8114
8115   // Move data into the byte array.
8116   SDValue Loads[4], LoadChains[4];
8117   for (unsigned i = 0; i < 4; ++i) {
8118     unsigned Offset = 4*i;
8119     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8120     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8121
8122     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8123                            PtrInfo.getWithOffset(Offset));
8124     LoadChains[i] = Loads[i].getValue(1);
8125   }
8126
8127   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8128
8129   SDValue Stores[4];
8130   for (unsigned i = 0; i < 4; ++i) {
8131     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8132     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8133
8134     Stores[i] = DAG.getTruncStore(
8135         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8136         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8137         SN->getAAInfo());
8138   }
8139
8140   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8141
8142   return StoreChain;
8143 }
8144
8145 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8146   SDLoc dl(Op);
8147   if (Op.getValueType() == MVT::v4i32) {
8148     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8149
8150     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8151     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8152
8153     SDValue RHSSwap =   // = vrlw RHS, 16
8154       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8155
8156     // Shrinkify inputs to v8i16.
8157     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8158     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8159     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8160
8161     // Low parts multiplied together, generating 32-bit results (we ignore the
8162     // top parts).
8163     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8164                                         LHS, RHS, DAG, dl, MVT::v4i32);
8165
8166     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8167                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8168     // Shift the high parts up 16 bits.
8169     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8170                               Neg16, DAG, dl);
8171     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8172   } else if (Op.getValueType() == MVT::v8i16) {
8173     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8174
8175     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8176
8177     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8178                             LHS, RHS, Zero, DAG, dl);
8179   } else if (Op.getValueType() == MVT::v16i8) {
8180     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8181     bool isLittleEndian = Subtarget.isLittleEndian();
8182
8183     // Multiply the even 8-bit parts, producing 16-bit sums.
8184     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8185                                            LHS, RHS, DAG, dl, MVT::v8i16);
8186     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8187
8188     // Multiply the odd 8-bit parts, producing 16-bit sums.
8189     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8190                                           LHS, RHS, DAG, dl, MVT::v8i16);
8191     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8192
8193     // Merge the results together.  Because vmuleub and vmuloub are
8194     // instructions with a big-endian bias, we must reverse the
8195     // element numbering and reverse the meaning of "odd" and "even"
8196     // when generating little endian code.
8197     int Ops[16];
8198     for (unsigned i = 0; i != 8; ++i) {
8199       if (isLittleEndian) {
8200         Ops[i*2  ] = 2*i;
8201         Ops[i*2+1] = 2*i+16;
8202       } else {
8203         Ops[i*2  ] = 2*i+1;
8204         Ops[i*2+1] = 2*i+1+16;
8205       }
8206     }
8207     if (isLittleEndian)
8208       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8209     else
8210       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8211   } else {
8212     llvm_unreachable("Unknown mul to lower!");
8213   }
8214 }
8215
8216 /// LowerOperation - Provide custom lowering hooks for some operations.
8217 ///
8218 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8219   switch (Op.getOpcode()) {
8220   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8221   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8222   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8223   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8224   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8225   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8226   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8227   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8228   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8229   case ISD::VASTART:
8230     return LowerVASTART(Op, DAG);
8231
8232   case ISD::VAARG:
8233     return LowerVAARG(Op, DAG);
8234
8235   case ISD::VACOPY:
8236     return LowerVACOPY(Op, DAG);
8237
8238   case ISD::STACKRESTORE:
8239     return LowerSTACKRESTORE(Op, DAG);
8240
8241   case ISD::DYNAMIC_STACKALLOC:
8242     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8243
8244   case ISD::GET_DYNAMIC_AREA_OFFSET:
8245     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8246
8247   case ISD::EH_DWARF_CFA:
8248     return LowerEH_DWARF_CFA(Op, DAG);
8249
8250   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8251   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8252
8253   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8254   case ISD::STORE:              return LowerSTORE(Op, DAG);
8255   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8256   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8257   case ISD::FP_TO_UINT:
8258   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8259                                                       SDLoc(Op));
8260   case ISD::UINT_TO_FP:
8261   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8262   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8263
8264   // Lower 64-bit shifts.
8265   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8266   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8267   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8268
8269   // Vector-related lowering.
8270   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8271   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8272   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8273   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8274   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8275   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8276   case ISD::MUL:                return LowerMUL(Op, DAG);
8277
8278   // For counter-based loop handling.
8279   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8280
8281   // Frame & Return address.
8282   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8283   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8284   }
8285 }
8286
8287 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8288                                            SmallVectorImpl<SDValue>&Results,
8289                                            SelectionDAG &DAG) const {
8290   SDLoc dl(N);
8291   switch (N->getOpcode()) {
8292   default:
8293     llvm_unreachable("Do not know how to custom type legalize this operation!");
8294   case ISD::READCYCLECOUNTER: {
8295     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8296     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8297
8298     Results.push_back(RTB);
8299     Results.push_back(RTB.getValue(1));
8300     Results.push_back(RTB.getValue(2));
8301     break;
8302   }
8303   case ISD::INTRINSIC_W_CHAIN: {
8304     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8305         Intrinsic::ppc_is_decremented_ctr_nonzero)
8306       break;
8307
8308     assert(N->getValueType(0) == MVT::i1 &&
8309            "Unexpected result type for CTR decrement intrinsic");
8310     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8311                                  N->getValueType(0));
8312     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8313     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8314                                  N->getOperand(1));
8315
8316     Results.push_back(NewInt);
8317     Results.push_back(NewInt.getValue(1));
8318     break;
8319   }
8320   case ISD::VAARG: {
8321     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8322       return;
8323
8324     EVT VT = N->getValueType(0);
8325
8326     if (VT == MVT::i64) {
8327       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8328
8329       Results.push_back(NewNode);
8330       Results.push_back(NewNode.getValue(1));
8331     }
8332     return;
8333   }
8334   case ISD::FP_ROUND_INREG: {
8335     assert(N->getValueType(0) == MVT::ppcf128);
8336     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8337     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8338                              MVT::f64, N->getOperand(0),
8339                              DAG.getIntPtrConstant(0, dl));
8340     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8341                              MVT::f64, N->getOperand(0),
8342                              DAG.getIntPtrConstant(1, dl));
8343
8344     // Add the two halves of the long double in round-to-zero mode.
8345     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8346
8347     // We know the low half is about to be thrown away, so just use something
8348     // convenient.
8349     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8350                                 FPreg, FPreg));
8351     return;
8352   }
8353   case ISD::FP_TO_SINT:
8354   case ISD::FP_TO_UINT:
8355     // LowerFP_TO_INT() can only handle f32 and f64.
8356     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8357       return;
8358     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8359     return;
8360   }
8361 }
8362
8363 //===----------------------------------------------------------------------===//
8364 //  Other Lowering Code
8365 //===----------------------------------------------------------------------===//
8366
8367 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8368   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8369   Function *Func = Intrinsic::getDeclaration(M, Id);
8370   return Builder.CreateCall(Func, {});
8371 }
8372
8373 // The mappings for emitLeading/TrailingFence is taken from
8374 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8375 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8376                                          AtomicOrdering Ord, bool IsStore,
8377                                          bool IsLoad) const {
8378   if (Ord == AtomicOrdering::SequentiallyConsistent)
8379     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8380   if (isReleaseOrStronger(Ord))
8381     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8382   return nullptr;
8383 }
8384
8385 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8386                                           AtomicOrdering Ord, bool IsStore,
8387                                           bool IsLoad) const {
8388   if (IsLoad && isAcquireOrStronger(Ord))
8389     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8390   // FIXME: this is too conservative, a dependent branch + isync is enough.
8391   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8392   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8393   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8394   return nullptr;
8395 }
8396
8397 MachineBasicBlock *
8398 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8399                                     unsigned AtomicSize,
8400                                     unsigned BinOpcode) const {
8401   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8402   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8403
8404   auto LoadMnemonic = PPC::LDARX;
8405   auto StoreMnemonic = PPC::STDCX;
8406   switch (AtomicSize) {
8407   default:
8408     llvm_unreachable("Unexpected size of atomic entity");
8409   case 1:
8410     LoadMnemonic = PPC::LBARX;
8411     StoreMnemonic = PPC::STBCX;
8412     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8413     break;
8414   case 2:
8415     LoadMnemonic = PPC::LHARX;
8416     StoreMnemonic = PPC::STHCX;
8417     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8418     break;
8419   case 4:
8420     LoadMnemonic = PPC::LWARX;
8421     StoreMnemonic = PPC::STWCX;
8422     break;
8423   case 8:
8424     LoadMnemonic = PPC::LDARX;
8425     StoreMnemonic = PPC::STDCX;
8426     break;
8427   }
8428
8429   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8430   MachineFunction *F = BB->getParent();
8431   MachineFunction::iterator It = ++BB->getIterator();
8432
8433   unsigned dest = MI.getOperand(0).getReg();
8434   unsigned ptrA = MI.getOperand(1).getReg();
8435   unsigned ptrB = MI.getOperand(2).getReg();
8436   unsigned incr = MI.getOperand(3).getReg();
8437   DebugLoc dl = MI.getDebugLoc();
8438
8439   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8440   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8441   F->insert(It, loopMBB);
8442   F->insert(It, exitMBB);
8443   exitMBB->splice(exitMBB->begin(), BB,
8444                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8445   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8446
8447   MachineRegisterInfo &RegInfo = F->getRegInfo();
8448   unsigned TmpReg = (!BinOpcode) ? incr :
8449     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8450                                            : &PPC::GPRCRegClass);
8451
8452   //  thisMBB:
8453   //   ...
8454   //   fallthrough --> loopMBB
8455   BB->addSuccessor(loopMBB);
8456
8457   //  loopMBB:
8458   //   l[wd]arx dest, ptr
8459   //   add r0, dest, incr
8460   //   st[wd]cx. r0, ptr
8461   //   bne- loopMBB
8462   //   fallthrough --> exitMBB
8463   BB = loopMBB;
8464   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8465     .addReg(ptrA).addReg(ptrB);
8466   if (BinOpcode)
8467     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8468   BuildMI(BB, dl, TII->get(StoreMnemonic))
8469     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8470   BuildMI(BB, dl, TII->get(PPC::BCC))
8471     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8472   BB->addSuccessor(loopMBB);
8473   BB->addSuccessor(exitMBB);
8474
8475   //  exitMBB:
8476   //   ...
8477   BB = exitMBB;
8478   return BB;
8479 }
8480
8481 MachineBasicBlock *
8482 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8483                                             MachineBasicBlock *BB,
8484                                             bool is8bit, // operation
8485                                             unsigned BinOpcode) const {
8486   // If we support part-word atomic mnemonics, just use them
8487   if (Subtarget.hasPartwordAtomics())
8488     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8489
8490   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8491   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8492   // In 64 bit mode we have to use 64 bits for addresses, even though the
8493   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8494   // registers without caring whether they're 32 or 64, but here we're
8495   // doing actual arithmetic on the addresses.
8496   bool is64bit = Subtarget.isPPC64();
8497   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8498
8499   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8500   MachineFunction *F = BB->getParent();
8501   MachineFunction::iterator It = ++BB->getIterator();
8502
8503   unsigned dest = MI.getOperand(0).getReg();
8504   unsigned ptrA = MI.getOperand(1).getReg();
8505   unsigned ptrB = MI.getOperand(2).getReg();
8506   unsigned incr = MI.getOperand(3).getReg();
8507   DebugLoc dl = MI.getDebugLoc();
8508
8509   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8510   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8511   F->insert(It, loopMBB);
8512   F->insert(It, exitMBB);
8513   exitMBB->splice(exitMBB->begin(), BB,
8514                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8515   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8516
8517   MachineRegisterInfo &RegInfo = F->getRegInfo();
8518   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8519                                           : &PPC::GPRCRegClass;
8520   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8521   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8522   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8523   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8524   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8525   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8526   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8527   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8528   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8529   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8530   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8531   unsigned Ptr1Reg;
8532   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8533
8534   //  thisMBB:
8535   //   ...
8536   //   fallthrough --> loopMBB
8537   BB->addSuccessor(loopMBB);
8538
8539   // The 4-byte load must be aligned, while a char or short may be
8540   // anywhere in the word.  Hence all this nasty bookkeeping code.
8541   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8542   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8543   //   xori shift, shift1, 24 [16]
8544   //   rlwinm ptr, ptr1, 0, 0, 29
8545   //   slw incr2, incr, shift
8546   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8547   //   slw mask, mask2, shift
8548   //  loopMBB:
8549   //   lwarx tmpDest, ptr
8550   //   add tmp, tmpDest, incr2
8551   //   andc tmp2, tmpDest, mask
8552   //   and tmp3, tmp, mask
8553   //   or tmp4, tmp3, tmp2
8554   //   stwcx. tmp4, ptr
8555   //   bne- loopMBB
8556   //   fallthrough --> exitMBB
8557   //   srw dest, tmpDest, shift
8558   if (ptrA != ZeroReg) {
8559     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8560     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8561       .addReg(ptrA).addReg(ptrB);
8562   } else {
8563     Ptr1Reg = ptrB;
8564   }
8565   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8566       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8567   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8568       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8569   if (is64bit)
8570     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8571       .addReg(Ptr1Reg).addImm(0).addImm(61);
8572   else
8573     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8574       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8575   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8576       .addReg(incr).addReg(ShiftReg);
8577   if (is8bit)
8578     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8579   else {
8580     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8581     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8582   }
8583   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8584       .addReg(Mask2Reg).addReg(ShiftReg);
8585
8586   BB = loopMBB;
8587   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8588     .addReg(ZeroReg).addReg(PtrReg);
8589   if (BinOpcode)
8590     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8591       .addReg(Incr2Reg).addReg(TmpDestReg);
8592   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8593     .addReg(TmpDestReg).addReg(MaskReg);
8594   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8595     .addReg(TmpReg).addReg(MaskReg);
8596   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8597     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8598   BuildMI(BB, dl, TII->get(PPC::STWCX))
8599     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8600   BuildMI(BB, dl, TII->get(PPC::BCC))
8601     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8602   BB->addSuccessor(loopMBB);
8603   BB->addSuccessor(exitMBB);
8604
8605   //  exitMBB:
8606   //   ...
8607   BB = exitMBB;
8608   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8609     .addReg(ShiftReg);
8610   return BB;
8611 }
8612
8613 llvm::MachineBasicBlock *
8614 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
8615                                     MachineBasicBlock *MBB) const {
8616   DebugLoc DL = MI.getDebugLoc();
8617   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8618
8619   MachineFunction *MF = MBB->getParent();
8620   MachineRegisterInfo &MRI = MF->getRegInfo();
8621
8622   const BasicBlock *BB = MBB->getBasicBlock();
8623   MachineFunction::iterator I = ++MBB->getIterator();
8624
8625   // Memory Reference
8626   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8627   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8628
8629   unsigned DstReg = MI.getOperand(0).getReg();
8630   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8631   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8632   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8633   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8634
8635   MVT PVT = getPointerTy(MF->getDataLayout());
8636   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8637          "Invalid Pointer Size!");
8638   // For v = setjmp(buf), we generate
8639   //
8640   // thisMBB:
8641   //  SjLjSetup mainMBB
8642   //  bl mainMBB
8643   //  v_restore = 1
8644   //  b sinkMBB
8645   //
8646   // mainMBB:
8647   //  buf[LabelOffset] = LR
8648   //  v_main = 0
8649   //
8650   // sinkMBB:
8651   //  v = phi(main, restore)
8652   //
8653
8654   MachineBasicBlock *thisMBB = MBB;
8655   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8656   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8657   MF->insert(I, mainMBB);
8658   MF->insert(I, sinkMBB);
8659
8660   MachineInstrBuilder MIB;
8661
8662   // Transfer the remainder of BB and its successor edges to sinkMBB.
8663   sinkMBB->splice(sinkMBB->begin(), MBB,
8664                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8665   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8666
8667   // Note that the structure of the jmp_buf used here is not compatible
8668   // with that used by libc, and is not designed to be. Specifically, it
8669   // stores only those 'reserved' registers that LLVM does not otherwise
8670   // understand how to spill. Also, by convention, by the time this
8671   // intrinsic is called, Clang has already stored the frame address in the
8672   // first slot of the buffer and stack address in the third. Following the
8673   // X86 target code, we'll store the jump address in the second slot. We also
8674   // need to save the TOC pointer (R2) to handle jumps between shared
8675   // libraries, and that will be stored in the fourth slot. The thread
8676   // identifier (R13) is not affected.
8677
8678   // thisMBB:
8679   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8680   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8681   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8682
8683   // Prepare IP either in reg.
8684   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8685   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8686   unsigned BufReg = MI.getOperand(1).getReg();
8687
8688   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8689     setUsesTOCBasePtr(*MBB->getParent());
8690     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8691             .addReg(PPC::X2)
8692             .addImm(TOCOffset)
8693             .addReg(BufReg);
8694     MIB.setMemRefs(MMOBegin, MMOEnd);
8695   }
8696
8697   // Naked functions never have a base pointer, and so we use r1. For all
8698   // other functions, this decision must be delayed until during PEI.
8699   unsigned BaseReg;
8700   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8701     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8702   else
8703     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8704
8705   MIB = BuildMI(*thisMBB, MI, DL,
8706                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8707             .addReg(BaseReg)
8708             .addImm(BPOffset)
8709             .addReg(BufReg);
8710   MIB.setMemRefs(MMOBegin, MMOEnd);
8711
8712   // Setup
8713   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8714   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8715   MIB.addRegMask(TRI->getNoPreservedMask());
8716
8717   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8718
8719   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8720           .addMBB(mainMBB);
8721   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8722
8723   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8724   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8725
8726   // mainMBB:
8727   //  mainDstReg = 0
8728   MIB =
8729       BuildMI(mainMBB, DL,
8730               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8731
8732   // Store IP
8733   if (Subtarget.isPPC64()) {
8734     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8735             .addReg(LabelReg)
8736             .addImm(LabelOffset)
8737             .addReg(BufReg);
8738   } else {
8739     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8740             .addReg(LabelReg)
8741             .addImm(LabelOffset)
8742             .addReg(BufReg);
8743   }
8744
8745   MIB.setMemRefs(MMOBegin, MMOEnd);
8746
8747   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8748   mainMBB->addSuccessor(sinkMBB);
8749
8750   // sinkMBB:
8751   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8752           TII->get(PPC::PHI), DstReg)
8753     .addReg(mainDstReg).addMBB(mainMBB)
8754     .addReg(restoreDstReg).addMBB(thisMBB);
8755
8756   MI.eraseFromParent();
8757   return sinkMBB;
8758 }
8759
8760 MachineBasicBlock *
8761 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
8762                                      MachineBasicBlock *MBB) const {
8763   DebugLoc DL = MI.getDebugLoc();
8764   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8765
8766   MachineFunction *MF = MBB->getParent();
8767   MachineRegisterInfo &MRI = MF->getRegInfo();
8768
8769   // Memory Reference
8770   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8771   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8772
8773   MVT PVT = getPointerTy(MF->getDataLayout());
8774   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8775          "Invalid Pointer Size!");
8776
8777   const TargetRegisterClass *RC =
8778     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8779   unsigned Tmp = MRI.createVirtualRegister(RC);
8780   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8781   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8782   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8783   unsigned BP =
8784       (PVT == MVT::i64)
8785           ? PPC::X30
8786           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
8787                                                               : PPC::R30);
8788
8789   MachineInstrBuilder MIB;
8790
8791   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8792   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8793   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8794   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8795
8796   unsigned BufReg = MI.getOperand(0).getReg();
8797
8798   // Reload FP (the jumped-to function may not have had a
8799   // frame pointer, and if so, then its r31 will be restored
8800   // as necessary).
8801   if (PVT == MVT::i64) {
8802     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8803             .addImm(0)
8804             .addReg(BufReg);
8805   } else {
8806     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8807             .addImm(0)
8808             .addReg(BufReg);
8809   }
8810   MIB.setMemRefs(MMOBegin, MMOEnd);
8811
8812   // Reload IP
8813   if (PVT == MVT::i64) {
8814     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8815             .addImm(LabelOffset)
8816             .addReg(BufReg);
8817   } else {
8818     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8819             .addImm(LabelOffset)
8820             .addReg(BufReg);
8821   }
8822   MIB.setMemRefs(MMOBegin, MMOEnd);
8823
8824   // Reload SP
8825   if (PVT == MVT::i64) {
8826     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8827             .addImm(SPOffset)
8828             .addReg(BufReg);
8829   } else {
8830     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8831             .addImm(SPOffset)
8832             .addReg(BufReg);
8833   }
8834   MIB.setMemRefs(MMOBegin, MMOEnd);
8835
8836   // Reload BP
8837   if (PVT == MVT::i64) {
8838     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8839             .addImm(BPOffset)
8840             .addReg(BufReg);
8841   } else {
8842     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8843             .addImm(BPOffset)
8844             .addReg(BufReg);
8845   }
8846   MIB.setMemRefs(MMOBegin, MMOEnd);
8847
8848   // Reload TOC
8849   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8850     setUsesTOCBasePtr(*MBB->getParent());
8851     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8852             .addImm(TOCOffset)
8853             .addReg(BufReg);
8854
8855     MIB.setMemRefs(MMOBegin, MMOEnd);
8856   }
8857
8858   // Jump
8859   BuildMI(*MBB, MI, DL,
8860           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8861   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8862
8863   MI.eraseFromParent();
8864   return MBB;
8865 }
8866
8867 MachineBasicBlock *
8868 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8869                                                MachineBasicBlock *BB) const {
8870   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
8871       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8872     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8873         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8874       // Call lowering should have added an r2 operand to indicate a dependence
8875       // on the TOC base pointer value. It can't however, because there is no
8876       // way to mark the dependence as implicit there, and so the stackmap code
8877       // will confuse it with a regular operand. Instead, add the dependence
8878       // here.
8879       setUsesTOCBasePtr(*BB->getParent());
8880       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8881     }
8882
8883     return emitPatchPoint(MI, BB);
8884   }
8885
8886   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8887       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
8888     return emitEHSjLjSetJmp(MI, BB);
8889   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8890              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
8891     return emitEHSjLjLongJmp(MI, BB);
8892   }
8893
8894   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8895
8896   // To "insert" these instructions we actually have to insert their
8897   // control-flow patterns.
8898   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8899   MachineFunction::iterator It = ++BB->getIterator();
8900
8901   MachineFunction *F = BB->getParent();
8902
8903   if (Subtarget.hasISEL() &&
8904       (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8905        MI.getOpcode() == PPC::SELECT_CC_I8 ||
8906        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
8907     SmallVector<MachineOperand, 2> Cond;
8908     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8909         MI.getOpcode() == PPC::SELECT_CC_I8)
8910       Cond.push_back(MI.getOperand(4));
8911     else
8912       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8913     Cond.push_back(MI.getOperand(1));
8914
8915     DebugLoc dl = MI.getDebugLoc();
8916     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
8917                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
8918   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8919              MI.getOpcode() == PPC::SELECT_CC_I8 ||
8920              MI.getOpcode() == PPC::SELECT_CC_F4 ||
8921              MI.getOpcode() == PPC::SELECT_CC_F8 ||
8922              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
8923              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
8924              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
8925              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
8926              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
8927              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
8928              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
8929              MI.getOpcode() == PPC::SELECT_I4 ||
8930              MI.getOpcode() == PPC::SELECT_I8 ||
8931              MI.getOpcode() == PPC::SELECT_F4 ||
8932              MI.getOpcode() == PPC::SELECT_F8 ||
8933              MI.getOpcode() == PPC::SELECT_QFRC ||
8934              MI.getOpcode() == PPC::SELECT_QSRC ||
8935              MI.getOpcode() == PPC::SELECT_QBRC ||
8936              MI.getOpcode() == PPC::SELECT_VRRC ||
8937              MI.getOpcode() == PPC::SELECT_VSFRC ||
8938              MI.getOpcode() == PPC::SELECT_VSSRC ||
8939              MI.getOpcode() == PPC::SELECT_VSRC) {
8940     // The incoming instruction knows the destination vreg to set, the
8941     // condition code register to branch on, the true/false values to
8942     // select between, and a branch opcode to use.
8943
8944     //  thisMBB:
8945     //  ...
8946     //   TrueVal = ...
8947     //   cmpTY ccX, r1, r2
8948     //   bCC copy1MBB
8949     //   fallthrough --> copy0MBB
8950     MachineBasicBlock *thisMBB = BB;
8951     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8952     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8953     DebugLoc dl = MI.getDebugLoc();
8954     F->insert(It, copy0MBB);
8955     F->insert(It, sinkMBB);
8956
8957     // Transfer the remainder of BB and its successor edges to sinkMBB.
8958     sinkMBB->splice(sinkMBB->begin(), BB,
8959                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8960     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8961
8962     // Next, add the true and fallthrough blocks as its successors.
8963     BB->addSuccessor(copy0MBB);
8964     BB->addSuccessor(sinkMBB);
8965
8966     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
8967         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
8968         MI.getOpcode() == PPC::SELECT_QFRC ||
8969         MI.getOpcode() == PPC::SELECT_QSRC ||
8970         MI.getOpcode() == PPC::SELECT_QBRC ||
8971         MI.getOpcode() == PPC::SELECT_VRRC ||
8972         MI.getOpcode() == PPC::SELECT_VSFRC ||
8973         MI.getOpcode() == PPC::SELECT_VSSRC ||
8974         MI.getOpcode() == PPC::SELECT_VSRC) {
8975       BuildMI(BB, dl, TII->get(PPC::BC))
8976           .addReg(MI.getOperand(1).getReg())
8977           .addMBB(sinkMBB);
8978     } else {
8979       unsigned SelectPred = MI.getOperand(4).getImm();
8980       BuildMI(BB, dl, TII->get(PPC::BCC))
8981           .addImm(SelectPred)
8982           .addReg(MI.getOperand(1).getReg())
8983           .addMBB(sinkMBB);
8984     }
8985
8986     //  copy0MBB:
8987     //   %FalseValue = ...
8988     //   # fallthrough to sinkMBB
8989     BB = copy0MBB;
8990
8991     // Update machine-CFG edges
8992     BB->addSuccessor(sinkMBB);
8993
8994     //  sinkMBB:
8995     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8996     //  ...
8997     BB = sinkMBB;
8998     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
8999         .addReg(MI.getOperand(3).getReg())
9000         .addMBB(copy0MBB)
9001         .addReg(MI.getOperand(2).getReg())
9002         .addMBB(thisMBB);
9003   } else if (MI.getOpcode() == PPC::ReadTB) {
9004     // To read the 64-bit time-base register on a 32-bit target, we read the
9005     // two halves. Should the counter have wrapped while it was being read, we
9006     // need to try again.
9007     // ...
9008     // readLoop:
9009     // mfspr Rx,TBU # load from TBU
9010     // mfspr Ry,TB  # load from TB
9011     // mfspr Rz,TBU # load from TBU
9012     // cmpw crX,Rx,Rz # check if 'old'='new'
9013     // bne readLoop   # branch if they're not equal
9014     // ...
9015
9016     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9017     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9018     DebugLoc dl = MI.getDebugLoc();
9019     F->insert(It, readMBB);
9020     F->insert(It, sinkMBB);
9021
9022     // Transfer the remainder of BB and its successor edges to sinkMBB.
9023     sinkMBB->splice(sinkMBB->begin(), BB,
9024                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9025     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9026
9027     BB->addSuccessor(readMBB);
9028     BB = readMBB;
9029
9030     MachineRegisterInfo &RegInfo = F->getRegInfo();
9031     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9032     unsigned LoReg = MI.getOperand(0).getReg();
9033     unsigned HiReg = MI.getOperand(1).getReg();
9034
9035     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9036     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9037     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9038
9039     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9040
9041     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9042       .addReg(HiReg).addReg(ReadAgainReg);
9043     BuildMI(BB, dl, TII->get(PPC::BCC))
9044       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9045
9046     BB->addSuccessor(readMBB);
9047     BB->addSuccessor(sinkMBB);
9048   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9049     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9050   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9051     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9052   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9053     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9054   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9055     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9056
9057   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9058     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9059   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9060     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9061   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9062     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9063   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9064     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9065
9066   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9067     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9068   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9069     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9070   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9071     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9072   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9073     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9074
9075   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9076     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9077   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9078     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9079   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9080     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9081   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9082     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9083
9084   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9085     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9086   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9087     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9088   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9089     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9090   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9091     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9092
9093   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9094     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9095   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9096     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9097   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9098     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9099   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9100     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9101
9102   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9103     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9104   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9105     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9106   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9107     BB = EmitAtomicBinary(MI, BB, 4, 0);
9108   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9109     BB = EmitAtomicBinary(MI, BB, 8, 0);
9110
9111   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9112            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9113            (Subtarget.hasPartwordAtomics() &&
9114             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9115            (Subtarget.hasPartwordAtomics() &&
9116             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9117     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9118
9119     auto LoadMnemonic = PPC::LDARX;
9120     auto StoreMnemonic = PPC::STDCX;
9121     switch (MI.getOpcode()) {
9122     default:
9123       llvm_unreachable("Compare and swap of unknown size");
9124     case PPC::ATOMIC_CMP_SWAP_I8:
9125       LoadMnemonic = PPC::LBARX;
9126       StoreMnemonic = PPC::STBCX;
9127       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9128       break;
9129     case PPC::ATOMIC_CMP_SWAP_I16:
9130       LoadMnemonic = PPC::LHARX;
9131       StoreMnemonic = PPC::STHCX;
9132       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9133       break;
9134     case PPC::ATOMIC_CMP_SWAP_I32:
9135       LoadMnemonic = PPC::LWARX;
9136       StoreMnemonic = PPC::STWCX;
9137       break;
9138     case PPC::ATOMIC_CMP_SWAP_I64:
9139       LoadMnemonic = PPC::LDARX;
9140       StoreMnemonic = PPC::STDCX;
9141       break;
9142     }
9143     unsigned dest = MI.getOperand(0).getReg();
9144     unsigned ptrA = MI.getOperand(1).getReg();
9145     unsigned ptrB = MI.getOperand(2).getReg();
9146     unsigned oldval = MI.getOperand(3).getReg();
9147     unsigned newval = MI.getOperand(4).getReg();
9148     DebugLoc dl = MI.getDebugLoc();
9149
9150     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9151     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9152     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9153     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9154     F->insert(It, loop1MBB);
9155     F->insert(It, loop2MBB);
9156     F->insert(It, midMBB);
9157     F->insert(It, exitMBB);
9158     exitMBB->splice(exitMBB->begin(), BB,
9159                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9160     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9161
9162     //  thisMBB:
9163     //   ...
9164     //   fallthrough --> loopMBB
9165     BB->addSuccessor(loop1MBB);
9166
9167     // loop1MBB:
9168     //   l[bhwd]arx dest, ptr
9169     //   cmp[wd] dest, oldval
9170     //   bne- midMBB
9171     // loop2MBB:
9172     //   st[bhwd]cx. newval, ptr
9173     //   bne- loopMBB
9174     //   b exitBB
9175     // midMBB:
9176     //   st[bhwd]cx. dest, ptr
9177     // exitBB:
9178     BB = loop1MBB;
9179     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9180       .addReg(ptrA).addReg(ptrB);
9181     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9182       .addReg(oldval).addReg(dest);
9183     BuildMI(BB, dl, TII->get(PPC::BCC))
9184       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9185     BB->addSuccessor(loop2MBB);
9186     BB->addSuccessor(midMBB);
9187
9188     BB = loop2MBB;
9189     BuildMI(BB, dl, TII->get(StoreMnemonic))
9190       .addReg(newval).addReg(ptrA).addReg(ptrB);
9191     BuildMI(BB, dl, TII->get(PPC::BCC))
9192       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9193     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9194     BB->addSuccessor(loop1MBB);
9195     BB->addSuccessor(exitMBB);
9196
9197     BB = midMBB;
9198     BuildMI(BB, dl, TII->get(StoreMnemonic))
9199       .addReg(dest).addReg(ptrA).addReg(ptrB);
9200     BB->addSuccessor(exitMBB);
9201
9202     //  exitMBB:
9203     //   ...
9204     BB = exitMBB;
9205   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9206              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9207     // We must use 64-bit registers for addresses when targeting 64-bit,
9208     // since we're actually doing arithmetic on them.  Other registers
9209     // can be 32-bit.
9210     bool is64bit = Subtarget.isPPC64();
9211     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9212
9213     unsigned dest = MI.getOperand(0).getReg();
9214     unsigned ptrA = MI.getOperand(1).getReg();
9215     unsigned ptrB = MI.getOperand(2).getReg();
9216     unsigned oldval = MI.getOperand(3).getReg();
9217     unsigned newval = MI.getOperand(4).getReg();
9218     DebugLoc dl = MI.getDebugLoc();
9219
9220     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9221     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9222     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9223     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9224     F->insert(It, loop1MBB);
9225     F->insert(It, loop2MBB);
9226     F->insert(It, midMBB);
9227     F->insert(It, exitMBB);
9228     exitMBB->splice(exitMBB->begin(), BB,
9229                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9230     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9231
9232     MachineRegisterInfo &RegInfo = F->getRegInfo();
9233     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9234                                             : &PPC::GPRCRegClass;
9235     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9236     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9237     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
9238     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9239     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9240     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9241     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9242     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9243     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9244     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9245     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9246     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9247     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9248     unsigned Ptr1Reg;
9249     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9250     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9251     //  thisMBB:
9252     //   ...
9253     //   fallthrough --> loopMBB
9254     BB->addSuccessor(loop1MBB);
9255
9256     // The 4-byte load must be aligned, while a char or short may be
9257     // anywhere in the word.  Hence all this nasty bookkeeping code.
9258     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9259     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9260     //   xori shift, shift1, 24 [16]
9261     //   rlwinm ptr, ptr1, 0, 0, 29
9262     //   slw newval2, newval, shift
9263     //   slw oldval2, oldval,shift
9264     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9265     //   slw mask, mask2, shift
9266     //   and newval3, newval2, mask
9267     //   and oldval3, oldval2, mask
9268     // loop1MBB:
9269     //   lwarx tmpDest, ptr
9270     //   and tmp, tmpDest, mask
9271     //   cmpw tmp, oldval3
9272     //   bne- midMBB
9273     // loop2MBB:
9274     //   andc tmp2, tmpDest, mask
9275     //   or tmp4, tmp2, newval3
9276     //   stwcx. tmp4, ptr
9277     //   bne- loop1MBB
9278     //   b exitBB
9279     // midMBB:
9280     //   stwcx. tmpDest, ptr
9281     // exitBB:
9282     //   srw dest, tmpDest, shift
9283     if (ptrA != ZeroReg) {
9284       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9285       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9286         .addReg(ptrA).addReg(ptrB);
9287     } else {
9288       Ptr1Reg = ptrB;
9289     }
9290     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9291         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9292     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9293         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9294     if (is64bit)
9295       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9296         .addReg(Ptr1Reg).addImm(0).addImm(61);
9297     else
9298       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9299         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9300     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9301         .addReg(newval).addReg(ShiftReg);
9302     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9303         .addReg(oldval).addReg(ShiftReg);
9304     if (is8bit)
9305       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9306     else {
9307       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9308       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9309         .addReg(Mask3Reg).addImm(65535);
9310     }
9311     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9312         .addReg(Mask2Reg).addReg(ShiftReg);
9313     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9314         .addReg(NewVal2Reg).addReg(MaskReg);
9315     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9316         .addReg(OldVal2Reg).addReg(MaskReg);
9317
9318     BB = loop1MBB;
9319     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9320         .addReg(ZeroReg).addReg(PtrReg);
9321     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9322         .addReg(TmpDestReg).addReg(MaskReg);
9323     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9324         .addReg(TmpReg).addReg(OldVal3Reg);
9325     BuildMI(BB, dl, TII->get(PPC::BCC))
9326         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9327     BB->addSuccessor(loop2MBB);
9328     BB->addSuccessor(midMBB);
9329
9330     BB = loop2MBB;
9331     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9332         .addReg(TmpDestReg).addReg(MaskReg);
9333     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9334         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9335     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9336         .addReg(ZeroReg).addReg(PtrReg);
9337     BuildMI(BB, dl, TII->get(PPC::BCC))
9338       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9339     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9340     BB->addSuccessor(loop1MBB);
9341     BB->addSuccessor(exitMBB);
9342
9343     BB = midMBB;
9344     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9345       .addReg(ZeroReg).addReg(PtrReg);
9346     BB->addSuccessor(exitMBB);
9347
9348     //  exitMBB:
9349     //   ...
9350     BB = exitMBB;
9351     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9352       .addReg(ShiftReg);
9353   } else if (MI.getOpcode() == PPC::FADDrtz) {
9354     // This pseudo performs an FADD with rounding mode temporarily forced
9355     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9356     // is not modeled at the SelectionDAG level.
9357     unsigned Dest = MI.getOperand(0).getReg();
9358     unsigned Src1 = MI.getOperand(1).getReg();
9359     unsigned Src2 = MI.getOperand(2).getReg();
9360     DebugLoc dl = MI.getDebugLoc();
9361
9362     MachineRegisterInfo &RegInfo = F->getRegInfo();
9363     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9364
9365     // Save FPSCR value.
9366     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9367
9368     // Set rounding mode to round-to-zero.
9369     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9370     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9371
9372     // Perform addition.
9373     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9374
9375     // Restore FPSCR value.
9376     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9377   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9378              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9379              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9380              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9381     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9382                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9383                           ? PPC::ANDIo8
9384                           : PPC::ANDIo;
9385     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9386                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9387
9388     MachineRegisterInfo &RegInfo = F->getRegInfo();
9389     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9390                                                   &PPC::GPRCRegClass :
9391                                                   &PPC::G8RCRegClass);
9392
9393     DebugLoc dl = MI.getDebugLoc();
9394     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9395         .addReg(MI.getOperand(1).getReg())
9396         .addImm(1);
9397     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9398             MI.getOperand(0).getReg())
9399         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9400   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9401     DebugLoc Dl = MI.getDebugLoc();
9402     MachineRegisterInfo &RegInfo = F->getRegInfo();
9403     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9404     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9405     return BB;
9406   } else {
9407     llvm_unreachable("Unexpected instr type to insert");
9408   }
9409
9410   MI.eraseFromParent(); // The pseudo instruction is gone now.
9411   return BB;
9412 }
9413
9414 //===----------------------------------------------------------------------===//
9415 // Target Optimization Hooks
9416 //===----------------------------------------------------------------------===//
9417
9418 static std::string getRecipOp(const char *Base, EVT VT) {
9419   std::string RecipOp(Base);
9420   if (VT.getScalarType() == MVT::f64)
9421     RecipOp += "d";
9422   else
9423     RecipOp += "f";
9424
9425   if (VT.isVector())
9426     RecipOp = "vec-" + RecipOp;
9427
9428   return RecipOp;
9429 }
9430
9431 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9432                                             DAGCombinerInfo &DCI,
9433                                             unsigned &RefinementSteps,
9434                                             bool &UseOneConstNR) const {
9435   EVT VT = Operand.getValueType();
9436   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9437       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9438       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9439       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9440       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9441       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9442     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9443     std::string RecipOp = getRecipOp("sqrt", VT);
9444     if (!Recips.isEnabled(RecipOp))
9445       return SDValue();
9446
9447     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9448     UseOneConstNR = true;
9449     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9450   }
9451   return SDValue();
9452 }
9453
9454 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9455                                             DAGCombinerInfo &DCI,
9456                                             unsigned &RefinementSteps) const {
9457   EVT VT = Operand.getValueType();
9458   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9459       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9460       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9461       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9462       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9463       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9464     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9465     std::string RecipOp = getRecipOp("div", VT);
9466     if (!Recips.isEnabled(RecipOp))
9467       return SDValue();
9468
9469     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9470     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9471   }
9472   return SDValue();
9473 }
9474
9475 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9476   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9477   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9478   // enabled for division), this functionality is redundant with the default
9479   // combiner logic (once the division -> reciprocal/multiply transformation
9480   // has taken place). As a result, this matters more for older cores than for
9481   // newer ones.
9482
9483   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9484   // reciprocal if there are two or more FDIVs (for embedded cores with only
9485   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9486   switch (Subtarget.getDarwinDirective()) {
9487   default:
9488     return 3;
9489   case PPC::DIR_440:
9490   case PPC::DIR_A2:
9491   case PPC::DIR_E500mc:
9492   case PPC::DIR_E5500:
9493     return 2;
9494   }
9495 }
9496
9497 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9498 // collapsed, and so we need to look through chains of them.
9499 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9500                                      int64_t& Offset, SelectionDAG &DAG) {
9501   if (DAG.isBaseWithConstantOffset(Loc)) {
9502     Base = Loc.getOperand(0);
9503     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9504
9505     // The base might itself be a base plus an offset, and if so, accumulate
9506     // that as well.
9507     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9508   }
9509 }
9510
9511 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9512                             unsigned Bytes, int Dist,
9513                             SelectionDAG &DAG) {
9514   if (VT.getSizeInBits() / 8 != Bytes)
9515     return false;
9516
9517   SDValue BaseLoc = Base->getBasePtr();
9518   if (Loc.getOpcode() == ISD::FrameIndex) {
9519     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9520       return false;
9521     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9522     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9523     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9524     int FS  = MFI->getObjectSize(FI);
9525     int BFS = MFI->getObjectSize(BFI);
9526     if (FS != BFS || FS != (int)Bytes) return false;
9527     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9528   }
9529
9530   SDValue Base1 = Loc, Base2 = BaseLoc;
9531   int64_t Offset1 = 0, Offset2 = 0;
9532   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9533   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9534   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9535     return true;
9536
9537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9538   const GlobalValue *GV1 = nullptr;
9539   const GlobalValue *GV2 = nullptr;
9540   Offset1 = 0;
9541   Offset2 = 0;
9542   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9543   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9544   if (isGA1 && isGA2 && GV1 == GV2)
9545     return Offset1 == (Offset2 + Dist*Bytes);
9546   return false;
9547 }
9548
9549 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9550 // not enforce equality of the chain operands.
9551 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9552                             unsigned Bytes, int Dist,
9553                             SelectionDAG &DAG) {
9554   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9555     EVT VT = LS->getMemoryVT();
9556     SDValue Loc = LS->getBasePtr();
9557     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9558   }
9559
9560   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9561     EVT VT;
9562     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9563     default: return false;
9564     case Intrinsic::ppc_qpx_qvlfd:
9565     case Intrinsic::ppc_qpx_qvlfda:
9566       VT = MVT::v4f64;
9567       break;
9568     case Intrinsic::ppc_qpx_qvlfs:
9569     case Intrinsic::ppc_qpx_qvlfsa:
9570       VT = MVT::v4f32;
9571       break;
9572     case Intrinsic::ppc_qpx_qvlfcd:
9573     case Intrinsic::ppc_qpx_qvlfcda:
9574       VT = MVT::v2f64;
9575       break;
9576     case Intrinsic::ppc_qpx_qvlfcs:
9577     case Intrinsic::ppc_qpx_qvlfcsa:
9578       VT = MVT::v2f32;
9579       break;
9580     case Intrinsic::ppc_qpx_qvlfiwa:
9581     case Intrinsic::ppc_qpx_qvlfiwz:
9582     case Intrinsic::ppc_altivec_lvx:
9583     case Intrinsic::ppc_altivec_lvxl:
9584     case Intrinsic::ppc_vsx_lxvw4x:
9585       VT = MVT::v4i32;
9586       break;
9587     case Intrinsic::ppc_vsx_lxvd2x:
9588       VT = MVT::v2f64;
9589       break;
9590     case Intrinsic::ppc_altivec_lvebx:
9591       VT = MVT::i8;
9592       break;
9593     case Intrinsic::ppc_altivec_lvehx:
9594       VT = MVT::i16;
9595       break;
9596     case Intrinsic::ppc_altivec_lvewx:
9597       VT = MVT::i32;
9598       break;
9599     }
9600
9601     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9602   }
9603
9604   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9605     EVT VT;
9606     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9607     default: return false;
9608     case Intrinsic::ppc_qpx_qvstfd:
9609     case Intrinsic::ppc_qpx_qvstfda:
9610       VT = MVT::v4f64;
9611       break;
9612     case Intrinsic::ppc_qpx_qvstfs:
9613     case Intrinsic::ppc_qpx_qvstfsa:
9614       VT = MVT::v4f32;
9615       break;
9616     case Intrinsic::ppc_qpx_qvstfcd:
9617     case Intrinsic::ppc_qpx_qvstfcda:
9618       VT = MVT::v2f64;
9619       break;
9620     case Intrinsic::ppc_qpx_qvstfcs:
9621     case Intrinsic::ppc_qpx_qvstfcsa:
9622       VT = MVT::v2f32;
9623       break;
9624     case Intrinsic::ppc_qpx_qvstfiw:
9625     case Intrinsic::ppc_qpx_qvstfiwa:
9626     case Intrinsic::ppc_altivec_stvx:
9627     case Intrinsic::ppc_altivec_stvxl:
9628     case Intrinsic::ppc_vsx_stxvw4x:
9629       VT = MVT::v4i32;
9630       break;
9631     case Intrinsic::ppc_vsx_stxvd2x:
9632       VT = MVT::v2f64;
9633       break;
9634     case Intrinsic::ppc_altivec_stvebx:
9635       VT = MVT::i8;
9636       break;
9637     case Intrinsic::ppc_altivec_stvehx:
9638       VT = MVT::i16;
9639       break;
9640     case Intrinsic::ppc_altivec_stvewx:
9641       VT = MVT::i32;
9642       break;
9643     }
9644
9645     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9646   }
9647
9648   return false;
9649 }
9650
9651 // Return true is there is a nearyby consecutive load to the one provided
9652 // (regardless of alignment). We search up and down the chain, looking though
9653 // token factors and other loads (but nothing else). As a result, a true result
9654 // indicates that it is safe to create a new consecutive load adjacent to the
9655 // load provided.
9656 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9657   SDValue Chain = LD->getChain();
9658   EVT VT = LD->getMemoryVT();
9659
9660   SmallSet<SDNode *, 16> LoadRoots;
9661   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9662   SmallSet<SDNode *, 16> Visited;
9663
9664   // First, search up the chain, branching to follow all token-factor operands.
9665   // If we find a consecutive load, then we're done, otherwise, record all
9666   // nodes just above the top-level loads and token factors.
9667   while (!Queue.empty()) {
9668     SDNode *ChainNext = Queue.pop_back_val();
9669     if (!Visited.insert(ChainNext).second)
9670       continue;
9671
9672     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9673       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9674         return true;
9675
9676       if (!Visited.count(ChainLD->getChain().getNode()))
9677         Queue.push_back(ChainLD->getChain().getNode());
9678     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9679       for (const SDUse &O : ChainNext->ops())
9680         if (!Visited.count(O.getNode()))
9681           Queue.push_back(O.getNode());
9682     } else
9683       LoadRoots.insert(ChainNext);
9684   }
9685
9686   // Second, search down the chain, starting from the top-level nodes recorded
9687   // in the first phase. These top-level nodes are the nodes just above all
9688   // loads and token factors. Starting with their uses, recursively look though
9689   // all loads (just the chain uses) and token factors to find a consecutive
9690   // load.
9691   Visited.clear();
9692   Queue.clear();
9693
9694   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9695        IE = LoadRoots.end(); I != IE; ++I) {
9696     Queue.push_back(*I);
9697
9698     while (!Queue.empty()) {
9699       SDNode *LoadRoot = Queue.pop_back_val();
9700       if (!Visited.insert(LoadRoot).second)
9701         continue;
9702
9703       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9704         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9705           return true;
9706
9707       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9708            UE = LoadRoot->use_end(); UI != UE; ++UI)
9709         if (((isa<MemSDNode>(*UI) &&
9710             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9711             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9712           Queue.push_back(*UI);
9713     }
9714   }
9715
9716   return false;
9717 }
9718
9719 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9720                                                   DAGCombinerInfo &DCI) const {
9721   SelectionDAG &DAG = DCI.DAG;
9722   SDLoc dl(N);
9723
9724   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9725   // If we're tracking CR bits, we need to be careful that we don't have:
9726   //   trunc(binary-ops(zext(x), zext(y)))
9727   // or
9728   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9729   // such that we're unnecessarily moving things into GPRs when it would be
9730   // better to keep them in CR bits.
9731
9732   // Note that trunc here can be an actual i1 trunc, or can be the effective
9733   // truncation that comes from a setcc or select_cc.
9734   if (N->getOpcode() == ISD::TRUNCATE &&
9735       N->getValueType(0) != MVT::i1)
9736     return SDValue();
9737
9738   if (N->getOperand(0).getValueType() != MVT::i32 &&
9739       N->getOperand(0).getValueType() != MVT::i64)
9740     return SDValue();
9741
9742   if (N->getOpcode() == ISD::SETCC ||
9743       N->getOpcode() == ISD::SELECT_CC) {
9744     // If we're looking at a comparison, then we need to make sure that the
9745     // high bits (all except for the first) don't matter the result.
9746     ISD::CondCode CC =
9747       cast<CondCodeSDNode>(N->getOperand(
9748         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9749     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9750
9751     if (ISD::isSignedIntSetCC(CC)) {
9752       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9753           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9754         return SDValue();
9755     } else if (ISD::isUnsignedIntSetCC(CC)) {
9756       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9757                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9758           !DAG.MaskedValueIsZero(N->getOperand(1),
9759                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9760         return SDValue();
9761     } else {
9762       // This is neither a signed nor an unsigned comparison, just make sure
9763       // that the high bits are equal.
9764       APInt Op1Zero, Op1One;
9765       APInt Op2Zero, Op2One;
9766       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9767       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9768
9769       // We don't really care about what is known about the first bit (if
9770       // anything), so clear it in all masks prior to comparing them.
9771       Op1Zero.clearBit(0); Op1One.clearBit(0);
9772       Op2Zero.clearBit(0); Op2One.clearBit(0);
9773
9774       if (Op1Zero != Op2Zero || Op1One != Op2One)
9775         return SDValue();
9776     }
9777   }
9778
9779   // We now know that the higher-order bits are irrelevant, we just need to
9780   // make sure that all of the intermediate operations are bit operations, and
9781   // all inputs are extensions.
9782   if (N->getOperand(0).getOpcode() != ISD::AND &&
9783       N->getOperand(0).getOpcode() != ISD::OR  &&
9784       N->getOperand(0).getOpcode() != ISD::XOR &&
9785       N->getOperand(0).getOpcode() != ISD::SELECT &&
9786       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9787       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9788       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9789       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9790       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9791     return SDValue();
9792
9793   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9794       N->getOperand(1).getOpcode() != ISD::AND &&
9795       N->getOperand(1).getOpcode() != ISD::OR  &&
9796       N->getOperand(1).getOpcode() != ISD::XOR &&
9797       N->getOperand(1).getOpcode() != ISD::SELECT &&
9798       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9799       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9800       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9801       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9802       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9803     return SDValue();
9804
9805   SmallVector<SDValue, 4> Inputs;
9806   SmallVector<SDValue, 8> BinOps, PromOps;
9807   SmallPtrSet<SDNode *, 16> Visited;
9808
9809   for (unsigned i = 0; i < 2; ++i) {
9810     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9811           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9812           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9813           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9814         isa<ConstantSDNode>(N->getOperand(i)))
9815       Inputs.push_back(N->getOperand(i));
9816     else
9817       BinOps.push_back(N->getOperand(i));
9818
9819     if (N->getOpcode() == ISD::TRUNCATE)
9820       break;
9821   }
9822
9823   // Visit all inputs, collect all binary operations (and, or, xor and
9824   // select) that are all fed by extensions.
9825   while (!BinOps.empty()) {
9826     SDValue BinOp = BinOps.back();
9827     BinOps.pop_back();
9828
9829     if (!Visited.insert(BinOp.getNode()).second)
9830       continue;
9831
9832     PromOps.push_back(BinOp);
9833
9834     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9835       // The condition of the select is not promoted.
9836       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9837         continue;
9838       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9839         continue;
9840
9841       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9842             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9843             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9844            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9845           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9846         Inputs.push_back(BinOp.getOperand(i));
9847       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9848                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9849                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9850                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9851                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9852                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9853                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9854                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9855                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9856         BinOps.push_back(BinOp.getOperand(i));
9857       } else {
9858         // We have an input that is not an extension or another binary
9859         // operation; we'll abort this transformation.
9860         return SDValue();
9861       }
9862     }
9863   }
9864
9865   // Make sure that this is a self-contained cluster of operations (which
9866   // is not quite the same thing as saying that everything has only one
9867   // use).
9868   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9869     if (isa<ConstantSDNode>(Inputs[i]))
9870       continue;
9871
9872     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9873                               UE = Inputs[i].getNode()->use_end();
9874          UI != UE; ++UI) {
9875       SDNode *User = *UI;
9876       if (User != N && !Visited.count(User))
9877         return SDValue();
9878
9879       // Make sure that we're not going to promote the non-output-value
9880       // operand(s) or SELECT or SELECT_CC.
9881       // FIXME: Although we could sometimes handle this, and it does occur in
9882       // practice that one of the condition inputs to the select is also one of
9883       // the outputs, we currently can't deal with this.
9884       if (User->getOpcode() == ISD::SELECT) {
9885         if (User->getOperand(0) == Inputs[i])
9886           return SDValue();
9887       } else if (User->getOpcode() == ISD::SELECT_CC) {
9888         if (User->getOperand(0) == Inputs[i] ||
9889             User->getOperand(1) == Inputs[i])
9890           return SDValue();
9891       }
9892     }
9893   }
9894
9895   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9896     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9897                               UE = PromOps[i].getNode()->use_end();
9898          UI != UE; ++UI) {
9899       SDNode *User = *UI;
9900       if (User != N && !Visited.count(User))
9901         return SDValue();
9902
9903       // Make sure that we're not going to promote the non-output-value
9904       // operand(s) or SELECT or SELECT_CC.
9905       // FIXME: Although we could sometimes handle this, and it does occur in
9906       // practice that one of the condition inputs to the select is also one of
9907       // the outputs, we currently can't deal with this.
9908       if (User->getOpcode() == ISD::SELECT) {
9909         if (User->getOperand(0) == PromOps[i])
9910           return SDValue();
9911       } else if (User->getOpcode() == ISD::SELECT_CC) {
9912         if (User->getOperand(0) == PromOps[i] ||
9913             User->getOperand(1) == PromOps[i])
9914           return SDValue();
9915       }
9916     }
9917   }
9918
9919   // Replace all inputs with the extension operand.
9920   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9921     // Constants may have users outside the cluster of to-be-promoted nodes,
9922     // and so we need to replace those as we do the promotions.
9923     if (isa<ConstantSDNode>(Inputs[i]))
9924       continue;
9925     else
9926       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9927   }
9928
9929   std::list<HandleSDNode> PromOpHandles;
9930   for (auto &PromOp : PromOps)
9931     PromOpHandles.emplace_back(PromOp);
9932
9933   // Replace all operations (these are all the same, but have a different
9934   // (i1) return type). DAG.getNode will validate that the types of
9935   // a binary operator match, so go through the list in reverse so that
9936   // we've likely promoted both operands first. Any intermediate truncations or
9937   // extensions disappear.
9938   while (!PromOpHandles.empty()) {
9939     SDValue PromOp = PromOpHandles.back().getValue();
9940     PromOpHandles.pop_back();
9941
9942     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9943         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9944         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9945         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9946       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9947           PromOp.getOperand(0).getValueType() != MVT::i1) {
9948         // The operand is not yet ready (see comment below).
9949         PromOpHandles.emplace_front(PromOp);
9950         continue;
9951       }
9952
9953       SDValue RepValue = PromOp.getOperand(0);
9954       if (isa<ConstantSDNode>(RepValue))
9955         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9956
9957       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9958       continue;
9959     }
9960
9961     unsigned C;
9962     switch (PromOp.getOpcode()) {
9963     default:             C = 0; break;
9964     case ISD::SELECT:    C = 1; break;
9965     case ISD::SELECT_CC: C = 2; break;
9966     }
9967
9968     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9969          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9970         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9971          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9972       // The to-be-promoted operands of this node have not yet been
9973       // promoted (this should be rare because we're going through the
9974       // list backward, but if one of the operands has several users in
9975       // this cluster of to-be-promoted nodes, it is possible).
9976       PromOpHandles.emplace_front(PromOp);
9977       continue;
9978     }
9979
9980     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9981                                 PromOp.getNode()->op_end());
9982
9983     // If there are any constant inputs, make sure they're replaced now.
9984     for (unsigned i = 0; i < 2; ++i)
9985       if (isa<ConstantSDNode>(Ops[C+i]))
9986         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9987
9988     DAG.ReplaceAllUsesOfValueWith(PromOp,
9989       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9990   }
9991
9992   // Now we're left with the initial truncation itself.
9993   if (N->getOpcode() == ISD::TRUNCATE)
9994     return N->getOperand(0);
9995
9996   // Otherwise, this is a comparison. The operands to be compared have just
9997   // changed type (to i1), but everything else is the same.
9998   return SDValue(N, 0);
9999 }
10000
10001 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10002                                                   DAGCombinerInfo &DCI) const {
10003   SelectionDAG &DAG = DCI.DAG;
10004   SDLoc dl(N);
10005
10006   // If we're tracking CR bits, we need to be careful that we don't have:
10007   //   zext(binary-ops(trunc(x), trunc(y)))
10008   // or
10009   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10010   // such that we're unnecessarily moving things into CR bits that can more
10011   // efficiently stay in GPRs. Note that if we're not certain that the high
10012   // bits are set as required by the final extension, we still may need to do
10013   // some masking to get the proper behavior.
10014
10015   // This same functionality is important on PPC64 when dealing with
10016   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10017   // the return values of functions. Because it is so similar, it is handled
10018   // here as well.
10019
10020   if (N->getValueType(0) != MVT::i32 &&
10021       N->getValueType(0) != MVT::i64)
10022     return SDValue();
10023
10024   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10025         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10026     return SDValue();
10027
10028   if (N->getOperand(0).getOpcode() != ISD::AND &&
10029       N->getOperand(0).getOpcode() != ISD::OR  &&
10030       N->getOperand(0).getOpcode() != ISD::XOR &&
10031       N->getOperand(0).getOpcode() != ISD::SELECT &&
10032       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10033     return SDValue();
10034
10035   SmallVector<SDValue, 4> Inputs;
10036   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10037   SmallPtrSet<SDNode *, 16> Visited;
10038
10039   // Visit all inputs, collect all binary operations (and, or, xor and
10040   // select) that are all fed by truncations.
10041   while (!BinOps.empty()) {
10042     SDValue BinOp = BinOps.back();
10043     BinOps.pop_back();
10044
10045     if (!Visited.insert(BinOp.getNode()).second)
10046       continue;
10047
10048     PromOps.push_back(BinOp);
10049
10050     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10051       // The condition of the select is not promoted.
10052       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10053         continue;
10054       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10055         continue;
10056
10057       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10058           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10059         Inputs.push_back(BinOp.getOperand(i));
10060       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10061                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10062                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10063                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10064                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10065         BinOps.push_back(BinOp.getOperand(i));
10066       } else {
10067         // We have an input that is not a truncation or another binary
10068         // operation; we'll abort this transformation.
10069         return SDValue();
10070       }
10071     }
10072   }
10073
10074   // The operands of a select that must be truncated when the select is
10075   // promoted because the operand is actually part of the to-be-promoted set.
10076   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10077
10078   // Make sure that this is a self-contained cluster of operations (which
10079   // is not quite the same thing as saying that everything has only one
10080   // use).
10081   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10082     if (isa<ConstantSDNode>(Inputs[i]))
10083       continue;
10084
10085     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10086                               UE = Inputs[i].getNode()->use_end();
10087          UI != UE; ++UI) {
10088       SDNode *User = *UI;
10089       if (User != N && !Visited.count(User))
10090         return SDValue();
10091
10092       // If we're going to promote the non-output-value operand(s) or SELECT or
10093       // SELECT_CC, record them for truncation.
10094       if (User->getOpcode() == ISD::SELECT) {
10095         if (User->getOperand(0) == Inputs[i])
10096           SelectTruncOp[0].insert(std::make_pair(User,
10097                                     User->getOperand(0).getValueType()));
10098       } else if (User->getOpcode() == ISD::SELECT_CC) {
10099         if (User->getOperand(0) == Inputs[i])
10100           SelectTruncOp[0].insert(std::make_pair(User,
10101                                     User->getOperand(0).getValueType()));
10102         if (User->getOperand(1) == Inputs[i])
10103           SelectTruncOp[1].insert(std::make_pair(User,
10104                                     User->getOperand(1).getValueType()));
10105       }
10106     }
10107   }
10108
10109   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10110     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10111                               UE = PromOps[i].getNode()->use_end();
10112          UI != UE; ++UI) {
10113       SDNode *User = *UI;
10114       if (User != N && !Visited.count(User))
10115         return SDValue();
10116
10117       // If we're going to promote the non-output-value operand(s) or SELECT or
10118       // SELECT_CC, record them for truncation.
10119       if (User->getOpcode() == ISD::SELECT) {
10120         if (User->getOperand(0) == PromOps[i])
10121           SelectTruncOp[0].insert(std::make_pair(User,
10122                                     User->getOperand(0).getValueType()));
10123       } else if (User->getOpcode() == ISD::SELECT_CC) {
10124         if (User->getOperand(0) == PromOps[i])
10125           SelectTruncOp[0].insert(std::make_pair(User,
10126                                     User->getOperand(0).getValueType()));
10127         if (User->getOperand(1) == PromOps[i])
10128           SelectTruncOp[1].insert(std::make_pair(User,
10129                                     User->getOperand(1).getValueType()));
10130       }
10131     }
10132   }
10133
10134   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10135   bool ReallyNeedsExt = false;
10136   if (N->getOpcode() != ISD::ANY_EXTEND) {
10137     // If all of the inputs are not already sign/zero extended, then
10138     // we'll still need to do that at the end.
10139     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10140       if (isa<ConstantSDNode>(Inputs[i]))
10141         continue;
10142
10143       unsigned OpBits =
10144         Inputs[i].getOperand(0).getValueSizeInBits();
10145       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10146
10147       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10148            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10149                                   APInt::getHighBitsSet(OpBits,
10150                                                         OpBits-PromBits))) ||
10151           (N->getOpcode() == ISD::SIGN_EXTEND &&
10152            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10153              (OpBits-(PromBits-1)))) {
10154         ReallyNeedsExt = true;
10155         break;
10156       }
10157     }
10158   }
10159
10160   // Replace all inputs, either with the truncation operand, or a
10161   // truncation or extension to the final output type.
10162   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10163     // Constant inputs need to be replaced with the to-be-promoted nodes that
10164     // use them because they might have users outside of the cluster of
10165     // promoted nodes.
10166     if (isa<ConstantSDNode>(Inputs[i]))
10167       continue;
10168
10169     SDValue InSrc = Inputs[i].getOperand(0);
10170     if (Inputs[i].getValueType() == N->getValueType(0))
10171       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10172     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10173       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10174         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10175     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10176       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10177         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10178     else
10179       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10180         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10181   }
10182
10183   std::list<HandleSDNode> PromOpHandles;
10184   for (auto &PromOp : PromOps)
10185     PromOpHandles.emplace_back(PromOp);
10186
10187   // Replace all operations (these are all the same, but have a different
10188   // (promoted) return type). DAG.getNode will validate that the types of
10189   // a binary operator match, so go through the list in reverse so that
10190   // we've likely promoted both operands first.
10191   while (!PromOpHandles.empty()) {
10192     SDValue PromOp = PromOpHandles.back().getValue();
10193     PromOpHandles.pop_back();
10194
10195     unsigned C;
10196     switch (PromOp.getOpcode()) {
10197     default:             C = 0; break;
10198     case ISD::SELECT:    C = 1; break;
10199     case ISD::SELECT_CC: C = 2; break;
10200     }
10201
10202     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10203          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10204         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10205          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10206       // The to-be-promoted operands of this node have not yet been
10207       // promoted (this should be rare because we're going through the
10208       // list backward, but if one of the operands has several users in
10209       // this cluster of to-be-promoted nodes, it is possible).
10210       PromOpHandles.emplace_front(PromOp);
10211       continue;
10212     }
10213
10214     // For SELECT and SELECT_CC nodes, we do a similar check for any
10215     // to-be-promoted comparison inputs.
10216     if (PromOp.getOpcode() == ISD::SELECT ||
10217         PromOp.getOpcode() == ISD::SELECT_CC) {
10218       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10219            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10220           (SelectTruncOp[1].count(PromOp.getNode()) &&
10221            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10222         PromOpHandles.emplace_front(PromOp);
10223         continue;
10224       }
10225     }
10226
10227     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10228                                 PromOp.getNode()->op_end());
10229
10230     // If this node has constant inputs, then they'll need to be promoted here.
10231     for (unsigned i = 0; i < 2; ++i) {
10232       if (!isa<ConstantSDNode>(Ops[C+i]))
10233         continue;
10234       if (Ops[C+i].getValueType() == N->getValueType(0))
10235         continue;
10236
10237       if (N->getOpcode() == ISD::SIGN_EXTEND)
10238         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10239       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10240         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10241       else
10242         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10243     }
10244
10245     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10246     // truncate them again to the original value type.
10247     if (PromOp.getOpcode() == ISD::SELECT ||
10248         PromOp.getOpcode() == ISD::SELECT_CC) {
10249       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10250       if (SI0 != SelectTruncOp[0].end())
10251         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10252       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10253       if (SI1 != SelectTruncOp[1].end())
10254         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10255     }
10256
10257     DAG.ReplaceAllUsesOfValueWith(PromOp,
10258       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10259   }
10260
10261   // Now we're left with the initial extension itself.
10262   if (!ReallyNeedsExt)
10263     return N->getOperand(0);
10264
10265   // To zero extend, just mask off everything except for the first bit (in the
10266   // i1 case).
10267   if (N->getOpcode() == ISD::ZERO_EXTEND)
10268     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10269                        DAG.getConstant(APInt::getLowBitsSet(
10270                                          N->getValueSizeInBits(0), PromBits),
10271                                        dl, N->getValueType(0)));
10272
10273   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10274          "Invalid extension type");
10275   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10276   SDValue ShiftCst =
10277       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10278   return DAG.getNode(
10279       ISD::SRA, dl, N->getValueType(0),
10280       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10281       ShiftCst);
10282 }
10283
10284 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
10285                                                  DAGCombinerInfo &DCI) const {
10286   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10287          "Should be called with a BUILD_VECTOR node");
10288
10289   SelectionDAG &DAG = DCI.DAG;
10290   SDLoc dl(N);
10291   if (N->getValueType(0) != MVT::v2f64 || !Subtarget.hasVSX())
10292     return SDValue();
10293
10294   // Looking for:
10295   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
10296   if (N->getOperand(0).getOpcode() != ISD::SINT_TO_FP &&
10297       N->getOperand(0).getOpcode() != ISD::UINT_TO_FP)
10298     return SDValue();
10299   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
10300       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
10301     return SDValue();
10302   if (N->getOperand(0).getOpcode() != N->getOperand(1).getOpcode())
10303     return SDValue();
10304
10305   SDValue Ext1 = N->getOperand(0).getOperand(0);
10306   SDValue Ext2 = N->getOperand(1).getOperand(0);
10307   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10308      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10309     return SDValue();
10310
10311   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
10312   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
10313   if (!Ext1Op || !Ext2Op)
10314     return SDValue();
10315   if (Ext1.getValueType() != MVT::i32 ||
10316       Ext2.getValueType() != MVT::i32)
10317   if (Ext1.getOperand(0) != Ext2.getOperand(0))
10318     return SDValue();
10319
10320   int FirstElem = Ext1Op->getZExtValue();
10321   int SecondElem = Ext2Op->getZExtValue();
10322   int SubvecIdx;
10323   if (FirstElem == 0 && SecondElem == 1)
10324     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
10325   else if (FirstElem == 2 && SecondElem == 3)
10326     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
10327   else
10328     return SDValue();
10329
10330   SDValue SrcVec = Ext1.getOperand(0);
10331   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
10332     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
10333   return DAG.getNode(NodeType, dl, MVT::v2f64,
10334                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
10335 }
10336
10337 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10338                                               DAGCombinerInfo &DCI) const {
10339   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10340           N->getOpcode() == ISD::UINT_TO_FP) &&
10341          "Need an int -> FP conversion node here");
10342
10343   if (useSoftFloat() || !Subtarget.has64BitSupport())
10344     return SDValue();
10345
10346   SelectionDAG &DAG = DCI.DAG;
10347   SDLoc dl(N);
10348   SDValue Op(N, 0);
10349
10350   // Don't handle ppc_fp128 here or i1 conversions.
10351   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10352     return SDValue();
10353   if (Op.getOperand(0).getValueType() == MVT::i1)
10354     return SDValue();
10355
10356   // For i32 intermediate values, unfortunately, the conversion functions
10357   // leave the upper 32 bits of the value are undefined. Within the set of
10358   // scalar instructions, we have no method for zero- or sign-extending the
10359   // value. Thus, we cannot handle i32 intermediate values here.
10360   if (Op.getOperand(0).getValueType() == MVT::i32)
10361     return SDValue();
10362
10363   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10364          "UINT_TO_FP is supported only with FPCVT");
10365
10366   // If we have FCFIDS, then use it when converting to single-precision.
10367   // Otherwise, convert to double-precision and then round.
10368   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10369                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10370                                                             : PPCISD::FCFIDS)
10371                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10372                                                             : PPCISD::FCFID);
10373   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10374                   ? MVT::f32
10375                   : MVT::f64;
10376
10377   // If we're converting from a float, to an int, and back to a float again,
10378   // then we don't need the store/load pair at all.
10379   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10380        Subtarget.hasFPCVT()) ||
10381       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10382     SDValue Src = Op.getOperand(0).getOperand(0);
10383     if (Src.getValueType() == MVT::f32) {
10384       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10385       DCI.AddToWorklist(Src.getNode());
10386     } else if (Src.getValueType() != MVT::f64) {
10387       // Make sure that we don't pick up a ppc_fp128 source value.
10388       return SDValue();
10389     }
10390
10391     unsigned FCTOp =
10392       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10393                                                         PPCISD::FCTIDUZ;
10394
10395     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10396     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10397
10398     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10399       FP = DAG.getNode(ISD::FP_ROUND, dl,
10400                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10401       DCI.AddToWorklist(FP.getNode());
10402     }
10403
10404     return FP;
10405   }
10406
10407   return SDValue();
10408 }
10409
10410 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10411 // builtins) into loads with swaps.
10412 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10413                                               DAGCombinerInfo &DCI) const {
10414   SelectionDAG &DAG = DCI.DAG;
10415   SDLoc dl(N);
10416   SDValue Chain;
10417   SDValue Base;
10418   MachineMemOperand *MMO;
10419
10420   switch (N->getOpcode()) {
10421   default:
10422     llvm_unreachable("Unexpected opcode for little endian VSX load");
10423   case ISD::LOAD: {
10424     LoadSDNode *LD = cast<LoadSDNode>(N);
10425     Chain = LD->getChain();
10426     Base = LD->getBasePtr();
10427     MMO = LD->getMemOperand();
10428     // If the MMO suggests this isn't a load of a full vector, leave
10429     // things alone.  For a built-in, we have to make the change for
10430     // correctness, so if there is a size problem that will be a bug.
10431     if (MMO->getSize() < 16)
10432       return SDValue();
10433     break;
10434   }
10435   case ISD::INTRINSIC_W_CHAIN: {
10436     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10437     Chain = Intrin->getChain();
10438     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10439     // us what we want. Get operand 2 instead.
10440     Base = Intrin->getOperand(2);
10441     MMO = Intrin->getMemOperand();
10442     break;
10443   }
10444   }
10445
10446   MVT VecTy = N->getValueType(0).getSimpleVT();
10447   SDValue LoadOps[] = { Chain, Base };
10448   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10449                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10450                                          LoadOps, MVT::v2f64, MMO);
10451
10452   DCI.AddToWorklist(Load.getNode());
10453   Chain = Load.getValue(1);
10454   SDValue Swap = DAG.getNode(
10455       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10456   DCI.AddToWorklist(Swap.getNode());
10457
10458   // Add a bitcast if the resulting load type doesn't match v2f64.
10459   if (VecTy != MVT::v2f64) {
10460     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10461     DCI.AddToWorklist(N.getNode());
10462     // Package {bitcast value, swap's chain} to match Load's shape.
10463     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10464                        N, Swap.getValue(1));
10465   }
10466
10467   return Swap;
10468 }
10469
10470 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10471 // builtins) into stores with swaps.
10472 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10473                                                DAGCombinerInfo &DCI) const {
10474   SelectionDAG &DAG = DCI.DAG;
10475   SDLoc dl(N);
10476   SDValue Chain;
10477   SDValue Base;
10478   unsigned SrcOpnd;
10479   MachineMemOperand *MMO;
10480
10481   switch (N->getOpcode()) {
10482   default:
10483     llvm_unreachable("Unexpected opcode for little endian VSX store");
10484   case ISD::STORE: {
10485     StoreSDNode *ST = cast<StoreSDNode>(N);
10486     Chain = ST->getChain();
10487     Base = ST->getBasePtr();
10488     MMO = ST->getMemOperand();
10489     SrcOpnd = 1;
10490     // If the MMO suggests this isn't a store of a full vector, leave
10491     // things alone.  For a built-in, we have to make the change for
10492     // correctness, so if there is a size problem that will be a bug.
10493     if (MMO->getSize() < 16)
10494       return SDValue();
10495     break;
10496   }
10497   case ISD::INTRINSIC_VOID: {
10498     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10499     Chain = Intrin->getChain();
10500     // Intrin->getBasePtr() oddly does not get what we want.
10501     Base = Intrin->getOperand(3);
10502     MMO = Intrin->getMemOperand();
10503     SrcOpnd = 2;
10504     break;
10505   }
10506   }
10507
10508   SDValue Src = N->getOperand(SrcOpnd);
10509   MVT VecTy = Src.getValueType().getSimpleVT();
10510
10511   // All stores are done as v2f64 and possible bit cast.
10512   if (VecTy != MVT::v2f64) {
10513     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10514     DCI.AddToWorklist(Src.getNode());
10515   }
10516
10517   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10518                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10519   DCI.AddToWorklist(Swap.getNode());
10520   Chain = Swap.getValue(1);
10521   SDValue StoreOps[] = { Chain, Swap, Base };
10522   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10523                                           DAG.getVTList(MVT::Other),
10524                                           StoreOps, VecTy, MMO);
10525   DCI.AddToWorklist(Store.getNode());
10526   return Store;
10527 }
10528
10529 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10530                                              DAGCombinerInfo &DCI) const {
10531   SelectionDAG &DAG = DCI.DAG;
10532   SDLoc dl(N);
10533   switch (N->getOpcode()) {
10534   default: break;
10535   case PPCISD::SHL:
10536     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10537         return N->getOperand(0);
10538     break;
10539   case PPCISD::SRL:
10540     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10541         return N->getOperand(0);
10542     break;
10543   case PPCISD::SRA:
10544     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10545       if (C->isNullValue() ||   //  0 >>s V -> 0.
10546           C->isAllOnesValue())    // -1 >>s V -> -1.
10547         return N->getOperand(0);
10548     }
10549     break;
10550   case ISD::SIGN_EXTEND:
10551   case ISD::ZERO_EXTEND:
10552   case ISD::ANY_EXTEND:
10553     return DAGCombineExtBoolTrunc(N, DCI);
10554   case ISD::TRUNCATE:
10555   case ISD::SETCC:
10556   case ISD::SELECT_CC:
10557     return DAGCombineTruncBoolExt(N, DCI);
10558   case ISD::SINT_TO_FP:
10559   case ISD::UINT_TO_FP:
10560     return combineFPToIntToFP(N, DCI);
10561   case ISD::STORE: {
10562     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10563     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10564         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10565         N->getOperand(1).getValueType() == MVT::i32 &&
10566         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10567       SDValue Val = N->getOperand(1).getOperand(0);
10568       if (Val.getValueType() == MVT::f32) {
10569         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10570         DCI.AddToWorklist(Val.getNode());
10571       }
10572       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10573       DCI.AddToWorklist(Val.getNode());
10574
10575       SDValue Ops[] = {
10576         N->getOperand(0), Val, N->getOperand(2),
10577         DAG.getValueType(N->getOperand(1).getValueType())
10578       };
10579
10580       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10581               DAG.getVTList(MVT::Other), Ops,
10582               cast<StoreSDNode>(N)->getMemoryVT(),
10583               cast<StoreSDNode>(N)->getMemOperand());
10584       DCI.AddToWorklist(Val.getNode());
10585       return Val;
10586     }
10587
10588     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10589     if (cast<StoreSDNode>(N)->isUnindexed() &&
10590         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10591         N->getOperand(1).getNode()->hasOneUse() &&
10592         (N->getOperand(1).getValueType() == MVT::i32 ||
10593          N->getOperand(1).getValueType() == MVT::i16 ||
10594          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10595           N->getOperand(1).getValueType() == MVT::i64))) {
10596       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10597       // Do an any-extend to 32-bits if this is a half-word input.
10598       if (BSwapOp.getValueType() == MVT::i16)
10599         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10600
10601       SDValue Ops[] = {
10602         N->getOperand(0), BSwapOp, N->getOperand(2),
10603         DAG.getValueType(N->getOperand(1).getValueType())
10604       };
10605       return
10606         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10607                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10608                                 cast<StoreSDNode>(N)->getMemOperand());
10609     }
10610
10611     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10612     EVT VT = N->getOperand(1).getValueType();
10613     if (VT.isSimple()) {
10614       MVT StoreVT = VT.getSimpleVT();
10615       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10616           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10617            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10618         return expandVSXStoreForLE(N, DCI);
10619     }
10620     break;
10621   }
10622   case ISD::LOAD: {
10623     LoadSDNode *LD = cast<LoadSDNode>(N);
10624     EVT VT = LD->getValueType(0);
10625
10626     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10627     if (VT.isSimple()) {
10628       MVT LoadVT = VT.getSimpleVT();
10629       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10630           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10631            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10632         return expandVSXLoadForLE(N, DCI);
10633     }
10634
10635     // We sometimes end up with a 64-bit integer load, from which we extract
10636     // two single-precision floating-point numbers. This happens with
10637     // std::complex<float>, and other similar structures, because of the way we
10638     // canonicalize structure copies. However, if we lack direct moves,
10639     // then the final bitcasts from the extracted integer values to the
10640     // floating-point numbers turn into store/load pairs. Even with direct moves,
10641     // just loading the two floating-point numbers is likely better.
10642     auto ReplaceTwoFloatLoad = [&]() {
10643       if (VT != MVT::i64)
10644         return false;
10645
10646       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10647           LD->isVolatile())
10648         return false;
10649
10650       //  We're looking for a sequence like this:
10651       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10652       //      t16: i64 = srl t13, Constant:i32<32>
10653       //    t17: i32 = truncate t16
10654       //  t18: f32 = bitcast t17
10655       //    t19: i32 = truncate t13
10656       //  t20: f32 = bitcast t19
10657
10658       if (!LD->hasNUsesOfValue(2, 0))
10659         return false;
10660
10661       auto UI = LD->use_begin();
10662       while (UI.getUse().getResNo() != 0) ++UI;
10663       SDNode *Trunc = *UI++;
10664       while (UI.getUse().getResNo() != 0) ++UI;
10665       SDNode *RightShift = *UI;
10666       if (Trunc->getOpcode() != ISD::TRUNCATE)
10667         std::swap(Trunc, RightShift);
10668
10669       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10670           Trunc->getValueType(0) != MVT::i32 ||
10671           !Trunc->hasOneUse())
10672         return false;
10673       if (RightShift->getOpcode() != ISD::SRL ||
10674           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10675           RightShift->getConstantOperandVal(1) != 32 ||
10676           !RightShift->hasOneUse())
10677         return false;
10678
10679       SDNode *Trunc2 = *RightShift->use_begin();
10680       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10681           Trunc2->getValueType(0) != MVT::i32 ||
10682           !Trunc2->hasOneUse())
10683         return false;
10684
10685       SDNode *Bitcast = *Trunc->use_begin();
10686       SDNode *Bitcast2 = *Trunc2->use_begin();
10687
10688       if (Bitcast->getOpcode() != ISD::BITCAST ||
10689           Bitcast->getValueType(0) != MVT::f32)
10690         return false;
10691       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10692           Bitcast2->getValueType(0) != MVT::f32)
10693         return false;
10694
10695       if (Subtarget.isLittleEndian())
10696         std::swap(Bitcast, Bitcast2);
10697
10698       // Bitcast has the second float (in memory-layout order) and Bitcast2
10699       // has the first one.
10700
10701       SDValue BasePtr = LD->getBasePtr();
10702       if (LD->isIndexed()) {
10703         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10704                "Non-pre-inc AM on PPC?");
10705         BasePtr =
10706           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10707                       LD->getOffset());
10708       }
10709
10710       auto MMOFlags =
10711           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
10712       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10713                                       LD->getPointerInfo(), LD->getAlignment(),
10714                                       MMOFlags, LD->getAAInfo());
10715       SDValue AddPtr =
10716         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10717                     BasePtr, DAG.getIntPtrConstant(4, dl));
10718       SDValue FloatLoad2 = DAG.getLoad(
10719           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10720           LD->getPointerInfo().getWithOffset(4),
10721           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
10722
10723       if (LD->isIndexed()) {
10724         // Note that DAGCombine should re-form any pre-increment load(s) from
10725         // what is produced here if that makes sense.
10726         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10727       }
10728
10729       DCI.CombineTo(Bitcast2, FloatLoad);
10730       DCI.CombineTo(Bitcast, FloatLoad2);
10731
10732       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10733                                     SDValue(FloatLoad2.getNode(), 1));
10734       return true;
10735     };
10736
10737     if (ReplaceTwoFloatLoad())
10738       return SDValue(N, 0);
10739
10740     EVT MemVT = LD->getMemoryVT();
10741     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10742     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10743     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10744     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10745     if (LD->isUnindexed() && VT.isVector() &&
10746         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10747           // P8 and later hardware should just use LOAD.
10748           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10749                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10750          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10751           LD->getAlignment() >= ScalarABIAlignment)) &&
10752         LD->getAlignment() < ABIAlignment) {
10753       // This is a type-legal unaligned Altivec or QPX load.
10754       SDValue Chain = LD->getChain();
10755       SDValue Ptr = LD->getBasePtr();
10756       bool isLittleEndian = Subtarget.isLittleEndian();
10757
10758       // This implements the loading of unaligned vectors as described in
10759       // the venerable Apple Velocity Engine overview. Specifically:
10760       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10761       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10762       //
10763       // The general idea is to expand a sequence of one or more unaligned
10764       // loads into an alignment-based permutation-control instruction (lvsl
10765       // or lvsr), a series of regular vector loads (which always truncate
10766       // their input address to an aligned address), and a series of
10767       // permutations.  The results of these permutations are the requested
10768       // loaded values.  The trick is that the last "extra" load is not taken
10769       // from the address you might suspect (sizeof(vector) bytes after the
10770       // last requested load), but rather sizeof(vector) - 1 bytes after the
10771       // last requested vector. The point of this is to avoid a page fault if
10772       // the base address happened to be aligned. This works because if the
10773       // base address is aligned, then adding less than a full vector length
10774       // will cause the last vector in the sequence to be (re)loaded.
10775       // Otherwise, the next vector will be fetched as you might suspect was
10776       // necessary.
10777
10778       // We might be able to reuse the permutation generation from
10779       // a different base address offset from this one by an aligned amount.
10780       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10781       // optimization later.
10782       Intrinsic::ID Intr, IntrLD, IntrPerm;
10783       MVT PermCntlTy, PermTy, LDTy;
10784       if (Subtarget.hasAltivec()) {
10785         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10786                                  Intrinsic::ppc_altivec_lvsl;
10787         IntrLD = Intrinsic::ppc_altivec_lvx;
10788         IntrPerm = Intrinsic::ppc_altivec_vperm;
10789         PermCntlTy = MVT::v16i8;
10790         PermTy = MVT::v4i32;
10791         LDTy = MVT::v4i32;
10792       } else {
10793         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10794                                        Intrinsic::ppc_qpx_qvlpcls;
10795         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10796                                        Intrinsic::ppc_qpx_qvlfs;
10797         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10798         PermCntlTy = MVT::v4f64;
10799         PermTy = MVT::v4f64;
10800         LDTy = MemVT.getSimpleVT();
10801       }
10802
10803       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10804
10805       // Create the new MMO for the new base load. It is like the original MMO,
10806       // but represents an area in memory almost twice the vector size centered
10807       // on the original address. If the address is unaligned, we might start
10808       // reading up to (sizeof(vector)-1) bytes below the address of the
10809       // original unaligned load.
10810       MachineFunction &MF = DAG.getMachineFunction();
10811       MachineMemOperand *BaseMMO =
10812         MF.getMachineMemOperand(LD->getMemOperand(),
10813                                 -(long)MemVT.getStoreSize()+1,
10814                                 2*MemVT.getStoreSize()-1);
10815
10816       // Create the new base load.
10817       SDValue LDXIntID =
10818           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10819       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10820       SDValue BaseLoad =
10821         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10822                                 DAG.getVTList(PermTy, MVT::Other),
10823                                 BaseLoadOps, LDTy, BaseMMO);
10824
10825       // Note that the value of IncOffset (which is provided to the next
10826       // load's pointer info offset value, and thus used to calculate the
10827       // alignment), and the value of IncValue (which is actually used to
10828       // increment the pointer value) are different! This is because we
10829       // require the next load to appear to be aligned, even though it
10830       // is actually offset from the base pointer by a lesser amount.
10831       int IncOffset = VT.getSizeInBits() / 8;
10832       int IncValue = IncOffset;
10833
10834       // Walk (both up and down) the chain looking for another load at the real
10835       // (aligned) offset (the alignment of the other load does not matter in
10836       // this case). If found, then do not use the offset reduction trick, as
10837       // that will prevent the loads from being later combined (as they would
10838       // otherwise be duplicates).
10839       if (!findConsecutiveLoad(LD, DAG))
10840         --IncValue;
10841
10842       SDValue Increment =
10843           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10844       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10845
10846       MachineMemOperand *ExtraMMO =
10847         MF.getMachineMemOperand(LD->getMemOperand(),
10848                                 1, 2*MemVT.getStoreSize()-1);
10849       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10850       SDValue ExtraLoad =
10851         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10852                                 DAG.getVTList(PermTy, MVT::Other),
10853                                 ExtraLoadOps, LDTy, ExtraMMO);
10854
10855       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10856         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10857
10858       // Because vperm has a big-endian bias, we must reverse the order
10859       // of the input vectors and complement the permute control vector
10860       // when generating little endian code.  We have already handled the
10861       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10862       // and ExtraLoad here.
10863       SDValue Perm;
10864       if (isLittleEndian)
10865         Perm = BuildIntrinsicOp(IntrPerm,
10866                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10867       else
10868         Perm = BuildIntrinsicOp(IntrPerm,
10869                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10870
10871       if (VT != PermTy)
10872         Perm = Subtarget.hasAltivec() ?
10873                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10874                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10875                                DAG.getTargetConstant(1, dl, MVT::i64));
10876                                // second argument is 1 because this rounding
10877                                // is always exact.
10878
10879       // The output of the permutation is our loaded result, the TokenFactor is
10880       // our new chain.
10881       DCI.CombineTo(N, Perm, TF);
10882       return SDValue(N, 0);
10883     }
10884     }
10885     break;
10886     case ISD::INTRINSIC_WO_CHAIN: {
10887       bool isLittleEndian = Subtarget.isLittleEndian();
10888       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10889       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10890                                            : Intrinsic::ppc_altivec_lvsl);
10891       if ((IID == Intr ||
10892            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10893            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10894         N->getOperand(1)->getOpcode() == ISD::ADD) {
10895         SDValue Add = N->getOperand(1);
10896
10897         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10898                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10899
10900         if (DAG.MaskedValueIsZero(
10901                 Add->getOperand(1),
10902                 APInt::getAllOnesValue(Bits /* alignment */)
10903                     .zext(
10904                         Add.getValueType().getScalarType().getSizeInBits()))) {
10905           SDNode *BasePtr = Add->getOperand(0).getNode();
10906           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10907                                     UE = BasePtr->use_end();
10908                UI != UE; ++UI) {
10909             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10910                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10911               // We've found another LVSL/LVSR, and this address is an aligned
10912               // multiple of that one. The results will be the same, so use the
10913               // one we've just found instead.
10914
10915               return SDValue(*UI, 0);
10916             }
10917           }
10918         }
10919
10920         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10921           SDNode *BasePtr = Add->getOperand(0).getNode();
10922           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10923                UE = BasePtr->use_end(); UI != UE; ++UI) {
10924             if (UI->getOpcode() == ISD::ADD &&
10925                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10926                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10927                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10928                 (1ULL << Bits) == 0) {
10929               SDNode *OtherAdd = *UI;
10930               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10931                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10932                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10933                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10934                   return SDValue(*VI, 0);
10935                 }
10936               }
10937             }
10938           }
10939         }
10940       }
10941     }
10942
10943     break;
10944   case ISD::INTRINSIC_W_CHAIN: {
10945     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10946     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10947       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10948       default:
10949         break;
10950       case Intrinsic::ppc_vsx_lxvw4x:
10951       case Intrinsic::ppc_vsx_lxvd2x:
10952         return expandVSXLoadForLE(N, DCI);
10953       }
10954     }
10955     break;
10956   }
10957   case ISD::INTRINSIC_VOID: {
10958     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10959     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10960       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10961       default:
10962         break;
10963       case Intrinsic::ppc_vsx_stxvw4x:
10964       case Intrinsic::ppc_vsx_stxvd2x:
10965         return expandVSXStoreForLE(N, DCI);
10966       }
10967     }
10968     break;
10969   }
10970   case ISD::BSWAP:
10971     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10972     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10973         N->getOperand(0).hasOneUse() &&
10974         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10975          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10976           N->getValueType(0) == MVT::i64))) {
10977       SDValue Load = N->getOperand(0);
10978       LoadSDNode *LD = cast<LoadSDNode>(Load);
10979       // Create the byte-swapping load.
10980       SDValue Ops[] = {
10981         LD->getChain(),    // Chain
10982         LD->getBasePtr(),  // Ptr
10983         DAG.getValueType(N->getValueType(0)) // VT
10984       };
10985       SDValue BSLoad =
10986         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10987                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10988                                               MVT::i64 : MVT::i32, MVT::Other),
10989                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10990
10991       // If this is an i16 load, insert the truncate.
10992       SDValue ResVal = BSLoad;
10993       if (N->getValueType(0) == MVT::i16)
10994         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10995
10996       // First, combine the bswap away.  This makes the value produced by the
10997       // load dead.
10998       DCI.CombineTo(N, ResVal);
10999
11000       // Next, combine the load away, we give it a bogus result value but a real
11001       // chain result.  The result value is dead because the bswap is dead.
11002       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11003
11004       // Return N so it doesn't get rechecked!
11005       return SDValue(N, 0);
11006     }
11007
11008     break;
11009   case PPCISD::VCMP: {
11010     // If a VCMPo node already exists with exactly the same operands as this
11011     // node, use its result instead of this node (VCMPo computes both a CR6 and
11012     // a normal output).
11013     //
11014     if (!N->getOperand(0).hasOneUse() &&
11015         !N->getOperand(1).hasOneUse() &&
11016         !N->getOperand(2).hasOneUse()) {
11017
11018       // Scan all of the users of the LHS, looking for VCMPo's that match.
11019       SDNode *VCMPoNode = nullptr;
11020
11021       SDNode *LHSN = N->getOperand(0).getNode();
11022       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11023            UI != E; ++UI)
11024         if (UI->getOpcode() == PPCISD::VCMPo &&
11025             UI->getOperand(1) == N->getOperand(1) &&
11026             UI->getOperand(2) == N->getOperand(2) &&
11027             UI->getOperand(0) == N->getOperand(0)) {
11028           VCMPoNode = *UI;
11029           break;
11030         }
11031
11032       // If there is no VCMPo node, or if the flag value has a single use, don't
11033       // transform this.
11034       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11035         break;
11036
11037       // Look at the (necessarily single) use of the flag value.  If it has a
11038       // chain, this transformation is more complex.  Note that multiple things
11039       // could use the value result, which we should ignore.
11040       SDNode *FlagUser = nullptr;
11041       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11042            FlagUser == nullptr; ++UI) {
11043         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11044         SDNode *User = *UI;
11045         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11046           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11047             FlagUser = User;
11048             break;
11049           }
11050         }
11051       }
11052
11053       // If the user is a MFOCRF instruction, we know this is safe.
11054       // Otherwise we give up for right now.
11055       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11056         return SDValue(VCMPoNode, 0);
11057     }
11058     break;
11059   }
11060   case ISD::BRCOND: {
11061     SDValue Cond = N->getOperand(1);
11062     SDValue Target = N->getOperand(2);
11063
11064     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11065         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11066           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11067
11068       // We now need to make the intrinsic dead (it cannot be instruction
11069       // selected).
11070       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11071       assert(Cond.getNode()->hasOneUse() &&
11072              "Counter decrement has more than one use");
11073
11074       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11075                          N->getOperand(0), Target);
11076     }
11077   }
11078   break;
11079   case ISD::BR_CC: {
11080     // If this is a branch on an altivec predicate comparison, lower this so
11081     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11082     // lowering is done pre-legalize, because the legalizer lowers the predicate
11083     // compare down to code that is difficult to reassemble.
11084     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11085     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11086
11087     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11088     // value. If so, pass-through the AND to get to the intrinsic.
11089     if (LHS.getOpcode() == ISD::AND &&
11090         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11091         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11092           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11093         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11094         !isNullConstant(LHS.getOperand(1)))
11095       LHS = LHS.getOperand(0);
11096
11097     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11098         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11099           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11100         isa<ConstantSDNode>(RHS)) {
11101       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11102              "Counter decrement comparison is not EQ or NE");
11103
11104       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11105       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11106                     (CC == ISD::SETNE && !Val);
11107
11108       // We now need to make the intrinsic dead (it cannot be instruction
11109       // selected).
11110       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11111       assert(LHS.getNode()->hasOneUse() &&
11112              "Counter decrement has more than one use");
11113
11114       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11115                          N->getOperand(0), N->getOperand(4));
11116     }
11117
11118     int CompareOpc;
11119     bool isDot;
11120
11121     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11122         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11123         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11124       assert(isDot && "Can't compare against a vector result!");
11125
11126       // If this is a comparison against something other than 0/1, then we know
11127       // that the condition is never/always true.
11128       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11129       if (Val != 0 && Val != 1) {
11130         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11131           return N->getOperand(0);
11132         // Always !=, turn it into an unconditional branch.
11133         return DAG.getNode(ISD::BR, dl, MVT::Other,
11134                            N->getOperand(0), N->getOperand(4));
11135       }
11136
11137       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11138
11139       // Create the PPCISD altivec 'dot' comparison node.
11140       SDValue Ops[] = {
11141         LHS.getOperand(2),  // LHS of compare
11142         LHS.getOperand(3),  // RHS of compare
11143         DAG.getConstant(CompareOpc, dl, MVT::i32)
11144       };
11145       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11146       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11147
11148       // Unpack the result based on how the target uses it.
11149       PPC::Predicate CompOpc;
11150       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11151       default:  // Can't happen, don't crash on invalid number though.
11152       case 0:   // Branch on the value of the EQ bit of CR6.
11153         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11154         break;
11155       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11156         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11157         break;
11158       case 2:   // Branch on the value of the LT bit of CR6.
11159         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11160         break;
11161       case 3:   // Branch on the inverted value of the LT bit of CR6.
11162         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11163         break;
11164       }
11165
11166       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11167                          DAG.getConstant(CompOpc, dl, MVT::i32),
11168                          DAG.getRegister(PPC::CR6, MVT::i32),
11169                          N->getOperand(4), CompNode.getValue(1));
11170     }
11171     break;
11172   }
11173   case ISD::BUILD_VECTOR:
11174     return DAGCombineBuildVector(N, DCI);
11175   }
11176
11177   return SDValue();
11178 }
11179
11180 SDValue
11181 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11182                                   SelectionDAG &DAG,
11183                                   std::vector<SDNode *> *Created) const {
11184   // fold (sdiv X, pow2)
11185   EVT VT = N->getValueType(0);
11186   if (VT == MVT::i64 && !Subtarget.isPPC64())
11187     return SDValue();
11188   if ((VT != MVT::i32 && VT != MVT::i64) ||
11189       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11190     return SDValue();
11191
11192   SDLoc DL(N);
11193   SDValue N0 = N->getOperand(0);
11194
11195   bool IsNegPow2 = (-Divisor).isPowerOf2();
11196   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11197   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11198
11199   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11200   if (Created)
11201     Created->push_back(Op.getNode());
11202
11203   if (IsNegPow2) {
11204     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11205     if (Created)
11206       Created->push_back(Op.getNode());
11207   }
11208
11209   return Op;
11210 }
11211
11212 //===----------------------------------------------------------------------===//
11213 // Inline Assembly Support
11214 //===----------------------------------------------------------------------===//
11215
11216 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11217                                                       APInt &KnownZero,
11218                                                       APInt &KnownOne,
11219                                                       const SelectionDAG &DAG,
11220                                                       unsigned Depth) const {
11221   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11222   switch (Op.getOpcode()) {
11223   default: break;
11224   case PPCISD::LBRX: {
11225     // lhbrx is known to have the top bits cleared out.
11226     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11227       KnownZero = 0xFFFF0000;
11228     break;
11229   }
11230   case ISD::INTRINSIC_WO_CHAIN: {
11231     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11232     default: break;
11233     case Intrinsic::ppc_altivec_vcmpbfp_p:
11234     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11235     case Intrinsic::ppc_altivec_vcmpequb_p:
11236     case Intrinsic::ppc_altivec_vcmpequh_p:
11237     case Intrinsic::ppc_altivec_vcmpequw_p:
11238     case Intrinsic::ppc_altivec_vcmpequd_p:
11239     case Intrinsic::ppc_altivec_vcmpgefp_p:
11240     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11241     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11242     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11243     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11244     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11245     case Intrinsic::ppc_altivec_vcmpgtub_p:
11246     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11247     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11248     case Intrinsic::ppc_altivec_vcmpgtud_p:
11249       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11250       break;
11251     }
11252   }
11253   }
11254 }
11255
11256 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11257   switch (Subtarget.getDarwinDirective()) {
11258   default: break;
11259   case PPC::DIR_970:
11260   case PPC::DIR_PWR4:
11261   case PPC::DIR_PWR5:
11262   case PPC::DIR_PWR5X:
11263   case PPC::DIR_PWR6:
11264   case PPC::DIR_PWR6X:
11265   case PPC::DIR_PWR7:
11266   case PPC::DIR_PWR8:
11267   case PPC::DIR_PWR9: {
11268     if (!ML)
11269       break;
11270
11271     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11272
11273     // For small loops (between 5 and 8 instructions), align to a 32-byte
11274     // boundary so that the entire loop fits in one instruction-cache line.
11275     uint64_t LoopSize = 0;
11276     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11277       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11278         LoopSize += TII->GetInstSizeInBytes(*J);
11279         if (LoopSize > 32)
11280           break;
11281       }
11282
11283     if (LoopSize > 16 && LoopSize <= 32)
11284       return 5;
11285
11286     break;
11287   }
11288   }
11289
11290   return TargetLowering::getPrefLoopAlignment(ML);
11291 }
11292
11293 /// getConstraintType - Given a constraint, return the type of
11294 /// constraint it is for this target.
11295 PPCTargetLowering::ConstraintType
11296 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11297   if (Constraint.size() == 1) {
11298     switch (Constraint[0]) {
11299     default: break;
11300     case 'b':
11301     case 'r':
11302     case 'f':
11303     case 'd':
11304     case 'v':
11305     case 'y':
11306       return C_RegisterClass;
11307     case 'Z':
11308       // FIXME: While Z does indicate a memory constraint, it specifically
11309       // indicates an r+r address (used in conjunction with the 'y' modifier
11310       // in the replacement string). Currently, we're forcing the base
11311       // register to be r0 in the asm printer (which is interpreted as zero)
11312       // and forming the complete address in the second register. This is
11313       // suboptimal.
11314       return C_Memory;
11315     }
11316   } else if (Constraint == "wc") { // individual CR bits.
11317     return C_RegisterClass;
11318   } else if (Constraint == "wa" || Constraint == "wd" ||
11319              Constraint == "wf" || Constraint == "ws") {
11320     return C_RegisterClass; // VSX registers.
11321   }
11322   return TargetLowering::getConstraintType(Constraint);
11323 }
11324
11325 /// Examine constraint type and operand type and determine a weight value.
11326 /// This object must already have been set up with the operand type
11327 /// and the current alternative constraint selected.
11328 TargetLowering::ConstraintWeight
11329 PPCTargetLowering::getSingleConstraintMatchWeight(
11330     AsmOperandInfo &info, const char *constraint) const {
11331   ConstraintWeight weight = CW_Invalid;
11332   Value *CallOperandVal = info.CallOperandVal;
11333     // If we don't have a value, we can't do a match,
11334     // but allow it at the lowest weight.
11335   if (!CallOperandVal)
11336     return CW_Default;
11337   Type *type = CallOperandVal->getType();
11338
11339   // Look at the constraint type.
11340   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11341     return CW_Register; // an individual CR bit.
11342   else if ((StringRef(constraint) == "wa" ||
11343             StringRef(constraint) == "wd" ||
11344             StringRef(constraint) == "wf") &&
11345            type->isVectorTy())
11346     return CW_Register;
11347   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11348     return CW_Register;
11349
11350   switch (*constraint) {
11351   default:
11352     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11353     break;
11354   case 'b':
11355     if (type->isIntegerTy())
11356       weight = CW_Register;
11357     break;
11358   case 'f':
11359     if (type->isFloatTy())
11360       weight = CW_Register;
11361     break;
11362   case 'd':
11363     if (type->isDoubleTy())
11364       weight = CW_Register;
11365     break;
11366   case 'v':
11367     if (type->isVectorTy())
11368       weight = CW_Register;
11369     break;
11370   case 'y':
11371     weight = CW_Register;
11372     break;
11373   case 'Z':
11374     weight = CW_Memory;
11375     break;
11376   }
11377   return weight;
11378 }
11379
11380 std::pair<unsigned, const TargetRegisterClass *>
11381 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11382                                                 StringRef Constraint,
11383                                                 MVT VT) const {
11384   if (Constraint.size() == 1) {
11385     // GCC RS6000 Constraint Letters
11386     switch (Constraint[0]) {
11387     case 'b':   // R1-R31
11388       if (VT == MVT::i64 && Subtarget.isPPC64())
11389         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11390       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11391     case 'r':   // R0-R31
11392       if (VT == MVT::i64 && Subtarget.isPPC64())
11393         return std::make_pair(0U, &PPC::G8RCRegClass);
11394       return std::make_pair(0U, &PPC::GPRCRegClass);
11395     // 'd' and 'f' constraints are both defined to be "the floating point
11396     // registers", where one is for 32-bit and the other for 64-bit. We don't
11397     // really care overly much here so just give them all the same reg classes.
11398     case 'd':
11399     case 'f':
11400       if (VT == MVT::f32 || VT == MVT::i32)
11401         return std::make_pair(0U, &PPC::F4RCRegClass);
11402       if (VT == MVT::f64 || VT == MVT::i64)
11403         return std::make_pair(0U, &PPC::F8RCRegClass);
11404       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11405         return std::make_pair(0U, &PPC::QFRCRegClass);
11406       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11407         return std::make_pair(0U, &PPC::QSRCRegClass);
11408       break;
11409     case 'v':
11410       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11411         return std::make_pair(0U, &PPC::QFRCRegClass);
11412       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11413         return std::make_pair(0U, &PPC::QSRCRegClass);
11414       if (Subtarget.hasAltivec())
11415         return std::make_pair(0U, &PPC::VRRCRegClass);
11416     case 'y':   // crrc
11417       return std::make_pair(0U, &PPC::CRRCRegClass);
11418     }
11419   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11420     // An individual CR bit.
11421     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11422   } else if ((Constraint == "wa" || Constraint == "wd" ||
11423              Constraint == "wf") && Subtarget.hasVSX()) {
11424     return std::make_pair(0U, &PPC::VSRCRegClass);
11425   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11426     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11427       return std::make_pair(0U, &PPC::VSSRCRegClass);
11428     else
11429       return std::make_pair(0U, &PPC::VSFRCRegClass);
11430   }
11431
11432   std::pair<unsigned, const TargetRegisterClass *> R =
11433       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11434
11435   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11436   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11437   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11438   // register.
11439   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11440   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11441   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11442       PPC::GPRCRegClass.contains(R.first))
11443     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11444                             PPC::sub_32, &PPC::G8RCRegClass),
11445                           &PPC::G8RCRegClass);
11446
11447   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11448   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11449     R.first = PPC::CR0;
11450     R.second = &PPC::CRRCRegClass;
11451   }
11452
11453   return R;
11454 }
11455
11456 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11457 /// vector.  If it is invalid, don't add anything to Ops.
11458 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11459                                                      std::string &Constraint,
11460                                                      std::vector<SDValue>&Ops,
11461                                                      SelectionDAG &DAG) const {
11462   SDValue Result;
11463
11464   // Only support length 1 constraints.
11465   if (Constraint.length() > 1) return;
11466
11467   char Letter = Constraint[0];
11468   switch (Letter) {
11469   default: break;
11470   case 'I':
11471   case 'J':
11472   case 'K':
11473   case 'L':
11474   case 'M':
11475   case 'N':
11476   case 'O':
11477   case 'P': {
11478     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11479     if (!CST) return; // Must be an immediate to match.
11480     SDLoc dl(Op);
11481     int64_t Value = CST->getSExtValue();
11482     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11483                          // numbers are printed as such.
11484     switch (Letter) {
11485     default: llvm_unreachable("Unknown constraint letter!");
11486     case 'I':  // "I" is a signed 16-bit constant.
11487       if (isInt<16>(Value))
11488         Result = DAG.getTargetConstant(Value, dl, TCVT);
11489       break;
11490     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11491       if (isShiftedUInt<16, 16>(Value))
11492         Result = DAG.getTargetConstant(Value, dl, TCVT);
11493       break;
11494     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11495       if (isShiftedInt<16, 16>(Value))
11496         Result = DAG.getTargetConstant(Value, dl, TCVT);
11497       break;
11498     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11499       if (isUInt<16>(Value))
11500         Result = DAG.getTargetConstant(Value, dl, TCVT);
11501       break;
11502     case 'M':  // "M" is a constant that is greater than 31.
11503       if (Value > 31)
11504         Result = DAG.getTargetConstant(Value, dl, TCVT);
11505       break;
11506     case 'N':  // "N" is a positive constant that is an exact power of two.
11507       if (Value > 0 && isPowerOf2_64(Value))
11508         Result = DAG.getTargetConstant(Value, dl, TCVT);
11509       break;
11510     case 'O':  // "O" is the constant zero.
11511       if (Value == 0)
11512         Result = DAG.getTargetConstant(Value, dl, TCVT);
11513       break;
11514     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11515       if (isInt<16>(-Value))
11516         Result = DAG.getTargetConstant(Value, dl, TCVT);
11517       break;
11518     }
11519     break;
11520   }
11521   }
11522
11523   if (Result.getNode()) {
11524     Ops.push_back(Result);
11525     return;
11526   }
11527
11528   // Handle standard constraint letters.
11529   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11530 }
11531
11532 // isLegalAddressingMode - Return true if the addressing mode represented
11533 // by AM is legal for this target, for a load/store of the specified type.
11534 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11535                                               const AddrMode &AM, Type *Ty,
11536                                               unsigned AS) const {
11537   // PPC does not allow r+i addressing modes for vectors!
11538   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11539     return false;
11540
11541   // PPC allows a sign-extended 16-bit immediate field.
11542   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11543     return false;
11544
11545   // No global is ever allowed as a base.
11546   if (AM.BaseGV)
11547     return false;
11548
11549   // PPC only support r+r,
11550   switch (AM.Scale) {
11551   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11552     break;
11553   case 1:
11554     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11555       return false;
11556     // Otherwise we have r+r or r+i.
11557     break;
11558   case 2:
11559     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11560       return false;
11561     // Allow 2*r as r+r.
11562     break;
11563   default:
11564     // No other scales are supported.
11565     return false;
11566   }
11567
11568   return true;
11569 }
11570
11571 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11572                                            SelectionDAG &DAG) const {
11573   MachineFunction &MF = DAG.getMachineFunction();
11574   MachineFrameInfo *MFI = MF.getFrameInfo();
11575   MFI->setReturnAddressIsTaken(true);
11576
11577   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11578     return SDValue();
11579
11580   SDLoc dl(Op);
11581   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11582
11583   // Make sure the function does not optimize away the store of the RA to
11584   // the stack.
11585   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11586   FuncInfo->setLRStoreRequired();
11587   bool isPPC64 = Subtarget.isPPC64();
11588   auto PtrVT = getPointerTy(MF.getDataLayout());
11589
11590   if (Depth > 0) {
11591     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11592     SDValue Offset =
11593         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11594                         isPPC64 ? MVT::i64 : MVT::i32);
11595     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11596                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11597                        MachinePointerInfo());
11598   }
11599
11600   // Just load the return address off the stack.
11601   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11602   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11603                      MachinePointerInfo());
11604 }
11605
11606 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11607                                           SelectionDAG &DAG) const {
11608   SDLoc dl(Op);
11609   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11610
11611   MachineFunction &MF = DAG.getMachineFunction();
11612   MachineFrameInfo *MFI = MF.getFrameInfo();
11613   MFI->setFrameAddressIsTaken(true);
11614
11615   EVT PtrVT = getPointerTy(MF.getDataLayout());
11616   bool isPPC64 = PtrVT == MVT::i64;
11617
11618   // Naked functions never have a frame pointer, and so we use r1. For all
11619   // other functions, this decision must be delayed until during PEI.
11620   unsigned FrameReg;
11621   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11622     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11623   else
11624     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11625
11626   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11627                                          PtrVT);
11628   while (Depth--)
11629     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11630                             FrameAddr, MachinePointerInfo());
11631   return FrameAddr;
11632 }
11633
11634 // FIXME? Maybe this could be a TableGen attribute on some registers and
11635 // this table could be generated automatically from RegInfo.
11636 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11637                                               SelectionDAG &DAG) const {
11638   bool isPPC64 = Subtarget.isPPC64();
11639   bool isDarwinABI = Subtarget.isDarwinABI();
11640
11641   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11642       (!isPPC64 && VT != MVT::i32))
11643     report_fatal_error("Invalid register global variable type");
11644
11645   bool is64Bit = isPPC64 && VT == MVT::i64;
11646   unsigned Reg = StringSwitch<unsigned>(RegName)
11647                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11648                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11649                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11650                                   (is64Bit ? PPC::X13 : PPC::R13))
11651                    .Default(0);
11652
11653   if (Reg)
11654     return Reg;
11655   report_fatal_error("Invalid register name global variable");
11656 }
11657
11658 bool
11659 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11660   // The PowerPC target isn't yet aware of offsets.
11661   return false;
11662 }
11663
11664 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11665                                            const CallInst &I,
11666                                            unsigned Intrinsic) const {
11667
11668   switch (Intrinsic) {
11669   case Intrinsic::ppc_qpx_qvlfd:
11670   case Intrinsic::ppc_qpx_qvlfs:
11671   case Intrinsic::ppc_qpx_qvlfcd:
11672   case Intrinsic::ppc_qpx_qvlfcs:
11673   case Intrinsic::ppc_qpx_qvlfiwa:
11674   case Intrinsic::ppc_qpx_qvlfiwz:
11675   case Intrinsic::ppc_altivec_lvx:
11676   case Intrinsic::ppc_altivec_lvxl:
11677   case Intrinsic::ppc_altivec_lvebx:
11678   case Intrinsic::ppc_altivec_lvehx:
11679   case Intrinsic::ppc_altivec_lvewx:
11680   case Intrinsic::ppc_vsx_lxvd2x:
11681   case Intrinsic::ppc_vsx_lxvw4x: {
11682     EVT VT;
11683     switch (Intrinsic) {
11684     case Intrinsic::ppc_altivec_lvebx:
11685       VT = MVT::i8;
11686       break;
11687     case Intrinsic::ppc_altivec_lvehx:
11688       VT = MVT::i16;
11689       break;
11690     case Intrinsic::ppc_altivec_lvewx:
11691       VT = MVT::i32;
11692       break;
11693     case Intrinsic::ppc_vsx_lxvd2x:
11694       VT = MVT::v2f64;
11695       break;
11696     case Intrinsic::ppc_qpx_qvlfd:
11697       VT = MVT::v4f64;
11698       break;
11699     case Intrinsic::ppc_qpx_qvlfs:
11700       VT = MVT::v4f32;
11701       break;
11702     case Intrinsic::ppc_qpx_qvlfcd:
11703       VT = MVT::v2f64;
11704       break;
11705     case Intrinsic::ppc_qpx_qvlfcs:
11706       VT = MVT::v2f32;
11707       break;
11708     default:
11709       VT = MVT::v4i32;
11710       break;
11711     }
11712
11713     Info.opc = ISD::INTRINSIC_W_CHAIN;
11714     Info.memVT = VT;
11715     Info.ptrVal = I.getArgOperand(0);
11716     Info.offset = -VT.getStoreSize()+1;
11717     Info.size = 2*VT.getStoreSize()-1;
11718     Info.align = 1;
11719     Info.vol = false;
11720     Info.readMem = true;
11721     Info.writeMem = false;
11722     return true;
11723   }
11724   case Intrinsic::ppc_qpx_qvlfda:
11725   case Intrinsic::ppc_qpx_qvlfsa:
11726   case Intrinsic::ppc_qpx_qvlfcda:
11727   case Intrinsic::ppc_qpx_qvlfcsa:
11728   case Intrinsic::ppc_qpx_qvlfiwaa:
11729   case Intrinsic::ppc_qpx_qvlfiwza: {
11730     EVT VT;
11731     switch (Intrinsic) {
11732     case Intrinsic::ppc_qpx_qvlfda:
11733       VT = MVT::v4f64;
11734       break;
11735     case Intrinsic::ppc_qpx_qvlfsa:
11736       VT = MVT::v4f32;
11737       break;
11738     case Intrinsic::ppc_qpx_qvlfcda:
11739       VT = MVT::v2f64;
11740       break;
11741     case Intrinsic::ppc_qpx_qvlfcsa:
11742       VT = MVT::v2f32;
11743       break;
11744     default:
11745       VT = MVT::v4i32;
11746       break;
11747     }
11748
11749     Info.opc = ISD::INTRINSIC_W_CHAIN;
11750     Info.memVT = VT;
11751     Info.ptrVal = I.getArgOperand(0);
11752     Info.offset = 0;
11753     Info.size = VT.getStoreSize();
11754     Info.align = 1;
11755     Info.vol = false;
11756     Info.readMem = true;
11757     Info.writeMem = false;
11758     return true;
11759   }
11760   case Intrinsic::ppc_qpx_qvstfd:
11761   case Intrinsic::ppc_qpx_qvstfs:
11762   case Intrinsic::ppc_qpx_qvstfcd:
11763   case Intrinsic::ppc_qpx_qvstfcs:
11764   case Intrinsic::ppc_qpx_qvstfiw:
11765   case Intrinsic::ppc_altivec_stvx:
11766   case Intrinsic::ppc_altivec_stvxl:
11767   case Intrinsic::ppc_altivec_stvebx:
11768   case Intrinsic::ppc_altivec_stvehx:
11769   case Intrinsic::ppc_altivec_stvewx:
11770   case Intrinsic::ppc_vsx_stxvd2x:
11771   case Intrinsic::ppc_vsx_stxvw4x: {
11772     EVT VT;
11773     switch (Intrinsic) {
11774     case Intrinsic::ppc_altivec_stvebx:
11775       VT = MVT::i8;
11776       break;
11777     case Intrinsic::ppc_altivec_stvehx:
11778       VT = MVT::i16;
11779       break;
11780     case Intrinsic::ppc_altivec_stvewx:
11781       VT = MVT::i32;
11782       break;
11783     case Intrinsic::ppc_vsx_stxvd2x:
11784       VT = MVT::v2f64;
11785       break;
11786     case Intrinsic::ppc_qpx_qvstfd:
11787       VT = MVT::v4f64;
11788       break;
11789     case Intrinsic::ppc_qpx_qvstfs:
11790       VT = MVT::v4f32;
11791       break;
11792     case Intrinsic::ppc_qpx_qvstfcd:
11793       VT = MVT::v2f64;
11794       break;
11795     case Intrinsic::ppc_qpx_qvstfcs:
11796       VT = MVT::v2f32;
11797       break;
11798     default:
11799       VT = MVT::v4i32;
11800       break;
11801     }
11802
11803     Info.opc = ISD::INTRINSIC_VOID;
11804     Info.memVT = VT;
11805     Info.ptrVal = I.getArgOperand(1);
11806     Info.offset = -VT.getStoreSize()+1;
11807     Info.size = 2*VT.getStoreSize()-1;
11808     Info.align = 1;
11809     Info.vol = false;
11810     Info.readMem = false;
11811     Info.writeMem = true;
11812     return true;
11813   }
11814   case Intrinsic::ppc_qpx_qvstfda:
11815   case Intrinsic::ppc_qpx_qvstfsa:
11816   case Intrinsic::ppc_qpx_qvstfcda:
11817   case Intrinsic::ppc_qpx_qvstfcsa:
11818   case Intrinsic::ppc_qpx_qvstfiwa: {
11819     EVT VT;
11820     switch (Intrinsic) {
11821     case Intrinsic::ppc_qpx_qvstfda:
11822       VT = MVT::v4f64;
11823       break;
11824     case Intrinsic::ppc_qpx_qvstfsa:
11825       VT = MVT::v4f32;
11826       break;
11827     case Intrinsic::ppc_qpx_qvstfcda:
11828       VT = MVT::v2f64;
11829       break;
11830     case Intrinsic::ppc_qpx_qvstfcsa:
11831       VT = MVT::v2f32;
11832       break;
11833     default:
11834       VT = MVT::v4i32;
11835       break;
11836     }
11837
11838     Info.opc = ISD::INTRINSIC_VOID;
11839     Info.memVT = VT;
11840     Info.ptrVal = I.getArgOperand(1);
11841     Info.offset = 0;
11842     Info.size = VT.getStoreSize();
11843     Info.align = 1;
11844     Info.vol = false;
11845     Info.readMem = false;
11846     Info.writeMem = true;
11847     return true;
11848   }
11849   default:
11850     break;
11851   }
11852
11853   return false;
11854 }
11855
11856 /// getOptimalMemOpType - Returns the target specific optimal type for load
11857 /// and store operations as a result of memset, memcpy, and memmove
11858 /// lowering. If DstAlign is zero that means it's safe to destination
11859 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11860 /// means there isn't a need to check it against alignment requirement,
11861 /// probably because the source does not need to be loaded. If 'IsMemset' is
11862 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11863 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11864 /// source is constant so it does not need to be loaded.
11865 /// It returns EVT::Other if the type should be determined using generic
11866 /// target-independent logic.
11867 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11868                                            unsigned DstAlign, unsigned SrcAlign,
11869                                            bool IsMemset, bool ZeroMemset,
11870                                            bool MemcpyStrSrc,
11871                                            MachineFunction &MF) const {
11872   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11873     const Function *F = MF.getFunction();
11874     // When expanding a memset, require at least two QPX instructions to cover
11875     // the cost of loading the value to be stored from the constant pool.
11876     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11877        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11878         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11879       return MVT::v4f64;
11880     }
11881
11882     // We should use Altivec/VSX loads and stores when available. For unaligned
11883     // addresses, unaligned VSX loads are only fast starting with the P8.
11884     if (Subtarget.hasAltivec() && Size >= 16 &&
11885         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11886          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11887       return MVT::v4i32;
11888   }
11889
11890   if (Subtarget.isPPC64()) {
11891     return MVT::i64;
11892   }
11893
11894   return MVT::i32;
11895 }
11896
11897 /// \brief Returns true if it is beneficial to convert a load of a constant
11898 /// to just the constant itself.
11899 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11900                                                           Type *Ty) const {
11901   assert(Ty->isIntegerTy());
11902
11903   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11904   return !(BitSize == 0 || BitSize > 64);
11905 }
11906
11907 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11908   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11909     return false;
11910   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11911   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11912   return NumBits1 == 64 && NumBits2 == 32;
11913 }
11914
11915 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11916   if (!VT1.isInteger() || !VT2.isInteger())
11917     return false;
11918   unsigned NumBits1 = VT1.getSizeInBits();
11919   unsigned NumBits2 = VT2.getSizeInBits();
11920   return NumBits1 == 64 && NumBits2 == 32;
11921 }
11922
11923 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11924   // Generally speaking, zexts are not free, but they are free when they can be
11925   // folded with other operations.
11926   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11927     EVT MemVT = LD->getMemoryVT();
11928     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11929          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11930         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11931          LD->getExtensionType() == ISD::ZEXTLOAD))
11932       return true;
11933   }
11934
11935   // FIXME: Add other cases...
11936   //  - 32-bit shifts with a zext to i64
11937   //  - zext after ctlz, bswap, etc.
11938   //  - zext after and by a constant mask
11939
11940   return TargetLowering::isZExtFree(Val, VT2);
11941 }
11942
11943 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11944   assert(VT.isFloatingPoint());
11945   return true;
11946 }
11947
11948 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11949   return isInt<16>(Imm) || isUInt<16>(Imm);
11950 }
11951
11952 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11953   return isInt<16>(Imm) || isUInt<16>(Imm);
11954 }
11955
11956 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11957                                                        unsigned,
11958                                                        unsigned,
11959                                                        bool *Fast) const {
11960   if (DisablePPCUnaligned)
11961     return false;
11962
11963   // PowerPC supports unaligned memory access for simple non-vector types.
11964   // Although accessing unaligned addresses is not as efficient as accessing
11965   // aligned addresses, it is generally more efficient than manual expansion,
11966   // and generally only traps for software emulation when crossing page
11967   // boundaries.
11968
11969   if (!VT.isSimple())
11970     return false;
11971
11972   if (VT.getSimpleVT().isVector()) {
11973     if (Subtarget.hasVSX()) {
11974       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11975           VT != MVT::v4f32 && VT != MVT::v4i32)
11976         return false;
11977     } else {
11978       return false;
11979     }
11980   }
11981
11982   if (VT == MVT::ppcf128)
11983     return false;
11984
11985   if (Fast)
11986     *Fast = true;
11987
11988   return true;
11989 }
11990
11991 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11992   VT = VT.getScalarType();
11993
11994   if (!VT.isSimple())
11995     return false;
11996
11997   switch (VT.getSimpleVT().SimpleTy) {
11998   case MVT::f32:
11999   case MVT::f64:
12000     return true;
12001   default:
12002     break;
12003   }
12004
12005   return false;
12006 }
12007
12008 const MCPhysReg *
12009 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12010   // LR is a callee-save register, but we must treat it as clobbered by any call
12011   // site. Hence we include LR in the scratch registers, which are in turn added
12012   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12013   // to CTR, which is used by any indirect call.
12014   static const MCPhysReg ScratchRegs[] = {
12015     PPC::X12, PPC::LR8, PPC::CTR8, 0
12016   };
12017
12018   return ScratchRegs;
12019 }
12020
12021 unsigned PPCTargetLowering::getExceptionPointerRegister(
12022     const Constant *PersonalityFn) const {
12023   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12024 }
12025
12026 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12027     const Constant *PersonalityFn) const {
12028   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12029 }
12030
12031 bool
12032 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12033                      EVT VT , unsigned DefinedValues) const {
12034   if (VT == MVT::v2i64)
12035     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12036
12037   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12038     return true;
12039
12040   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12041 }
12042
12043 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12044   if (DisableILPPref || Subtarget.enableMachineScheduler())
12045     return TargetLowering::getSchedulingPreference(N);
12046
12047   return Sched::ILP;
12048 }
12049
12050 // Create a fast isel object.
12051 FastISel *
12052 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12053                                   const TargetLibraryInfo *LibInfo) const {
12054   return PPC::createFastISel(FuncInfo, LibInfo);
12055 }
12056
12057 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12058   if (Subtarget.isDarwinABI()) return;
12059   if (!Subtarget.isPPC64()) return;
12060
12061   // Update IsSplitCSR in PPCFunctionInfo
12062   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12063   PFI->setIsSplitCSR(true);
12064 }
12065
12066 void PPCTargetLowering::insertCopiesSplitCSR(
12067   MachineBasicBlock *Entry,
12068   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12069   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12070   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12071   if (!IStart)
12072     return;
12073
12074   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12075   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12076   MachineBasicBlock::iterator MBBI = Entry->begin();
12077   for (const MCPhysReg *I = IStart; *I; ++I) {
12078     const TargetRegisterClass *RC = nullptr;
12079     if (PPC::G8RCRegClass.contains(*I))
12080       RC = &PPC::G8RCRegClass;
12081     else if (PPC::F8RCRegClass.contains(*I))
12082       RC = &PPC::F8RCRegClass;
12083     else if (PPC::CRRCRegClass.contains(*I))
12084       RC = &PPC::CRRCRegClass;
12085     else if (PPC::VRRCRegClass.contains(*I))
12086       RC = &PPC::VRRCRegClass;
12087     else
12088       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12089
12090     unsigned NewVR = MRI->createVirtualRegister(RC);
12091     // Create copy from CSR to a virtual register.
12092     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12093     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12094     // nounwind. If we want to generalize this later, we may need to emit
12095     // CFI pseudo-instructions.
12096     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12097              Attribute::NoUnwind) &&
12098            "Function should be nounwind in insertCopiesSplitCSR!");
12099     Entry->addLiveIn(*I);
12100     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12101       .addReg(*I);
12102
12103     // Insert the copy-back instructions right before the terminator
12104     for (auto *Exit : Exits)
12105       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12106               TII->get(TargetOpcode::COPY), *I)
12107         .addReg(NewVR);
12108   }
12109 }
12110
12111 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12112 bool PPCTargetLowering::useLoadStackGuardNode() const {
12113   if (!Subtarget.isTargetLinux())
12114     return TargetLowering::useLoadStackGuardNode();
12115   return true;
12116 }
12117
12118 // Override to disable global variable loading on Linux.
12119 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12120   if (!Subtarget.isTargetLinux())
12121     return TargetLowering::insertSSPDeclarations(M);
12122 }