OSDN Git Service

170704958d4c9e0d903fb234dd2ce9c8e059dccd
[android-x86/external-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "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 (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2368     return V;
2369
2370   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2371     // Leave comparisons against 0 and -1 alone for now, since they're usually
2372     // optimized.  FIXME: revisit this when we can custom lower all setcc
2373     // optimizations.
2374     if (C->isAllOnesValue() || C->isNullValue())
2375       return SDValue();
2376   }
2377
2378   // If we have an integer seteq/setne, turn it into a compare against zero
2379   // by xor'ing the rhs with the lhs, which is faster than setting a
2380   // condition register, reading it back out, and masking the correct bit.  The
2381   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2382   // the result to other bit-twiddling opportunities.
2383   EVT LHSVT = Op.getOperand(0).getValueType();
2384   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2385     EVT VT = Op.getValueType();
2386     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2387                                 Op.getOperand(1));
2388     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2389   }
2390   return SDValue();
2391 }
2392
2393 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2394   SDNode *Node = Op.getNode();
2395   EVT VT = Node->getValueType(0);
2396   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2397   SDValue InChain = Node->getOperand(0);
2398   SDValue VAListPtr = Node->getOperand(1);
2399   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2400   SDLoc dl(Node);
2401
2402   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2403
2404   // gpr_index
2405   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2406                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2407   InChain = GprIndex.getValue(1);
2408
2409   if (VT == MVT::i64) {
2410     // Check if GprIndex is even
2411     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2412                                  DAG.getConstant(1, dl, MVT::i32));
2413     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2414                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2415     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2416                                           DAG.getConstant(1, dl, MVT::i32));
2417     // Align GprIndex to be even if it isn't
2418     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2419                            GprIndex);
2420   }
2421
2422   // fpr index is 1 byte after gpr
2423   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2424                                DAG.getConstant(1, dl, MVT::i32));
2425
2426   // fpr
2427   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2428                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2429   InChain = FprIndex.getValue(1);
2430
2431   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2432                                        DAG.getConstant(8, dl, MVT::i32));
2433
2434   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2435                                         DAG.getConstant(4, dl, MVT::i32));
2436
2437   // areas
2438   SDValue OverflowArea =
2439       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2440   InChain = OverflowArea.getValue(1);
2441
2442   SDValue RegSaveArea =
2443       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2444   InChain = RegSaveArea.getValue(1);
2445
2446   // select overflow_area if index > 8
2447   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2448                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2449
2450   // adjustment constant gpr_index * 4/8
2451   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2452                                     VT.isInteger() ? GprIndex : FprIndex,
2453                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2454                                                     MVT::i32));
2455
2456   // OurReg = RegSaveArea + RegConstant
2457   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2458                                RegConstant);
2459
2460   // Floating types are 32 bytes into RegSaveArea
2461   if (VT.isFloatingPoint())
2462     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2463                          DAG.getConstant(32, dl, MVT::i32));
2464
2465   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2466   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2467                                    VT.isInteger() ? GprIndex : FprIndex,
2468                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2469                                                    MVT::i32));
2470
2471   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2472                               VT.isInteger() ? VAListPtr : FprPtr,
2473                               MachinePointerInfo(SV), MVT::i8);
2474
2475   // determine if we should load from reg_save_area or overflow_area
2476   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2477
2478   // increase overflow_area by 4/8 if gpr/fpr > 8
2479   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2480                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2481                                           dl, MVT::i32));
2482
2483   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2484                              OverflowAreaPlusN);
2485
2486   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2487                               MachinePointerInfo(), MVT::i32);
2488
2489   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2490 }
2491
2492 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2493   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2494
2495   // We have to copy the entire va_list struct:
2496   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2497   return DAG.getMemcpy(Op.getOperand(0), Op,
2498                        Op.getOperand(1), Op.getOperand(2),
2499                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2500                        false, MachinePointerInfo(), MachinePointerInfo());
2501 }
2502
2503 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2504                                                   SelectionDAG &DAG) const {
2505   return Op.getOperand(0);
2506 }
2507
2508 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2509                                                 SelectionDAG &DAG) const {
2510   SDValue Chain = Op.getOperand(0);
2511   SDValue Trmp = Op.getOperand(1); // trampoline
2512   SDValue FPtr = Op.getOperand(2); // nested function
2513   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2514   SDLoc dl(Op);
2515
2516   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2517   bool isPPC64 = (PtrVT == MVT::i64);
2518   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2519
2520   TargetLowering::ArgListTy Args;
2521   TargetLowering::ArgListEntry Entry;
2522
2523   Entry.Ty = IntPtrTy;
2524   Entry.Node = Trmp; Args.push_back(Entry);
2525
2526   // TrampSize == (isPPC64 ? 48 : 40);
2527   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2528                                isPPC64 ? MVT::i64 : MVT::i32);
2529   Args.push_back(Entry);
2530
2531   Entry.Node = FPtr; Args.push_back(Entry);
2532   Entry.Node = Nest; Args.push_back(Entry);
2533
2534   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2535   TargetLowering::CallLoweringInfo CLI(DAG);
2536   CLI.setDebugLoc(dl).setChain(Chain)
2537     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2538                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2539                std::move(Args));
2540
2541   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2542   return CallResult.second;
2543 }
2544
2545 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2546   MachineFunction &MF = DAG.getMachineFunction();
2547   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2548   EVT PtrVT = getPointerTy(MF.getDataLayout());
2549
2550   SDLoc dl(Op);
2551
2552   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2553     // vastart just stores the address of the VarArgsFrameIndex slot into the
2554     // memory location argument.
2555     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2556     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2557     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2558                         MachinePointerInfo(SV));
2559   }
2560
2561   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2562   // We suppose the given va_list is already allocated.
2563   //
2564   // typedef struct {
2565   //  char gpr;     /* index into the array of 8 GPRs
2566   //                 * stored in the register save area
2567   //                 * gpr=0 corresponds to r3,
2568   //                 * gpr=1 to r4, etc.
2569   //                 */
2570   //  char fpr;     /* index into the array of 8 FPRs
2571   //                 * stored in the register save area
2572   //                 * fpr=0 corresponds to f1,
2573   //                 * fpr=1 to f2, etc.
2574   //                 */
2575   //  char *overflow_arg_area;
2576   //                /* location on stack that holds
2577   //                 * the next overflow argument
2578   //                 */
2579   //  char *reg_save_area;
2580   //               /* where r3:r10 and f1:f8 (if saved)
2581   //                * are stored
2582   //                */
2583   // } va_list[1];
2584
2585   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2586   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2587   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2588                                             PtrVT);
2589   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2590                                  PtrVT);
2591
2592   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2593   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2594
2595   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2596   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2597
2598   uint64_t FPROffset = 1;
2599   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2600
2601   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2602
2603   // Store first byte : number of int regs
2604   SDValue firstStore =
2605       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2606                         MachinePointerInfo(SV), MVT::i8);
2607   uint64_t nextOffset = FPROffset;
2608   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2609                                   ConstFPROffset);
2610
2611   // Store second byte : number of float regs
2612   SDValue secondStore =
2613       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2614                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2615   nextOffset += StackOffset;
2616   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2617
2618   // Store second word : arguments given on stack
2619   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2620                                     MachinePointerInfo(SV, nextOffset));
2621   nextOffset += FrameOffset;
2622   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2623
2624   // Store third word : arguments given in registers
2625   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2626                       MachinePointerInfo(SV, nextOffset));
2627 }
2628
2629 #include "PPCGenCallingConv.inc"
2630
2631 // Function whose sole purpose is to kill compiler warnings
2632 // stemming from unused functions included from PPCGenCallingConv.inc.
2633 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2634   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2635 }
2636
2637 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2638                                       CCValAssign::LocInfo &LocInfo,
2639                                       ISD::ArgFlagsTy &ArgFlags,
2640                                       CCState &State) {
2641   return true;
2642 }
2643
2644 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2645                                              MVT &LocVT,
2646                                              CCValAssign::LocInfo &LocInfo,
2647                                              ISD::ArgFlagsTy &ArgFlags,
2648                                              CCState &State) {
2649   static const MCPhysReg ArgRegs[] = {
2650     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2651     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2652   };
2653   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2654
2655   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2656
2657   // Skip one register if the first unallocated register has an even register
2658   // number and there are still argument registers available which have not been
2659   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2660   // need to skip a register if RegNum is odd.
2661   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2662     State.AllocateReg(ArgRegs[RegNum]);
2663   }
2664
2665   // Always return false here, as this function only makes sure that the first
2666   // unallocated register has an odd register number and does not actually
2667   // allocate a register for the current argument.
2668   return false;
2669 }
2670
2671 bool 
2672 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2673                                                   MVT &LocVT,
2674                                                   CCValAssign::LocInfo &LocInfo,
2675                                                   ISD::ArgFlagsTy &ArgFlags,
2676                                                   CCState &State) {
2677   static const MCPhysReg ArgRegs[] = {
2678     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2679     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2680   };
2681   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2682
2683   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2684   int RegsLeft = NumArgRegs - RegNum;
2685
2686   // Skip if there is not enough registers left for long double type (4 gpr regs 
2687   // in soft float mode) and put long double argument on the stack.
2688   if (RegNum != NumArgRegs && RegsLeft < 4) {
2689     for (int i = 0; i < RegsLeft; i++) {
2690       State.AllocateReg(ArgRegs[RegNum + i]);
2691     }
2692   }
2693
2694   return false;
2695 }
2696
2697 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2698                                                MVT &LocVT,
2699                                                CCValAssign::LocInfo &LocInfo,
2700                                                ISD::ArgFlagsTy &ArgFlags,
2701                                                CCState &State) {
2702   static const MCPhysReg ArgRegs[] = {
2703     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2704     PPC::F8
2705   };
2706
2707   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2708
2709   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2710
2711   // If there is only one Floating-point register left we need to put both f64
2712   // values of a split ppc_fp128 value on the stack.
2713   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2714     State.AllocateReg(ArgRegs[RegNum]);
2715   }
2716
2717   // Always return false here, as this function only makes sure that the two f64
2718   // values a ppc_fp128 value is split into are both passed in registers or both
2719   // passed on the stack and does not actually allocate a register for the
2720   // current argument.
2721   return false;
2722 }
2723
2724 /// FPR - The set of FP registers that should be allocated for arguments,
2725 /// on Darwin.
2726 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2727                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2728                                 PPC::F11, PPC::F12, PPC::F13};
2729
2730 /// QFPR - The set of QPX registers that should be allocated for arguments.
2731 static const MCPhysReg QFPR[] = {
2732     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2733     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2734
2735 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2736 /// the stack.
2737 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2738                                        unsigned PtrByteSize) {
2739   unsigned ArgSize = ArgVT.getStoreSize();
2740   if (Flags.isByVal())
2741     ArgSize = Flags.getByValSize();
2742
2743   // Round up to multiples of the pointer size, except for array members,
2744   // which are always packed.
2745   if (!Flags.isInConsecutiveRegs())
2746     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2747
2748   return ArgSize;
2749 }
2750
2751 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2752 /// on the stack.
2753 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2754                                             ISD::ArgFlagsTy Flags,
2755                                             unsigned PtrByteSize) {
2756   unsigned Align = PtrByteSize;
2757
2758   // Altivec parameters are padded to a 16 byte boundary.
2759   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2760       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2761       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2762       ArgVT == MVT::v1i128)
2763     Align = 16;
2764   // QPX vector types stored in double-precision are padded to a 32 byte
2765   // boundary.
2766   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2767     Align = 32;
2768
2769   // ByVal parameters are aligned as requested.
2770   if (Flags.isByVal()) {
2771     unsigned BVAlign = Flags.getByValAlign();
2772     if (BVAlign > PtrByteSize) {
2773       if (BVAlign % PtrByteSize != 0)
2774           llvm_unreachable(
2775             "ByVal alignment is not a multiple of the pointer size");
2776
2777       Align = BVAlign;
2778     }
2779   }
2780
2781   // Array members are always packed to their original alignment.
2782   if (Flags.isInConsecutiveRegs()) {
2783     // If the array member was split into multiple registers, the first
2784     // needs to be aligned to the size of the full type.  (Except for
2785     // ppcf128, which is only aligned as its f64 components.)
2786     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2787       Align = OrigVT.getStoreSize();
2788     else
2789       Align = ArgVT.getStoreSize();
2790   }
2791
2792   return Align;
2793 }
2794
2795 /// CalculateStackSlotUsed - Return whether this argument will use its
2796 /// stack slot (instead of being passed in registers).  ArgOffset,
2797 /// AvailableFPRs, and AvailableVRs must hold the current argument
2798 /// position, and will be updated to account for this argument.
2799 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2800                                    ISD::ArgFlagsTy Flags,
2801                                    unsigned PtrByteSize,
2802                                    unsigned LinkageSize,
2803                                    unsigned ParamAreaSize,
2804                                    unsigned &ArgOffset,
2805                                    unsigned &AvailableFPRs,
2806                                    unsigned &AvailableVRs, bool HasQPX) {
2807   bool UseMemory = false;
2808
2809   // Respect alignment of argument on the stack.
2810   unsigned Align =
2811     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2812   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2813   // If there's no space left in the argument save area, we must
2814   // use memory (this check also catches zero-sized arguments).
2815   if (ArgOffset >= LinkageSize + ParamAreaSize)
2816     UseMemory = true;
2817
2818   // Allocate argument on the stack.
2819   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2820   if (Flags.isInConsecutiveRegsLast())
2821     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2822   // If we overran the argument save area, we must use memory
2823   // (this check catches arguments passed partially in memory)
2824   if (ArgOffset > LinkageSize + ParamAreaSize)
2825     UseMemory = true;
2826
2827   // However, if the argument is actually passed in an FPR or a VR,
2828   // we don't use memory after all.
2829   if (!Flags.isByVal()) {
2830     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2831         // QPX registers overlap with the scalar FP registers.
2832         (HasQPX && (ArgVT == MVT::v4f32 ||
2833                     ArgVT == MVT::v4f64 ||
2834                     ArgVT == MVT::v4i1)))
2835       if (AvailableFPRs > 0) {
2836         --AvailableFPRs;
2837         return false;
2838       }
2839     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2840         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2841         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2842         ArgVT == MVT::v1i128)
2843       if (AvailableVRs > 0) {
2844         --AvailableVRs;
2845         return false;
2846       }
2847   }
2848
2849   return UseMemory;
2850 }
2851
2852 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2853 /// ensure minimum alignment required for target.
2854 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2855                                      unsigned NumBytes) {
2856   unsigned TargetAlign = Lowering->getStackAlignment();
2857   unsigned AlignMask = TargetAlign - 1;
2858   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2859   return NumBytes;
2860 }
2861
2862 SDValue PPCTargetLowering::LowerFormalArguments(
2863     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2864     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2865     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2866   if (Subtarget.isSVR4ABI()) {
2867     if (Subtarget.isPPC64())
2868       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2869                                          dl, DAG, InVals);
2870     else
2871       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2872                                          dl, DAG, InVals);
2873   } else {
2874     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2875                                        dl, DAG, InVals);
2876   }
2877 }
2878
2879 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2880     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2881     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2882     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2883
2884   // 32-bit SVR4 ABI Stack Frame Layout:
2885   //              +-----------------------------------+
2886   //        +-->  |            Back chain             |
2887   //        |     +-----------------------------------+
2888   //        |     | Floating-point register save area |
2889   //        |     +-----------------------------------+
2890   //        |     |    General register save area     |
2891   //        |     +-----------------------------------+
2892   //        |     |          CR save word             |
2893   //        |     +-----------------------------------+
2894   //        |     |         VRSAVE save word          |
2895   //        |     +-----------------------------------+
2896   //        |     |         Alignment padding         |
2897   //        |     +-----------------------------------+
2898   //        |     |     Vector register save area     |
2899   //        |     +-----------------------------------+
2900   //        |     |       Local variable space        |
2901   //        |     +-----------------------------------+
2902   //        |     |        Parameter list area        |
2903   //        |     +-----------------------------------+
2904   //        |     |           LR save word            |
2905   //        |     +-----------------------------------+
2906   // SP-->  +---  |            Back chain             |
2907   //              +-----------------------------------+
2908   //
2909   // Specifications:
2910   //   System V Application Binary Interface PowerPC Processor Supplement
2911   //   AltiVec Technology Programming Interface Manual
2912
2913   MachineFunction &MF = DAG.getMachineFunction();
2914   MachineFrameInfo &MFI = MF.getFrameInfo();
2915   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2916
2917   EVT PtrVT = getPointerTy(MF.getDataLayout());
2918   // Potential tail calls could cause overwriting of argument stack slots.
2919   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2920                        (CallConv == CallingConv::Fast));
2921   unsigned PtrByteSize = 4;
2922
2923   // Assign locations to all of the incoming arguments.
2924   SmallVector<CCValAssign, 16> ArgLocs;
2925   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2926                  *DAG.getContext());
2927
2928   // Reserve space for the linkage area on the stack.
2929   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2930   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2931   if (useSoftFloat())
2932     CCInfo.PreAnalyzeFormalArguments(Ins);
2933
2934   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2935   CCInfo.clearWasPPCF128();
2936
2937   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2938     CCValAssign &VA = ArgLocs[i];
2939
2940     // Arguments stored in registers.
2941     if (VA.isRegLoc()) {
2942       const TargetRegisterClass *RC;
2943       EVT ValVT = VA.getValVT();
2944
2945       switch (ValVT.getSimpleVT().SimpleTy) {
2946         default:
2947           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2948         case MVT::i1:
2949         case MVT::i32:
2950           RC = &PPC::GPRCRegClass;
2951           break;
2952         case MVT::f32:
2953           if (Subtarget.hasP8Vector())
2954             RC = &PPC::VSSRCRegClass;
2955           else
2956             RC = &PPC::F4RCRegClass;
2957           break;
2958         case MVT::f64:
2959           if (Subtarget.hasVSX())
2960             RC = &PPC::VSFRCRegClass;
2961           else
2962             RC = &PPC::F8RCRegClass;
2963           break;
2964         case MVT::v16i8:
2965         case MVT::v8i16:
2966         case MVT::v4i32:
2967           RC = &PPC::VRRCRegClass;
2968           break;
2969         case MVT::v4f32:
2970           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2971           break;
2972         case MVT::v2f64:
2973         case MVT::v2i64:
2974           RC = &PPC::VSHRCRegClass;
2975           break;
2976         case MVT::v4f64:
2977           RC = &PPC::QFRCRegClass;
2978           break;
2979         case MVT::v4i1:
2980           RC = &PPC::QBRCRegClass;
2981           break;
2982       }
2983
2984       // Transform the arguments stored in physical registers into virtual ones.
2985       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2986       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2987                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2988
2989       if (ValVT == MVT::i1)
2990         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2991
2992       InVals.push_back(ArgValue);
2993     } else {
2994       // Argument stored in memory.
2995       assert(VA.isMemLoc());
2996
2997       unsigned ArgSize = VA.getLocVT().getStoreSize();
2998       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2999                                      isImmutable);
3000
3001       // Create load nodes to retrieve arguments from the stack.
3002       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3003       InVals.push_back(
3004           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3005     }
3006   }
3007
3008   // Assign locations to all of the incoming aggregate by value arguments.
3009   // Aggregates passed by value are stored in the local variable space of the
3010   // caller's stack frame, right above the parameter list area.
3011   SmallVector<CCValAssign, 16> ByValArgLocs;
3012   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3013                       ByValArgLocs, *DAG.getContext());
3014
3015   // Reserve stack space for the allocations in CCInfo.
3016   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3017
3018   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3019
3020   // Area that is at least reserved in the caller of this function.
3021   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3022   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3023
3024   // Set the size that is at least reserved in caller of this function.  Tail
3025   // call optimized function's reserved stack space needs to be aligned so that
3026   // taking the difference between two stack areas will result in an aligned
3027   // stack.
3028   MinReservedArea =
3029       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3030   FuncInfo->setMinReservedArea(MinReservedArea);
3031
3032   SmallVector<SDValue, 8> MemOps;
3033
3034   // If the function takes variable number of arguments, make a frame index for
3035   // the start of the first vararg value... for expansion of llvm.va_start.
3036   if (isVarArg) {
3037     static const MCPhysReg GPArgRegs[] = {
3038       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3039       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3040     };
3041     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3042
3043     static const MCPhysReg FPArgRegs[] = {
3044       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3045       PPC::F8
3046     };
3047     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3048
3049     if (useSoftFloat())
3050        NumFPArgRegs = 0;
3051
3052     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3053     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3054
3055     // Make room for NumGPArgRegs and NumFPArgRegs.
3056     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3057                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3058
3059     FuncInfo->setVarArgsStackOffset(
3060       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3061                             CCInfo.getNextStackOffset(), true));
3062
3063     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3064     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3065
3066     // The fixed integer arguments of a variadic function are stored to the
3067     // VarArgsFrameIndex on the stack so that they may be loaded by
3068     // dereferencing the result of va_next.
3069     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3070       // Get an existing live-in vreg, or add a new one.
3071       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3072       if (!VReg)
3073         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3074
3075       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3076       SDValue Store =
3077           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3078       MemOps.push_back(Store);
3079       // Increment the address by four for the next argument to store
3080       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3081       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3082     }
3083
3084     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3085     // is set.
3086     // The double arguments are stored to the VarArgsFrameIndex
3087     // on the stack.
3088     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3089       // Get an existing live-in vreg, or add a new one.
3090       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3091       if (!VReg)
3092         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3093
3094       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3095       SDValue Store =
3096           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3097       MemOps.push_back(Store);
3098       // Increment the address by eight for the next argument to store
3099       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3100                                          PtrVT);
3101       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3102     }
3103   }
3104
3105   if (!MemOps.empty())
3106     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3107
3108   return Chain;
3109 }
3110
3111 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3112 // value to MVT::i64 and then truncate to the correct register size.
3113 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3114                                              EVT ObjectVT, SelectionDAG &DAG,
3115                                              SDValue ArgVal,
3116                                              const SDLoc &dl) const {
3117   if (Flags.isSExt())
3118     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3119                          DAG.getValueType(ObjectVT));
3120   else if (Flags.isZExt())
3121     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3122                          DAG.getValueType(ObjectVT));
3123
3124   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3125 }
3126
3127 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3128     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3129     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3130     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3131   // TODO: add description of PPC stack frame format, or at least some docs.
3132   //
3133   bool isELFv2ABI = Subtarget.isELFv2ABI();
3134   bool isLittleEndian = Subtarget.isLittleEndian();
3135   MachineFunction &MF = DAG.getMachineFunction();
3136   MachineFrameInfo &MFI = MF.getFrameInfo();
3137   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3138
3139   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3140          "fastcc not supported on varargs functions");
3141
3142   EVT PtrVT = getPointerTy(MF.getDataLayout());
3143   // Potential tail calls could cause overwriting of argument stack slots.
3144   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3145                        (CallConv == CallingConv::Fast));
3146   unsigned PtrByteSize = 8;
3147   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3148
3149   static const MCPhysReg GPR[] = {
3150     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3151     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3152   };
3153   static const MCPhysReg VR[] = {
3154     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3155     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3156   };
3157   static const MCPhysReg VSRH[] = {
3158     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3159     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3160   };
3161
3162   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3163   const unsigned Num_FPR_Regs = 13;
3164   const unsigned Num_VR_Regs  = array_lengthof(VR);
3165   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3166
3167   // Do a first pass over the arguments to determine whether the ABI
3168   // guarantees that our caller has allocated the parameter save area
3169   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3170   // in the ELFv2 ABI, it is true if this is a vararg function or if
3171   // any parameter is located in a stack slot.
3172
3173   bool HasParameterArea = !isELFv2ABI || isVarArg;
3174   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3175   unsigned NumBytes = LinkageSize;
3176   unsigned AvailableFPRs = Num_FPR_Regs;
3177   unsigned AvailableVRs = Num_VR_Regs;
3178   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3179     if (Ins[i].Flags.isNest())
3180       continue;
3181
3182     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3183                                PtrByteSize, LinkageSize, ParamAreaSize,
3184                                NumBytes, AvailableFPRs, AvailableVRs,
3185                                Subtarget.hasQPX()))
3186       HasParameterArea = true;
3187   }
3188
3189   // Add DAG nodes to load the arguments or copy them out of registers.  On
3190   // entry to a function on PPC, the arguments start after the linkage area,
3191   // although the first ones are often in registers.
3192
3193   unsigned ArgOffset = LinkageSize;
3194   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3195   unsigned &QFPR_idx = FPR_idx;
3196   SmallVector<SDValue, 8> MemOps;
3197   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3198   unsigned CurArgIdx = 0;
3199   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3200     SDValue ArgVal;
3201     bool needsLoad = false;
3202     EVT ObjectVT = Ins[ArgNo].VT;
3203     EVT OrigVT = Ins[ArgNo].ArgVT;
3204     unsigned ObjSize = ObjectVT.getStoreSize();
3205     unsigned ArgSize = ObjSize;
3206     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3207     if (Ins[ArgNo].isOrigArg()) {
3208       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3209       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3210     }
3211     // We re-align the argument offset for each argument, except when using the
3212     // fast calling convention, when we need to make sure we do that only when
3213     // we'll actually use a stack slot.
3214     unsigned CurArgOffset, Align;
3215     auto ComputeArgOffset = [&]() {
3216       /* Respect alignment of argument on the stack.  */
3217       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3218       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3219       CurArgOffset = ArgOffset;
3220     };
3221
3222     if (CallConv != CallingConv::Fast) {
3223       ComputeArgOffset();
3224
3225       /* Compute GPR index associated with argument offset.  */
3226       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3227       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3228     }
3229
3230     // FIXME the codegen can be much improved in some cases.
3231     // We do not have to keep everything in memory.
3232     if (Flags.isByVal()) {
3233       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3234
3235       if (CallConv == CallingConv::Fast)
3236         ComputeArgOffset();
3237
3238       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3239       ObjSize = Flags.getByValSize();
3240       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3241       // Empty aggregate parameters do not take up registers.  Examples:
3242       //   struct { } a;
3243       //   union  { } b;
3244       //   int c[0];
3245       // etc.  However, we have to provide a place-holder in InVals, so
3246       // pretend we have an 8-byte item at the current address for that
3247       // purpose.
3248       if (!ObjSize) {
3249         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3250         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3251         InVals.push_back(FIN);
3252         continue;
3253       }
3254
3255       // Create a stack object covering all stack doublewords occupied
3256       // by the argument.  If the argument is (fully or partially) on
3257       // the stack, or if the argument is fully in registers but the
3258       // caller has allocated the parameter save anyway, we can refer
3259       // directly to the caller's stack frame.  Otherwise, create a
3260       // local copy in our own frame.
3261       int FI;
3262       if (HasParameterArea ||
3263           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3264         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3265       else
3266         FI = MFI.CreateStackObject(ArgSize, Align, false);
3267       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3268
3269       // Handle aggregates smaller than 8 bytes.
3270       if (ObjSize < PtrByteSize) {
3271         // The value of the object is its address, which differs from the
3272         // address of the enclosing doubleword on big-endian systems.
3273         SDValue Arg = FIN;
3274         if (!isLittleEndian) {
3275           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3276           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3277         }
3278         InVals.push_back(Arg);
3279
3280         if (GPR_idx != Num_GPR_Regs) {
3281           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3282           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3283           SDValue Store;
3284
3285           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3286             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3287                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3288             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3289                                       MachinePointerInfo(&*FuncArg), ObjType);
3290           } else {
3291             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3292             // store the whole register as-is to the parameter save area
3293             // slot.
3294             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3295                                  MachinePointerInfo(&*FuncArg));
3296           }
3297
3298           MemOps.push_back(Store);
3299         }
3300         // Whether we copied from a register or not, advance the offset
3301         // into the parameter save area by a full doubleword.
3302         ArgOffset += PtrByteSize;
3303         continue;
3304       }
3305
3306       // The value of the object is its address, which is the address of
3307       // its first stack doubleword.
3308       InVals.push_back(FIN);
3309
3310       // Store whatever pieces of the object are in registers to memory.
3311       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3312         if (GPR_idx == Num_GPR_Regs)
3313           break;
3314
3315         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3316         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3317         SDValue Addr = FIN;
3318         if (j) {
3319           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3320           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3321         }
3322         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3323                                      MachinePointerInfo(&*FuncArg, j));
3324         MemOps.push_back(Store);
3325         ++GPR_idx;
3326       }
3327       ArgOffset += ArgSize;
3328       continue;
3329     }
3330
3331     switch (ObjectVT.getSimpleVT().SimpleTy) {
3332     default: llvm_unreachable("Unhandled argument type!");
3333     case MVT::i1:
3334     case MVT::i32:
3335     case MVT::i64:
3336       if (Flags.isNest()) {
3337         // The 'nest' parameter, if any, is passed in R11.
3338         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3339         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3340
3341         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3342           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3343
3344         break;
3345       }
3346
3347       // These can be scalar arguments or elements of an integer array type
3348       // passed directly.  Clang may use those instead of "byval" aggregate
3349       // types to avoid forcing arguments to memory unnecessarily.
3350       if (GPR_idx != Num_GPR_Regs) {
3351         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3352         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3353
3354         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3355           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3356           // value to MVT::i64 and then truncate to the correct register size.
3357           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3358       } else {
3359         if (CallConv == CallingConv::Fast)
3360           ComputeArgOffset();
3361
3362         needsLoad = true;
3363         ArgSize = PtrByteSize;
3364       }
3365       if (CallConv != CallingConv::Fast || needsLoad)
3366         ArgOffset += 8;
3367       break;
3368
3369     case MVT::f32:
3370     case MVT::f64:
3371       // These can be scalar arguments or elements of a float array type
3372       // passed directly.  The latter are used to implement ELFv2 homogenous
3373       // float aggregates.
3374       if (FPR_idx != Num_FPR_Regs) {
3375         unsigned VReg;
3376
3377         if (ObjectVT == MVT::f32)
3378           VReg = MF.addLiveIn(FPR[FPR_idx],
3379                               Subtarget.hasP8Vector()
3380                                   ? &PPC::VSSRCRegClass
3381                                   : &PPC::F4RCRegClass);
3382         else
3383           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3384                                                 ? &PPC::VSFRCRegClass
3385                                                 : &PPC::F8RCRegClass);
3386
3387         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3388         ++FPR_idx;
3389       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3390         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3391         // once we support fp <-> gpr moves.
3392
3393         // This can only ever happen in the presence of f32 array types,
3394         // since otherwise we never run out of FPRs before running out
3395         // of GPRs.
3396         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3397         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3398
3399         if (ObjectVT == MVT::f32) {
3400           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3401             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3402                                  DAG.getConstant(32, dl, MVT::i32));
3403           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3404         }
3405
3406         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3407       } else {
3408         if (CallConv == CallingConv::Fast)
3409           ComputeArgOffset();
3410
3411         needsLoad = true;
3412       }
3413
3414       // When passing an array of floats, the array occupies consecutive
3415       // space in the argument area; only round up to the next doubleword
3416       // at the end of the array.  Otherwise, each float takes 8 bytes.
3417       if (CallConv != CallingConv::Fast || needsLoad) {
3418         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3419         ArgOffset += ArgSize;
3420         if (Flags.isInConsecutiveRegsLast())
3421           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3422       }
3423       break;
3424     case MVT::v4f32:
3425     case MVT::v4i32:
3426     case MVT::v8i16:
3427     case MVT::v16i8:
3428     case MVT::v2f64:
3429     case MVT::v2i64:
3430     case MVT::v1i128:
3431       if (!Subtarget.hasQPX()) {
3432       // These can be scalar arguments or elements of a vector array type
3433       // passed directly.  The latter are used to implement ELFv2 homogenous
3434       // vector aggregates.
3435       if (VR_idx != Num_VR_Regs) {
3436         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3437                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3438                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3439         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3440         ++VR_idx;
3441       } else {
3442         if (CallConv == CallingConv::Fast)
3443           ComputeArgOffset();
3444
3445         needsLoad = true;
3446       }
3447       if (CallConv != CallingConv::Fast || needsLoad)
3448         ArgOffset += 16;
3449       break;
3450       } // not QPX
3451
3452       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3453              "Invalid QPX parameter type");
3454       /* fall through */
3455
3456     case MVT::v4f64:
3457     case MVT::v4i1:
3458       // QPX vectors are treated like their scalar floating-point subregisters
3459       // (except that they're larger).
3460       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3461       if (QFPR_idx != Num_QFPR_Regs) {
3462         const TargetRegisterClass *RC;
3463         switch (ObjectVT.getSimpleVT().SimpleTy) {
3464         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3465         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3466         default:         RC = &PPC::QBRCRegClass; break;
3467         }
3468
3469         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3470         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3471         ++QFPR_idx;
3472       } else {
3473         if (CallConv == CallingConv::Fast)
3474           ComputeArgOffset();
3475         needsLoad = true;
3476       }
3477       if (CallConv != CallingConv::Fast || needsLoad)
3478         ArgOffset += Sz;
3479       break;
3480     }
3481
3482     // We need to load the argument to a virtual register if we determined
3483     // above that we ran out of physical registers of the appropriate type.
3484     if (needsLoad) {
3485       if (ObjSize < ArgSize && !isLittleEndian)
3486         CurArgOffset += ArgSize - ObjSize;
3487       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3488       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3489       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3490     }
3491
3492     InVals.push_back(ArgVal);
3493   }
3494
3495   // Area that is at least reserved in the caller of this function.
3496   unsigned MinReservedArea;
3497   if (HasParameterArea)
3498     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3499   else
3500     MinReservedArea = LinkageSize;
3501
3502   // Set the size that is at least reserved in caller of this function.  Tail
3503   // call optimized functions' reserved stack space needs to be aligned so that
3504   // taking the difference between two stack areas will result in an aligned
3505   // stack.
3506   MinReservedArea =
3507       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3508   FuncInfo->setMinReservedArea(MinReservedArea);
3509
3510   // If the function takes variable number of arguments, make a frame index for
3511   // the start of the first vararg value... for expansion of llvm.va_start.
3512   if (isVarArg) {
3513     int Depth = ArgOffset;
3514
3515     FuncInfo->setVarArgsFrameIndex(
3516       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3517     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3518
3519     // If this function is vararg, store any remaining integer argument regs
3520     // to their spots on the stack so that they may be loaded by dereferencing
3521     // the result of va_next.
3522     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3523          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3524       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3525       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3526       SDValue Store =
3527           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3528       MemOps.push_back(Store);
3529       // Increment the address by four for the next argument to store
3530       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3531       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3532     }
3533   }
3534
3535   if (!MemOps.empty())
3536     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3537
3538   return Chain;
3539 }
3540
3541 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3542     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3543     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3544     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3545   // TODO: add description of PPC stack frame format, or at least some docs.
3546   //
3547   MachineFunction &MF = DAG.getMachineFunction();
3548   MachineFrameInfo &MFI = MF.getFrameInfo();
3549   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3550
3551   EVT PtrVT = getPointerTy(MF.getDataLayout());
3552   bool isPPC64 = PtrVT == MVT::i64;
3553   // Potential tail calls could cause overwriting of argument stack slots.
3554   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3555                        (CallConv == CallingConv::Fast));
3556   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3557   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3558   unsigned ArgOffset = LinkageSize;
3559   // Area that is at least reserved in caller of this function.
3560   unsigned MinReservedArea = ArgOffset;
3561
3562   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3563     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3564     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3565   };
3566   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3567     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3568     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3569   };
3570   static const MCPhysReg VR[] = {
3571     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3572     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3573   };
3574
3575   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3576   const unsigned Num_FPR_Regs = 13;
3577   const unsigned Num_VR_Regs  = array_lengthof( VR);
3578
3579   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3580
3581   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3582
3583   // In 32-bit non-varargs functions, the stack space for vectors is after the
3584   // stack space for non-vectors.  We do not use this space unless we have
3585   // too many vectors to fit in registers, something that only occurs in
3586   // constructed examples:), but we have to walk the arglist to figure
3587   // that out...for the pathological case, compute VecArgOffset as the
3588   // start of the vector parameter area.  Computing VecArgOffset is the
3589   // entire point of the following loop.
3590   unsigned VecArgOffset = ArgOffset;
3591   if (!isVarArg && !isPPC64) {
3592     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3593          ++ArgNo) {
3594       EVT ObjectVT = Ins[ArgNo].VT;
3595       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3596
3597       if (Flags.isByVal()) {
3598         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3599         unsigned ObjSize = Flags.getByValSize();
3600         unsigned ArgSize =
3601                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3602         VecArgOffset += ArgSize;
3603         continue;
3604       }
3605
3606       switch(ObjectVT.getSimpleVT().SimpleTy) {
3607       default: llvm_unreachable("Unhandled argument type!");
3608       case MVT::i1:
3609       case MVT::i32:
3610       case MVT::f32:
3611         VecArgOffset += 4;
3612         break;
3613       case MVT::i64:  // PPC64
3614       case MVT::f64:
3615         // FIXME: We are guaranteed to be !isPPC64 at this point.
3616         // Does MVT::i64 apply?
3617         VecArgOffset += 8;
3618         break;
3619       case MVT::v4f32:
3620       case MVT::v4i32:
3621       case MVT::v8i16:
3622       case MVT::v16i8:
3623         // Nothing to do, we're only looking at Nonvector args here.
3624         break;
3625       }
3626     }
3627   }
3628   // We've found where the vector parameter area in memory is.  Skip the
3629   // first 12 parameters; these don't use that memory.
3630   VecArgOffset = ((VecArgOffset+15)/16)*16;
3631   VecArgOffset += 12*16;
3632
3633   // Add DAG nodes to load the arguments or copy them out of registers.  On
3634   // entry to a function on PPC, the arguments start after the linkage area,
3635   // although the first ones are often in registers.
3636
3637   SmallVector<SDValue, 8> MemOps;
3638   unsigned nAltivecParamsAtEnd = 0;
3639   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3640   unsigned CurArgIdx = 0;
3641   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3642     SDValue ArgVal;
3643     bool needsLoad = false;
3644     EVT ObjectVT = Ins[ArgNo].VT;
3645     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3646     unsigned ArgSize = ObjSize;
3647     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3648     if (Ins[ArgNo].isOrigArg()) {
3649       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3650       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3651     }
3652     unsigned CurArgOffset = ArgOffset;
3653
3654     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3655     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3656         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3657       if (isVarArg || isPPC64) {
3658         MinReservedArea = ((MinReservedArea+15)/16)*16;
3659         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3660                                                   Flags,
3661                                                   PtrByteSize);
3662       } else  nAltivecParamsAtEnd++;
3663     } else
3664       // Calculate min reserved area.
3665       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3666                                                 Flags,
3667                                                 PtrByteSize);
3668
3669     // FIXME the codegen can be much improved in some cases.
3670     // We do not have to keep everything in memory.
3671     if (Flags.isByVal()) {
3672       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3673
3674       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3675       ObjSize = Flags.getByValSize();
3676       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3677       // Objects of size 1 and 2 are right justified, everything else is
3678       // left justified.  This means the memory address is adjusted forwards.
3679       if (ObjSize==1 || ObjSize==2) {
3680         CurArgOffset = CurArgOffset + (4 - ObjSize);
3681       }
3682       // The value of the object is its address.
3683       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3684       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3685       InVals.push_back(FIN);
3686       if (ObjSize==1 || ObjSize==2) {
3687         if (GPR_idx != Num_GPR_Regs) {
3688           unsigned VReg;
3689           if (isPPC64)
3690             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3691           else
3692             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3693           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3694           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3695           SDValue Store =
3696               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3697                                 MachinePointerInfo(&*FuncArg), ObjType);
3698           MemOps.push_back(Store);
3699           ++GPR_idx;
3700         }
3701
3702         ArgOffset += PtrByteSize;
3703
3704         continue;
3705       }
3706       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3707         // Store whatever pieces of the object are in registers
3708         // to memory.  ArgOffset will be the address of the beginning
3709         // of the object.
3710         if (GPR_idx != Num_GPR_Regs) {
3711           unsigned VReg;
3712           if (isPPC64)
3713             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3714           else
3715             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3716           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3717           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3718           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3719           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3720                                        MachinePointerInfo(&*FuncArg, j));
3721           MemOps.push_back(Store);
3722           ++GPR_idx;
3723           ArgOffset += PtrByteSize;
3724         } else {
3725           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3726           break;
3727         }
3728       }
3729       continue;
3730     }
3731
3732     switch (ObjectVT.getSimpleVT().SimpleTy) {
3733     default: llvm_unreachable("Unhandled argument type!");
3734     case MVT::i1:
3735     case MVT::i32:
3736       if (!isPPC64) {
3737         if (GPR_idx != Num_GPR_Regs) {
3738           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3739           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3740
3741           if (ObjectVT == MVT::i1)
3742             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3743
3744           ++GPR_idx;
3745         } else {
3746           needsLoad = true;
3747           ArgSize = PtrByteSize;
3748         }
3749         // All int arguments reserve stack space in the Darwin ABI.
3750         ArgOffset += PtrByteSize;
3751         break;
3752       }
3753       LLVM_FALLTHROUGH;
3754     case MVT::i64:  // PPC64
3755       if (GPR_idx != Num_GPR_Regs) {
3756         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3757         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3758
3759         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3760           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3761           // value to MVT::i64 and then truncate to the correct register size.
3762           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3763
3764         ++GPR_idx;
3765       } else {
3766         needsLoad = true;
3767         ArgSize = PtrByteSize;
3768       }
3769       // All int arguments reserve stack space in the Darwin ABI.
3770       ArgOffset += 8;
3771       break;
3772
3773     case MVT::f32:
3774     case MVT::f64:
3775       // Every 4 bytes of argument space consumes one of the GPRs available for
3776       // argument passing.
3777       if (GPR_idx != Num_GPR_Regs) {
3778         ++GPR_idx;
3779         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3780           ++GPR_idx;
3781       }
3782       if (FPR_idx != Num_FPR_Regs) {
3783         unsigned VReg;
3784
3785         if (ObjectVT == MVT::f32)
3786           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3787         else
3788           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3789
3790         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3791         ++FPR_idx;
3792       } else {
3793         needsLoad = true;
3794       }
3795
3796       // All FP arguments reserve stack space in the Darwin ABI.
3797       ArgOffset += isPPC64 ? 8 : ObjSize;
3798       break;
3799     case MVT::v4f32:
3800     case MVT::v4i32:
3801     case MVT::v8i16:
3802     case MVT::v16i8:
3803       // Note that vector arguments in registers don't reserve stack space,
3804       // except in varargs functions.
3805       if (VR_idx != Num_VR_Regs) {
3806         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3807         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3808         if (isVarArg) {
3809           while ((ArgOffset % 16) != 0) {
3810             ArgOffset += PtrByteSize;
3811             if (GPR_idx != Num_GPR_Regs)
3812               GPR_idx++;
3813           }
3814           ArgOffset += 16;
3815           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3816         }
3817         ++VR_idx;
3818       } else {
3819         if (!isVarArg && !isPPC64) {
3820           // Vectors go after all the nonvectors.
3821           CurArgOffset = VecArgOffset;
3822           VecArgOffset += 16;
3823         } else {
3824           // Vectors are aligned.
3825           ArgOffset = ((ArgOffset+15)/16)*16;
3826           CurArgOffset = ArgOffset;
3827           ArgOffset += 16;
3828         }
3829         needsLoad = true;
3830       }
3831       break;
3832     }
3833
3834     // We need to load the argument to a virtual register if we determined above
3835     // that we ran out of physical registers of the appropriate type.
3836     if (needsLoad) {
3837       int FI = MFI.CreateFixedObject(ObjSize,
3838                                      CurArgOffset + (ArgSize - ObjSize),
3839                                      isImmutable);
3840       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3841       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3842     }
3843
3844     InVals.push_back(ArgVal);
3845   }
3846
3847   // Allow for Altivec parameters at the end, if needed.
3848   if (nAltivecParamsAtEnd) {
3849     MinReservedArea = ((MinReservedArea+15)/16)*16;
3850     MinReservedArea += 16*nAltivecParamsAtEnd;
3851   }
3852
3853   // Area that is at least reserved in the caller of this function.
3854   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3855
3856   // Set the size that is at least reserved in caller of this function.  Tail
3857   // call optimized functions' reserved stack space needs to be aligned so that
3858   // taking the difference between two stack areas will result in an aligned
3859   // stack.
3860   MinReservedArea =
3861       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3862   FuncInfo->setMinReservedArea(MinReservedArea);
3863
3864   // If the function takes variable number of arguments, make a frame index for
3865   // the start of the first vararg value... for expansion of llvm.va_start.
3866   if (isVarArg) {
3867     int Depth = ArgOffset;
3868
3869     FuncInfo->setVarArgsFrameIndex(
3870       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3871                             Depth, true));
3872     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3873
3874     // If this function is vararg, store any remaining integer argument regs
3875     // to their spots on the stack so that they may be loaded by dereferencing
3876     // the result of va_next.
3877     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3878       unsigned VReg;
3879
3880       if (isPPC64)
3881         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3882       else
3883         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3884
3885       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3886       SDValue Store =
3887           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3888       MemOps.push_back(Store);
3889       // Increment the address by four for the next argument to store
3890       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3891       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3892     }
3893   }
3894
3895   if (!MemOps.empty())
3896     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3897
3898   return Chain;
3899 }
3900
3901 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3902 /// adjusted to accommodate the arguments for the tailcall.
3903 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3904                                    unsigned ParamSize) {
3905
3906   if (!isTailCall) return 0;
3907
3908   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3909   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3910   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3911   // Remember only if the new adjustement is bigger.
3912   if (SPDiff < FI->getTailCallSPDelta())
3913     FI->setTailCallSPDelta(SPDiff);
3914
3915   return SPDiff;
3916 }
3917
3918 static bool isFunctionGlobalAddress(SDValue Callee);
3919
3920 static bool
3921 resideInSameModule(SDValue Callee, Reloc::Model RelMod) {
3922   // If !G, Callee can be an external symbol.
3923   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3924   if (!G) return false;
3925
3926   const GlobalValue *GV = G->getGlobal();
3927
3928   if (GV->isDeclaration()) return false;
3929
3930   switch(GV->getLinkage()) {
3931   default: llvm_unreachable("unknow linkage type");
3932   case GlobalValue::AvailableExternallyLinkage:
3933   case GlobalValue::ExternalWeakLinkage:
3934     return false;
3935
3936   // Callee with weak linkage is allowed if it has hidden or protected
3937   // visibility
3938   case GlobalValue::LinkOnceAnyLinkage:
3939   case GlobalValue::LinkOnceODRLinkage: // e.g. c++ inline functions
3940   case GlobalValue::WeakAnyLinkage:
3941   case GlobalValue::WeakODRLinkage:     // e.g. c++ template instantiation
3942     if (GV->hasDefaultVisibility())
3943       return false;
3944
3945   case GlobalValue::ExternalLinkage:
3946   case GlobalValue::InternalLinkage:
3947   case GlobalValue::PrivateLinkage:
3948     break;
3949   }
3950
3951   // With '-fPIC', calling default visiblity function need insert 'nop' after
3952   // function call, no matter that function resides in same module or not, so
3953   // we treat it as in different module.
3954   if (RelMod == Reloc::PIC_ && GV->hasDefaultVisibility())
3955     return false;
3956
3957   return true;
3958 }
3959
3960 static bool
3961 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
3962                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
3963   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
3964
3965   const unsigned PtrByteSize = 8;
3966   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3967
3968   static const MCPhysReg GPR[] = {
3969     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3970     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3971   };
3972   static const MCPhysReg VR[] = {
3973     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3974     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3975   };
3976
3977   const unsigned NumGPRs = array_lengthof(GPR);
3978   const unsigned NumFPRs = 13;
3979   const unsigned NumVRs = array_lengthof(VR);
3980   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
3981
3982   unsigned NumBytes = LinkageSize;
3983   unsigned AvailableFPRs = NumFPRs;
3984   unsigned AvailableVRs = NumVRs;
3985
3986   for (const ISD::OutputArg& Param : Outs) {
3987     if (Param.Flags.isNest()) continue;
3988
3989     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
3990                                PtrByteSize, LinkageSize, ParamAreaSize,
3991                                NumBytes, AvailableFPRs, AvailableVRs,
3992                                Subtarget.hasQPX()))
3993       return true;
3994   }
3995   return false;
3996 }
3997
3998 static bool
3999 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4000   if (CS->arg_size() != CallerFn->getArgumentList().size())
4001     return false;
4002
4003   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4004   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4005   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4006
4007   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4008     const Value* CalleeArg = *CalleeArgIter;
4009     const Value* CallerArg = &(*CallerArgIter);
4010     if (CalleeArg == CallerArg)
4011       continue;
4012
4013     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4014     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4015     //      }
4016     // 1st argument of callee is undef and has the same type as caller.
4017     if (CalleeArg->getType() == CallerArg->getType() &&
4018         isa<UndefValue>(CalleeArg))
4019       continue;
4020
4021     return false;
4022   }
4023
4024   return true;
4025 }
4026
4027 bool
4028 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4029                                     SDValue Callee,
4030                                     CallingConv::ID CalleeCC,
4031                                     ImmutableCallSite *CS,
4032                                     bool isVarArg,
4033                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4034                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4035                                     SelectionDAG& DAG) const {
4036   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4037
4038   if (DisableSCO && !TailCallOpt) return false;
4039
4040   // Variadic argument functions are not supported.
4041   if (isVarArg) return false;
4042
4043   MachineFunction &MF = DAG.getMachineFunction();
4044   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4045
4046   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4047   // the same calling convention
4048   if (CallerCC != CalleeCC) return false;
4049
4050   // SCO support C calling convention
4051   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4052     return false;
4053
4054   // Caller contains any byval parameter is not supported.
4055   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4056     return false;
4057
4058   // Callee contains any byval parameter is not supported, too.
4059   // Note: This is a quick work around, because in some cases, e.g.
4060   // caller's stack size > callee's stack size, we are still able to apply
4061   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4062   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4063     return false;
4064
4065   // No TCO/SCO on indirect call because Caller have to restore its TOC
4066   if (!isFunctionGlobalAddress(Callee) &&
4067       !isa<ExternalSymbolSDNode>(Callee))
4068     return false;
4069
4070   // Check if Callee resides in the same module, because for now, PPC64 SVR4 ABI
4071   // (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4072   // module.
4073   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4074   if (!resideInSameModule(Callee, getTargetMachine().getRelocationModel()))
4075     return false;
4076
4077   // TCO allows altering callee ABI, so we don't have to check further.
4078   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4079     return true;
4080
4081   if (DisableSCO) return false;
4082
4083   // If callee use the same argument list that caller is using, then we can
4084   // apply SCO on this case. If it is not, then we need to check if callee needs
4085   // stack for passing arguments.
4086   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4087       needStackSlotPassParameters(Subtarget, Outs)) {
4088     return false;
4089   }
4090
4091   return true;
4092 }
4093
4094 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4095 /// for tail call optimization. Targets which want to do tail call
4096 /// optimization should implement this function.
4097 bool
4098 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4099                                                      CallingConv::ID CalleeCC,
4100                                                      bool isVarArg,
4101                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4102                                                      SelectionDAG& DAG) const {
4103   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4104     return false;
4105
4106   // Variable argument functions are not supported.
4107   if (isVarArg)
4108     return false;
4109
4110   MachineFunction &MF = DAG.getMachineFunction();
4111   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4112   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4113     // Functions containing by val parameters are not supported.
4114     for (unsigned i = 0; i != Ins.size(); i++) {
4115        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4116        if (Flags.isByVal()) return false;
4117     }
4118
4119     // Non-PIC/GOT tail calls are supported.
4120     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4121       return true;
4122
4123     // At the moment we can only do local tail calls (in same module, hidden
4124     // or protected) if we are generating PIC.
4125     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4126       return G->getGlobal()->hasHiddenVisibility()
4127           || G->getGlobal()->hasProtectedVisibility();
4128   }
4129
4130   return false;
4131 }
4132
4133 /// isCallCompatibleAddress - Return the immediate to use if the specified
4134 /// 32-bit value is representable in the immediate field of a BxA instruction.
4135 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4136   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4137   if (!C) return nullptr;
4138
4139   int Addr = C->getZExtValue();
4140   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4141       SignExtend32<26>(Addr) != Addr)
4142     return nullptr;  // Top 6 bits have to be sext of immediate.
4143
4144   return DAG
4145       .getConstant(
4146           (int)C->getZExtValue() >> 2, SDLoc(Op),
4147           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4148       .getNode();
4149 }
4150
4151 namespace {
4152
4153 struct TailCallArgumentInfo {
4154   SDValue Arg;
4155   SDValue FrameIdxOp;
4156   int       FrameIdx;
4157
4158   TailCallArgumentInfo() : FrameIdx(0) {}
4159 };
4160 }
4161
4162 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4163 static void StoreTailCallArgumentsToStackSlot(
4164     SelectionDAG &DAG, SDValue Chain,
4165     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4166     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4167   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4168     SDValue Arg = TailCallArgs[i].Arg;
4169     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4170     int FI = TailCallArgs[i].FrameIdx;
4171     // Store relative to framepointer.
4172     MemOpChains.push_back(DAG.getStore(
4173         Chain, dl, Arg, FIN,
4174         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4175   }
4176 }
4177
4178 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4179 /// the appropriate stack slot for the tail call optimized function call.
4180 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4181                                              SDValue OldRetAddr, SDValue OldFP,
4182                                              int SPDiff, const SDLoc &dl) {
4183   if (SPDiff) {
4184     // Calculate the new stack slot for the return address.
4185     MachineFunction &MF = DAG.getMachineFunction();
4186     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4187     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4188     bool isPPC64 = Subtarget.isPPC64();
4189     int SlotSize = isPPC64 ? 8 : 4;
4190     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4191     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4192                                                          NewRetAddrLoc, true);
4193     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4194     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4195     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4196                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4197
4198     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4199     // slot as the FP is never overwritten.
4200     if (Subtarget.isDarwinABI()) {
4201       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4202       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4203                                                          true);
4204       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4205       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4206                            MachinePointerInfo::getFixedStack(
4207                                DAG.getMachineFunction(), NewFPIdx));
4208     }
4209   }
4210   return Chain;
4211 }
4212
4213 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4214 /// the position of the argument.
4215 static void
4216 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4217                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4218                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4219   int Offset = ArgOffset + SPDiff;
4220   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
4221   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4222   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4223   SDValue FIN = DAG.getFrameIndex(FI, VT);
4224   TailCallArgumentInfo Info;
4225   Info.Arg = Arg;
4226   Info.FrameIdxOp = FIN;
4227   Info.FrameIdx = FI;
4228   TailCallArguments.push_back(Info);
4229 }
4230
4231 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4232 /// stack slot. Returns the chain as result and the loaded frame pointers in
4233 /// LROpOut/FPOpout. Used when tail calling.
4234 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4235     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4236     SDValue &FPOpOut, const SDLoc &dl) const {
4237   if (SPDiff) {
4238     // Load the LR and FP stack slot for later adjusting.
4239     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4240     LROpOut = getReturnAddrFrameIndex(DAG);
4241     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4242     Chain = SDValue(LROpOut.getNode(), 1);
4243
4244     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4245     // slot as the FP is never overwritten.
4246     if (Subtarget.isDarwinABI()) {
4247       FPOpOut = getFramePointerFrameIndex(DAG);
4248       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4249       Chain = SDValue(FPOpOut.getNode(), 1);
4250     }
4251   }
4252   return Chain;
4253 }
4254
4255 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4256 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4257 /// specified by the specific parameter attribute. The copy will be passed as
4258 /// a byval function parameter.
4259 /// Sometimes what we are copying is the end of a larger object, the part that
4260 /// does not fit in registers.
4261 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4262                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4263                                          SelectionDAG &DAG, const SDLoc &dl) {
4264   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4265   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4266                        false, false, false, MachinePointerInfo(),
4267                        MachinePointerInfo());
4268 }
4269
4270 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4271 /// tail calls.
4272 static void LowerMemOpCallTo(
4273     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4274     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4275     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4276     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4277   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4278   if (!isTailCall) {
4279     if (isVector) {
4280       SDValue StackPtr;
4281       if (isPPC64)
4282         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4283       else
4284         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4285       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4286                            DAG.getConstant(ArgOffset, dl, PtrVT));
4287     }
4288     MemOpChains.push_back(
4289         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4290     // Calculate and remember argument location.
4291   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4292                                   TailCallArguments);
4293 }
4294
4295 static void
4296 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4297                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4298                 SDValue FPOp,
4299                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4300   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4301   // might overwrite each other in case of tail call optimization.
4302   SmallVector<SDValue, 8> MemOpChains2;
4303   // Do not flag preceding copytoreg stuff together with the following stuff.
4304   InFlag = SDValue();
4305   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4306                                     MemOpChains2, dl);
4307   if (!MemOpChains2.empty())
4308     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4309
4310   // Store the return address to the appropriate stack slot.
4311   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4312
4313   // Emit callseq_end just before tailcall node.
4314   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4315                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4316   InFlag = Chain.getValue(1);
4317 }
4318
4319 // Is this global address that of a function that can be called by name? (as
4320 // opposed to something that must hold a descriptor for an indirect call).
4321 static bool isFunctionGlobalAddress(SDValue Callee) {
4322   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4323     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4324         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4325       return false;
4326
4327     return G->getGlobal()->getValueType()->isFunctionTy();
4328   }
4329
4330   return false;
4331 }
4332
4333 static unsigned
4334 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4335             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4336             bool isPatchPoint, bool hasNest,
4337             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4338             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4339             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4340
4341   bool isPPC64 = Subtarget.isPPC64();
4342   bool isSVR4ABI = Subtarget.isSVR4ABI();
4343   bool isELFv2ABI = Subtarget.isELFv2ABI();
4344
4345   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4346   NodeTys.push_back(MVT::Other);   // Returns a chain
4347   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4348
4349   unsigned CallOpc = PPCISD::CALL;
4350
4351   bool needIndirectCall = true;
4352   if (!isSVR4ABI || !isPPC64)
4353     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4354       // If this is an absolute destination address, use the munged value.
4355       Callee = SDValue(Dest, 0);
4356       needIndirectCall = false;
4357     }
4358
4359   // PC-relative references to external symbols should go through $stub, unless
4360   // we're building with the leopard linker or later, which automatically
4361   // synthesizes these stubs.
4362   const TargetMachine &TM = DAG.getTarget();
4363   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4364   const GlobalValue *GV = nullptr;
4365   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4366     GV = G->getGlobal();
4367   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4368   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4369
4370   if (isFunctionGlobalAddress(Callee)) {
4371     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4372     // A call to a TLS address is actually an indirect call to a
4373     // thread-specific pointer.
4374     unsigned OpFlags = 0;
4375     if (UsePlt)
4376       OpFlags = PPCII::MO_PLT;
4377
4378     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4379     // every direct call is) turn it into a TargetGlobalAddress /
4380     // TargetExternalSymbol node so that legalize doesn't hack it.
4381     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4382                                         Callee.getValueType(), 0, OpFlags);
4383     needIndirectCall = false;
4384   }
4385
4386   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4387     unsigned char OpFlags = 0;
4388
4389     if (UsePlt)
4390       OpFlags = PPCII::MO_PLT;
4391
4392     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4393                                          OpFlags);
4394     needIndirectCall = false;
4395   }
4396
4397   if (isPatchPoint) {
4398     // We'll form an invalid direct call when lowering a patchpoint; the full
4399     // sequence for an indirect call is complicated, and many of the
4400     // instructions introduced might have side effects (and, thus, can't be
4401     // removed later). The call itself will be removed as soon as the
4402     // argument/return lowering is complete, so the fact that it has the wrong
4403     // kind of operands should not really matter.
4404     needIndirectCall = false;
4405   }
4406
4407   if (needIndirectCall) {
4408     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4409     // to do the call, we can't use PPCISD::CALL.
4410     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4411
4412     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4413       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4414       // entry point, but to the function descriptor (the function entry point
4415       // address is part of the function descriptor though).
4416       // The function descriptor is a three doubleword structure with the
4417       // following fields: function entry point, TOC base address and
4418       // environment pointer.
4419       // Thus for a call through a function pointer, the following actions need
4420       // to be performed:
4421       //   1. Save the TOC of the caller in the TOC save area of its stack
4422       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4423       //   2. Load the address of the function entry point from the function
4424       //      descriptor.
4425       //   3. Load the TOC of the callee from the function descriptor into r2.
4426       //   4. Load the environment pointer from the function descriptor into
4427       //      r11.
4428       //   5. Branch to the function entry point address.
4429       //   6. On return of the callee, the TOC of the caller needs to be
4430       //      restored (this is done in FinishCall()).
4431       //
4432       // The loads are scheduled at the beginning of the call sequence, and the
4433       // register copies are flagged together to ensure that no other
4434       // operations can be scheduled in between. E.g. without flagging the
4435       // copies together, a TOC access in the caller could be scheduled between
4436       // the assignment of the callee TOC and the branch to the callee, which
4437       // results in the TOC access going through the TOC of the callee instead
4438       // of going through the TOC of the caller, which leads to incorrect code.
4439
4440       // Load the address of the function entry point from the function
4441       // descriptor.
4442       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4443       if (LDChain.getValueType() == MVT::Glue)
4444         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4445
4446       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4447                           ? (MachineMemOperand::MODereferenceable |
4448                              MachineMemOperand::MOInvariant)
4449                           : MachineMemOperand::MONone;
4450
4451       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4452       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4453                                         /* Alignment = */ 8, MMOFlags);
4454
4455       // Load environment pointer into r11.
4456       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4457       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4458       SDValue LoadEnvPtr =
4459           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4460                       /* Alignment = */ 8, MMOFlags);
4461
4462       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4463       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4464       SDValue TOCPtr =
4465           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4466                       /* Alignment = */ 8, MMOFlags);
4467
4468       setUsesTOCBasePtr(DAG);
4469       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4470                                         InFlag);
4471       Chain = TOCVal.getValue(0);
4472       InFlag = TOCVal.getValue(1);
4473
4474       // If the function call has an explicit 'nest' parameter, it takes the
4475       // place of the environment pointer.
4476       if (!hasNest) {
4477         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4478                                           InFlag);
4479
4480         Chain = EnvVal.getValue(0);
4481         InFlag = EnvVal.getValue(1);
4482       }
4483
4484       MTCTROps[0] = Chain;
4485       MTCTROps[1] = LoadFuncPtr;
4486       MTCTROps[2] = InFlag;
4487     }
4488
4489     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4490                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4491     InFlag = Chain.getValue(1);
4492
4493     NodeTys.clear();
4494     NodeTys.push_back(MVT::Other);
4495     NodeTys.push_back(MVT::Glue);
4496     Ops.push_back(Chain);
4497     CallOpc = PPCISD::BCTRL;
4498     Callee.setNode(nullptr);
4499     // Add use of X11 (holding environment pointer)
4500     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4501       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4502     // Add CTR register as callee so a bctr can be emitted later.
4503     if (isTailCall)
4504       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4505   }
4506
4507   // If this is a direct call, pass the chain and the callee.
4508   if (Callee.getNode()) {
4509     Ops.push_back(Chain);
4510     Ops.push_back(Callee);
4511   }
4512   // If this is a tail call add stack pointer delta.
4513   if (isTailCall)
4514     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4515
4516   // Add argument registers to the end of the list so that they are known live
4517   // into the call.
4518   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4519     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4520                                   RegsToPass[i].second.getValueType()));
4521
4522   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4523   // into the call.
4524   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4525     setUsesTOCBasePtr(DAG);
4526     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4527   }
4528
4529   return CallOpc;
4530 }
4531
4532 static
4533 bool isLocalCall(const SDValue &Callee)
4534 {
4535   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4536     return G->getGlobal()->isStrongDefinitionForLinker();
4537   return false;
4538 }
4539
4540 SDValue PPCTargetLowering::LowerCallResult(
4541     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4542     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4543     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4544
4545   SmallVector<CCValAssign, 16> RVLocs;
4546   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4547                     *DAG.getContext());
4548   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4549
4550   // Copy all of the result registers out of their specified physreg.
4551   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4552     CCValAssign &VA = RVLocs[i];
4553     assert(VA.isRegLoc() && "Can only return in registers!");
4554
4555     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4556                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4557     Chain = Val.getValue(1);
4558     InFlag = Val.getValue(2);
4559
4560     switch (VA.getLocInfo()) {
4561     default: llvm_unreachable("Unknown loc info!");
4562     case CCValAssign::Full: break;
4563     case CCValAssign::AExt:
4564       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4565       break;
4566     case CCValAssign::ZExt:
4567       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4568                         DAG.getValueType(VA.getValVT()));
4569       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4570       break;
4571     case CCValAssign::SExt:
4572       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4573                         DAG.getValueType(VA.getValVT()));
4574       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4575       break;
4576     }
4577
4578     InVals.push_back(Val);
4579   }
4580
4581   return Chain;
4582 }
4583
4584 SDValue PPCTargetLowering::FinishCall(
4585     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4586     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4587     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4588     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4589     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4590     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4591
4592   std::vector<EVT> NodeTys;
4593   SmallVector<SDValue, 8> Ops;
4594   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4595                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4596                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4597
4598   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4599   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4600     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4601
4602   // When performing tail call optimization the callee pops its arguments off
4603   // the stack. Account for this here so these bytes can be pushed back on in
4604   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4605   int BytesCalleePops =
4606     (CallConv == CallingConv::Fast &&
4607      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4608
4609   // Add a register mask operand representing the call-preserved registers.
4610   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4611   const uint32_t *Mask =
4612       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4613   assert(Mask && "Missing call preserved mask for calling convention");
4614   Ops.push_back(DAG.getRegisterMask(Mask));
4615
4616   if (InFlag.getNode())
4617     Ops.push_back(InFlag);
4618
4619   // Emit tail call.
4620   if (isTailCall) {
4621     assert(((Callee.getOpcode() == ISD::Register &&
4622              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4623             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4624             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4625             isa<ConstantSDNode>(Callee)) &&
4626     "Expecting an global address, external symbol, absolute value or register");
4627
4628     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4629     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4630   }
4631
4632   // Add a NOP immediately after the branch instruction when using the 64-bit
4633   // SVR4 ABI. At link time, if caller and callee are in a different module and
4634   // thus have a different TOC, the call will be replaced with a call to a stub
4635   // function which saves the current TOC, loads the TOC of the callee and
4636   // branches to the callee. The NOP will be replaced with a load instruction
4637   // which restores the TOC of the caller from the TOC save slot of the current
4638   // stack frame. If caller and callee belong to the same module (and have the
4639   // same TOC), the NOP will remain unchanged.
4640
4641   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4642       !isPatchPoint) {
4643     if (CallOpc == PPCISD::BCTRL) {
4644       // This is a call through a function pointer.
4645       // Restore the caller TOC from the save area into R2.
4646       // See PrepareCall() for more information about calls through function
4647       // pointers in the 64-bit SVR4 ABI.
4648       // We are using a target-specific load with r2 hard coded, because the
4649       // result of a target-independent load would never go directly into r2,
4650       // since r2 is a reserved register (which prevents the register allocator
4651       // from allocating it), resulting in an additional register being
4652       // allocated and an unnecessary move instruction being generated.
4653       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4654
4655       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4656       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4657       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4658       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4659       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4660
4661       // The address needs to go after the chain input but before the flag (or
4662       // any other variadic arguments).
4663       Ops.insert(std::next(Ops.begin()), AddTOC);
4664     } else if ((CallOpc == PPCISD::CALL) &&
4665                (!isLocalCall(Callee) ||
4666                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4667       // Otherwise insert NOP for non-local calls.
4668       CallOpc = PPCISD::CALL_NOP;
4669   }
4670
4671   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4672   InFlag = Chain.getValue(1);
4673
4674   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4675                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4676                              InFlag, dl);
4677   if (!Ins.empty())
4678     InFlag = Chain.getValue(1);
4679
4680   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4681                          Ins, dl, DAG, InVals);
4682 }
4683
4684 SDValue
4685 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4686                              SmallVectorImpl<SDValue> &InVals) const {
4687   SelectionDAG &DAG                     = CLI.DAG;
4688   SDLoc &dl                             = CLI.DL;
4689   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4690   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4691   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4692   SDValue Chain                         = CLI.Chain;
4693   SDValue Callee                        = CLI.Callee;
4694   bool &isTailCall                      = CLI.IsTailCall;
4695   CallingConv::ID CallConv              = CLI.CallConv;
4696   bool isVarArg                         = CLI.IsVarArg;
4697   bool isPatchPoint                     = CLI.IsPatchPoint;
4698   ImmutableCallSite *CS                 = CLI.CS;
4699
4700   if (isTailCall) {
4701     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4702       isTailCall = false;
4703     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4704       isTailCall =
4705         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4706                                                  isVarArg, Outs, Ins, DAG);
4707     else
4708       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4709                                                      Ins, DAG);
4710     if (isTailCall) {
4711       ++NumTailCalls;
4712       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4713         ++NumSiblingCalls;
4714
4715       assert(isa<GlobalAddressSDNode>(Callee) &&
4716              "Callee should be an llvm::Function object.");
4717       DEBUG(
4718         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4719         const unsigned Width = 80 - strlen("TCO caller: ")
4720                                   - strlen(", callee linkage: 0, 0");
4721         dbgs() << "TCO caller: "
4722                << left_justify(DAG.getMachineFunction().getName(), Width)
4723                << ", callee linkage: "
4724                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4725       );
4726     }
4727   }
4728
4729   if (!isTailCall && CS && CS->isMustTailCall())
4730     report_fatal_error("failed to perform tail call elimination on a call "
4731                        "site marked musttail");
4732
4733   // When long calls (i.e. indirect calls) are always used, calls are always
4734   // made via function pointer. If we have a function name, first translate it
4735   // into a pointer.
4736   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4737       !isTailCall)
4738     Callee = LowerGlobalAddress(Callee, DAG);
4739
4740   if (Subtarget.isSVR4ABI()) {
4741     if (Subtarget.isPPC64())
4742       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4743                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4744                               dl, DAG, InVals, CS);
4745     else
4746       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4747                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4748                               dl, DAG, InVals, CS);
4749   }
4750
4751   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4752                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4753                           dl, DAG, InVals, CS);
4754 }
4755
4756 SDValue PPCTargetLowering::LowerCall_32SVR4(
4757     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4758     bool isTailCall, bool isPatchPoint,
4759     const SmallVectorImpl<ISD::OutputArg> &Outs,
4760     const SmallVectorImpl<SDValue> &OutVals,
4761     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4762     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4763     ImmutableCallSite *CS) const {
4764   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4765   // of the 32-bit SVR4 ABI stack frame layout.
4766
4767   assert((CallConv == CallingConv::C ||
4768           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4769
4770   unsigned PtrByteSize = 4;
4771
4772   MachineFunction &MF = DAG.getMachineFunction();
4773
4774   // Mark this function as potentially containing a function that contains a
4775   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4776   // and restoring the callers stack pointer in this functions epilog. This is
4777   // done because by tail calling the called function might overwrite the value
4778   // in this function's (MF) stack pointer stack slot 0(SP).
4779   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4780       CallConv == CallingConv::Fast)
4781     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4782
4783   // Count how many bytes are to be pushed on the stack, including the linkage
4784   // area, parameter list area and the part of the local variable space which
4785   // contains copies of aggregates which are passed by value.
4786
4787   // Assign locations to all of the outgoing arguments.
4788   SmallVector<CCValAssign, 16> ArgLocs;
4789   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4790
4791   // Reserve space for the linkage area on the stack.
4792   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4793                        PtrByteSize);
4794   if (useSoftFloat())
4795     CCInfo.PreAnalyzeCallOperands(Outs);
4796
4797   if (isVarArg) {
4798     // Handle fixed and variable vector arguments differently.
4799     // Fixed vector arguments go into registers as long as registers are
4800     // available. Variable vector arguments always go into memory.
4801     unsigned NumArgs = Outs.size();
4802
4803     for (unsigned i = 0; i != NumArgs; ++i) {
4804       MVT ArgVT = Outs[i].VT;
4805       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4806       bool Result;
4807
4808       if (Outs[i].IsFixed) {
4809         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4810                                CCInfo);
4811       } else {
4812         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4813                                       ArgFlags, CCInfo);
4814       }
4815
4816       if (Result) {
4817 #ifndef NDEBUG
4818         errs() << "Call operand #" << i << " has unhandled type "
4819              << EVT(ArgVT).getEVTString() << "\n";
4820 #endif
4821         llvm_unreachable(nullptr);
4822       }
4823     }
4824   } else {
4825     // All arguments are treated the same.
4826     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4827   }
4828   CCInfo.clearWasPPCF128();
4829
4830   // Assign locations to all of the outgoing aggregate by value arguments.
4831   SmallVector<CCValAssign, 16> ByValArgLocs;
4832   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4833
4834   // Reserve stack space for the allocations in CCInfo.
4835   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4836
4837   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4838
4839   // Size of the linkage area, parameter list area and the part of the local
4840   // space variable where copies of aggregates which are passed by value are
4841   // stored.
4842   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4843
4844   // Calculate by how many bytes the stack has to be adjusted in case of tail
4845   // call optimization.
4846   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4847
4848   // Adjust the stack pointer for the new arguments...
4849   // These operations are automatically eliminated by the prolog/epilog pass
4850   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4851                                dl);
4852   SDValue CallSeqStart = Chain;
4853
4854   // Load the return address and frame pointer so it can be moved somewhere else
4855   // later.
4856   SDValue LROp, FPOp;
4857   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4858
4859   // Set up a copy of the stack pointer for use loading and storing any
4860   // arguments that may not fit in the registers available for argument
4861   // passing.
4862   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4863
4864   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4865   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4866   SmallVector<SDValue, 8> MemOpChains;
4867
4868   bool seenFloatArg = false;
4869   // Walk the register/memloc assignments, inserting copies/loads.
4870   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4871        i != e;
4872        ++i) {
4873     CCValAssign &VA = ArgLocs[i];
4874     SDValue Arg = OutVals[i];
4875     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4876
4877     if (Flags.isByVal()) {
4878       // Argument is an aggregate which is passed by value, thus we need to
4879       // create a copy of it in the local variable space of the current stack
4880       // frame (which is the stack frame of the caller) and pass the address of
4881       // this copy to the callee.
4882       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4883       CCValAssign &ByValVA = ByValArgLocs[j++];
4884       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4885
4886       // Memory reserved in the local variable space of the callers stack frame.
4887       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4888
4889       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4890       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4891                            StackPtr, PtrOff);
4892
4893       // Create a copy of the argument in the local area of the current
4894       // stack frame.
4895       SDValue MemcpyCall =
4896         CreateCopyOfByValArgument(Arg, PtrOff,
4897                                   CallSeqStart.getNode()->getOperand(0),
4898                                   Flags, DAG, dl);
4899
4900       // This must go outside the CALLSEQ_START..END.
4901       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4902                            CallSeqStart.getNode()->getOperand(1),
4903                            SDLoc(MemcpyCall));
4904       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4905                              NewCallSeqStart.getNode());
4906       Chain = CallSeqStart = NewCallSeqStart;
4907
4908       // Pass the address of the aggregate copy on the stack either in a
4909       // physical register or in the parameter list area of the current stack
4910       // frame to the callee.
4911       Arg = PtrOff;
4912     }
4913
4914     if (VA.isRegLoc()) {
4915       if (Arg.getValueType() == MVT::i1)
4916         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4917
4918       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4919       // Put argument in a physical register.
4920       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4921     } else {
4922       // Put argument in the parameter list area of the current stack frame.
4923       assert(VA.isMemLoc());
4924       unsigned LocMemOffset = VA.getLocMemOffset();
4925
4926       if (!isTailCall) {
4927         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4928         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4929                              StackPtr, PtrOff);
4930
4931         MemOpChains.push_back(
4932             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4933       } else {
4934         // Calculate and remember argument location.
4935         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4936                                  TailCallArguments);
4937       }
4938     }
4939   }
4940
4941   if (!MemOpChains.empty())
4942     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4943
4944   // Build a sequence of copy-to-reg nodes chained together with token chain
4945   // and flag operands which copy the outgoing args into the appropriate regs.
4946   SDValue InFlag;
4947   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4948     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4949                              RegsToPass[i].second, InFlag);
4950     InFlag = Chain.getValue(1);
4951   }
4952
4953   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4954   // registers.
4955   if (isVarArg) {
4956     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4957     SDValue Ops[] = { Chain, InFlag };
4958
4959     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4960                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4961
4962     InFlag = Chain.getValue(1);
4963   }
4964
4965   if (isTailCall)
4966     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
4967                     TailCallArguments);
4968
4969   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
4970                     /* unused except on PPC64 ELFv1 */ false, DAG,
4971                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4972                     NumBytes, Ins, InVals, CS);
4973 }
4974
4975 // Copy an argument into memory, being careful to do this outside the
4976 // call sequence for the call to which the argument belongs.
4977 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
4978     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
4979     SelectionDAG &DAG, const SDLoc &dl) const {
4980   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4981                         CallSeqStart.getNode()->getOperand(0),
4982                         Flags, DAG, dl);
4983   // The MEMCPY must go outside the CALLSEQ_START..END.
4984   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4985                              CallSeqStart.getNode()->getOperand(1),
4986                              SDLoc(MemcpyCall));
4987   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4988                          NewCallSeqStart.getNode());
4989   return NewCallSeqStart;
4990 }
4991
4992 SDValue PPCTargetLowering::LowerCall_64SVR4(
4993     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4994     bool isTailCall, bool isPatchPoint,
4995     const SmallVectorImpl<ISD::OutputArg> &Outs,
4996     const SmallVectorImpl<SDValue> &OutVals,
4997     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4998     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4999     ImmutableCallSite *CS) const {
5000
5001   bool isELFv2ABI = Subtarget.isELFv2ABI();
5002   bool isLittleEndian = Subtarget.isLittleEndian();
5003   unsigned NumOps = Outs.size();
5004   bool hasNest = false;
5005   bool IsSibCall = false;
5006
5007   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5008   unsigned PtrByteSize = 8;
5009
5010   MachineFunction &MF = DAG.getMachineFunction();
5011
5012   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5013     IsSibCall = true;
5014
5015   // Mark this function as potentially containing a function that contains a
5016   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5017   // and restoring the callers stack pointer in this functions epilog. This is
5018   // done because by tail calling the called function might overwrite the value
5019   // in this function's (MF) stack pointer stack slot 0(SP).
5020   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5021       CallConv == CallingConv::Fast)
5022     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5023
5024   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5025          "fastcc not supported on varargs functions");
5026
5027   // Count how many bytes are to be pushed on the stack, including the linkage
5028   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5029   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5030   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5031   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5032   unsigned NumBytes = LinkageSize;
5033   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5034   unsigned &QFPR_idx = FPR_idx;
5035
5036   static const MCPhysReg GPR[] = {
5037     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5038     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5039   };
5040   static const MCPhysReg VR[] = {
5041     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5042     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5043   };
5044   static const MCPhysReg VSRH[] = {
5045     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
5046     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
5047   };
5048
5049   const unsigned NumGPRs = array_lengthof(GPR);
5050   const unsigned NumFPRs = 13;
5051   const unsigned NumVRs  = array_lengthof(VR);
5052   const unsigned NumQFPRs = NumFPRs;
5053
5054   // When using the fast calling convention, we don't provide backing for
5055   // arguments that will be in registers.
5056   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5057
5058   // Add up all the space actually used.
5059   for (unsigned i = 0; i != NumOps; ++i) {
5060     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5061     EVT ArgVT = Outs[i].VT;
5062     EVT OrigVT = Outs[i].ArgVT;
5063
5064     if (Flags.isNest())
5065       continue;
5066
5067     if (CallConv == CallingConv::Fast) {
5068       if (Flags.isByVal())
5069         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5070       else
5071         switch (ArgVT.getSimpleVT().SimpleTy) {
5072         default: llvm_unreachable("Unexpected ValueType for argument!");
5073         case MVT::i1:
5074         case MVT::i32:
5075         case MVT::i64:
5076           if (++NumGPRsUsed <= NumGPRs)
5077             continue;
5078           break;
5079         case MVT::v4i32:
5080         case MVT::v8i16:
5081         case MVT::v16i8:
5082         case MVT::v2f64:
5083         case MVT::v2i64:
5084         case MVT::v1i128:
5085           if (++NumVRsUsed <= NumVRs)
5086             continue;
5087           break;
5088         case MVT::v4f32:
5089           // When using QPX, this is handled like a FP register, otherwise, it
5090           // is an Altivec register.
5091           if (Subtarget.hasQPX()) {
5092             if (++NumFPRsUsed <= NumFPRs)
5093               continue;
5094           } else {
5095             if (++NumVRsUsed <= NumVRs)
5096               continue;
5097           }
5098           break;
5099         case MVT::f32:
5100         case MVT::f64:
5101         case MVT::v4f64: // QPX
5102         case MVT::v4i1:  // QPX
5103           if (++NumFPRsUsed <= NumFPRs)
5104             continue;
5105           break;
5106         }
5107     }
5108
5109     /* Respect alignment of argument on the stack.  */
5110     unsigned Align =
5111       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5112     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5113
5114     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5115     if (Flags.isInConsecutiveRegsLast())
5116       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5117   }
5118
5119   unsigned NumBytesActuallyUsed = NumBytes;
5120
5121   // The prolog code of the callee may store up to 8 GPR argument registers to
5122   // the stack, allowing va_start to index over them in memory if its varargs.
5123   // Because we cannot tell if this is needed on the caller side, we have to
5124   // conservatively assume that it is needed.  As such, make sure we have at
5125   // least enough stack space for the caller to store the 8 GPRs.
5126   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
5127   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5128
5129   // Tail call needs the stack to be aligned.
5130   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5131       CallConv == CallingConv::Fast)
5132     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5133
5134   int SPDiff = 0;
5135
5136   // Calculate by how many bytes the stack has to be adjusted in case of tail
5137   // call optimization.
5138   if (!IsSibCall)
5139     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5140
5141   // To protect arguments on the stack from being clobbered in a tail call,
5142   // force all the loads to happen before doing any other lowering.
5143   if (isTailCall)
5144     Chain = DAG.getStackArgumentTokenFactor(Chain);
5145
5146   // Adjust the stack pointer for the new arguments...
5147   // These operations are automatically eliminated by the prolog/epilog pass
5148   if (!IsSibCall)
5149     Chain = DAG.getCALLSEQ_START(Chain,
5150                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
5151   SDValue CallSeqStart = Chain;
5152
5153   // Load the return address and frame pointer so it can be move somewhere else
5154   // later.
5155   SDValue LROp, FPOp;
5156   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5157
5158   // Set up a copy of the stack pointer for use loading and storing any
5159   // arguments that may not fit in the registers available for argument
5160   // passing.
5161   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5162
5163   // Figure out which arguments are going to go in registers, and which in
5164   // memory.  Also, if this is a vararg function, floating point operations
5165   // must be stored to our stack, and loaded into integer regs as well, if
5166   // any integer regs are available for argument passing.
5167   unsigned ArgOffset = LinkageSize;
5168
5169   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5170   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5171
5172   SmallVector<SDValue, 8> MemOpChains;
5173   for (unsigned i = 0; i != NumOps; ++i) {
5174     SDValue Arg = OutVals[i];
5175     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5176     EVT ArgVT = Outs[i].VT;
5177     EVT OrigVT = Outs[i].ArgVT;
5178
5179     // PtrOff will be used to store the current argument to the stack if a
5180     // register cannot be found for it.
5181     SDValue PtrOff;
5182
5183     // We re-align the argument offset for each argument, except when using the
5184     // fast calling convention, when we need to make sure we do that only when
5185     // we'll actually use a stack slot.
5186     auto ComputePtrOff = [&]() {
5187       /* Respect alignment of argument on the stack.  */
5188       unsigned Align =
5189         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5190       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5191
5192       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5193
5194       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5195     };
5196
5197     if (CallConv != CallingConv::Fast) {
5198       ComputePtrOff();
5199
5200       /* Compute GPR index associated with argument offset.  */
5201       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5202       GPR_idx = std::min(GPR_idx, NumGPRs);
5203     }
5204
5205     // Promote integers to 64-bit values.
5206     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5207       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5208       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5209       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5210     }
5211
5212     // FIXME memcpy is used way more than necessary.  Correctness first.
5213     // Note: "by value" is code for passing a structure by value, not
5214     // basic types.
5215     if (Flags.isByVal()) {
5216       // Note: Size includes alignment padding, so
5217       //   struct x { short a; char b; }
5218       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5219       // These are the proper values we need for right-justifying the
5220       // aggregate in a parameter register.
5221       unsigned Size = Flags.getByValSize();
5222
5223       // An empty aggregate parameter takes up no storage and no
5224       // registers.
5225       if (Size == 0)
5226         continue;
5227
5228       if (CallConv == CallingConv::Fast)
5229         ComputePtrOff();
5230
5231       // All aggregates smaller than 8 bytes must be passed right-justified.
5232       if (Size==1 || Size==2 || Size==4) {
5233         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5234         if (GPR_idx != NumGPRs) {
5235           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5236                                         MachinePointerInfo(), VT);
5237           MemOpChains.push_back(Load.getValue(1));
5238           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5239
5240           ArgOffset += PtrByteSize;
5241           continue;
5242         }
5243       }
5244
5245       if (GPR_idx == NumGPRs && Size < 8) {
5246         SDValue AddPtr = PtrOff;
5247         if (!isLittleEndian) {
5248           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5249                                           PtrOff.getValueType());
5250           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5251         }
5252         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5253                                                           CallSeqStart,
5254                                                           Flags, DAG, dl);
5255         ArgOffset += PtrByteSize;
5256         continue;
5257       }
5258       // Copy entire object into memory.  There are cases where gcc-generated
5259       // code assumes it is there, even if it could be put entirely into
5260       // registers.  (This is not what the doc says.)
5261
5262       // FIXME: The above statement is likely due to a misunderstanding of the
5263       // documents.  All arguments must be copied into the parameter area BY
5264       // THE CALLEE in the event that the callee takes the address of any
5265       // formal argument.  That has not yet been implemented.  However, it is
5266       // reasonable to use the stack area as a staging area for the register
5267       // load.
5268
5269       // Skip this for small aggregates, as we will use the same slot for a
5270       // right-justified copy, below.
5271       if (Size >= 8)
5272         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5273                                                           CallSeqStart,
5274                                                           Flags, DAG, dl);
5275
5276       // When a register is available, pass a small aggregate right-justified.
5277       if (Size < 8 && GPR_idx != NumGPRs) {
5278         // The easiest way to get this right-justified in a register
5279         // is to copy the structure into the rightmost portion of a
5280         // local variable slot, then load the whole slot into the
5281         // register.
5282         // FIXME: The memcpy seems to produce pretty awful code for
5283         // small aggregates, particularly for packed ones.
5284         // FIXME: It would be preferable to use the slot in the
5285         // parameter save area instead of a new local variable.
5286         SDValue AddPtr = PtrOff;
5287         if (!isLittleEndian) {
5288           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5289           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5290         }
5291         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5292                                                           CallSeqStart,
5293                                                           Flags, DAG, dl);
5294
5295         // Load the slot into the register.
5296         SDValue Load =
5297             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5298         MemOpChains.push_back(Load.getValue(1));
5299         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5300
5301         // Done with this argument.
5302         ArgOffset += PtrByteSize;
5303         continue;
5304       }
5305
5306       // For aggregates larger than PtrByteSize, copy the pieces of the
5307       // object that fit into registers from the parameter save area.
5308       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5309         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5310         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5311         if (GPR_idx != NumGPRs) {
5312           SDValue Load =
5313               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5314           MemOpChains.push_back(Load.getValue(1));
5315           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5316           ArgOffset += PtrByteSize;
5317         } else {
5318           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5319           break;
5320         }
5321       }
5322       continue;
5323     }
5324
5325     switch (Arg.getSimpleValueType().SimpleTy) {
5326     default: llvm_unreachable("Unexpected ValueType for argument!");
5327     case MVT::i1:
5328     case MVT::i32:
5329     case MVT::i64:
5330       if (Flags.isNest()) {
5331         // The 'nest' parameter, if any, is passed in R11.
5332         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5333         hasNest = true;
5334         break;
5335       }
5336
5337       // These can be scalar arguments or elements of an integer array type
5338       // passed directly.  Clang may use those instead of "byval" aggregate
5339       // types to avoid forcing arguments to memory unnecessarily.
5340       if (GPR_idx != NumGPRs) {
5341         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5342       } else {
5343         if (CallConv == CallingConv::Fast)
5344           ComputePtrOff();
5345
5346         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5347                          true, isTailCall, false, MemOpChains,
5348                          TailCallArguments, dl);
5349         if (CallConv == CallingConv::Fast)
5350           ArgOffset += PtrByteSize;
5351       }
5352       if (CallConv != CallingConv::Fast)
5353         ArgOffset += PtrByteSize;
5354       break;
5355     case MVT::f32:
5356     case MVT::f64: {
5357       // These can be scalar arguments or elements of a float array type
5358       // passed directly.  The latter are used to implement ELFv2 homogenous
5359       // float aggregates.
5360
5361       // Named arguments go into FPRs first, and once they overflow, the
5362       // remaining arguments go into GPRs and then the parameter save area.
5363       // Unnamed arguments for vararg functions always go to GPRs and
5364       // then the parameter save area.  For now, put all arguments to vararg
5365       // routines always in both locations (FPR *and* GPR or stack slot).
5366       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5367       bool NeededLoad = false;
5368
5369       // First load the argument into the next available FPR.
5370       if (FPR_idx != NumFPRs)
5371         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5372
5373       // Next, load the argument into GPR or stack slot if needed.
5374       if (!NeedGPROrStack)
5375         ;
5376       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5377         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5378         // once we support fp <-> gpr moves.
5379
5380         // In the non-vararg case, this can only ever happen in the
5381         // presence of f32 array types, since otherwise we never run
5382         // out of FPRs before running out of GPRs.
5383         SDValue ArgVal;
5384
5385         // Double values are always passed in a single GPR.
5386         if (Arg.getValueType() != MVT::f32) {
5387           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5388
5389         // Non-array float values are extended and passed in a GPR.
5390         } else if (!Flags.isInConsecutiveRegs()) {
5391           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5392           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5393
5394         // If we have an array of floats, we collect every odd element
5395         // together with its predecessor into one GPR.
5396         } else if (ArgOffset % PtrByteSize != 0) {
5397           SDValue Lo, Hi;
5398           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5399           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5400           if (!isLittleEndian)
5401             std::swap(Lo, Hi);
5402           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5403
5404         // The final element, if even, goes into the first half of a GPR.
5405         } else if (Flags.isInConsecutiveRegsLast()) {
5406           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5407           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5408           if (!isLittleEndian)
5409             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5410                                  DAG.getConstant(32, dl, MVT::i32));
5411
5412         // Non-final even elements are skipped; they will be handled
5413         // together the with subsequent argument on the next go-around.
5414         } else
5415           ArgVal = SDValue();
5416
5417         if (ArgVal.getNode())
5418           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5419       } else {
5420         if (CallConv == CallingConv::Fast)
5421           ComputePtrOff();
5422
5423         // Single-precision floating-point values are mapped to the
5424         // second (rightmost) word of the stack doubleword.
5425         if (Arg.getValueType() == MVT::f32 &&
5426             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5427           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5428           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5429         }
5430
5431         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5432                          true, isTailCall, false, MemOpChains,
5433                          TailCallArguments, dl);
5434
5435         NeededLoad = true;
5436       }
5437       // When passing an array of floats, the array occupies consecutive
5438       // space in the argument area; only round up to the next doubleword
5439       // at the end of the array.  Otherwise, each float takes 8 bytes.
5440       if (CallConv != CallingConv::Fast || NeededLoad) {
5441         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5442                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5443         if (Flags.isInConsecutiveRegsLast())
5444           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5445       }
5446       break;
5447     }
5448     case MVT::v4f32:
5449     case MVT::v4i32:
5450     case MVT::v8i16:
5451     case MVT::v16i8:
5452     case MVT::v2f64:
5453     case MVT::v2i64:
5454     case MVT::v1i128:
5455       if (!Subtarget.hasQPX()) {
5456       // These can be scalar arguments or elements of a vector array type
5457       // passed directly.  The latter are used to implement ELFv2 homogenous
5458       // vector aggregates.
5459
5460       // For a varargs call, named arguments go into VRs or on the stack as
5461       // usual; unnamed arguments always go to the stack or the corresponding
5462       // GPRs when within range.  For now, we always put the value in both
5463       // locations (or even all three).
5464       if (isVarArg) {
5465         // We could elide this store in the case where the object fits
5466         // entirely in R registers.  Maybe later.
5467         SDValue Store =
5468             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5469         MemOpChains.push_back(Store);
5470         if (VR_idx != NumVRs) {
5471           SDValue Load =
5472               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5473           MemOpChains.push_back(Load.getValue(1));
5474
5475           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5476                            Arg.getSimpleValueType() == MVT::v2i64) ?
5477                           VSRH[VR_idx] : VR[VR_idx];
5478           ++VR_idx;
5479
5480           RegsToPass.push_back(std::make_pair(VReg, Load));
5481         }
5482         ArgOffset += 16;
5483         for (unsigned i=0; i<16; i+=PtrByteSize) {
5484           if (GPR_idx == NumGPRs)
5485             break;
5486           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5487                                    DAG.getConstant(i, dl, PtrVT));
5488           SDValue Load =
5489               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5490           MemOpChains.push_back(Load.getValue(1));
5491           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5492         }
5493         break;
5494       }
5495
5496       // Non-varargs Altivec params go into VRs or on the stack.
5497       if (VR_idx != NumVRs) {
5498         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5499                          Arg.getSimpleValueType() == MVT::v2i64) ?
5500                         VSRH[VR_idx] : VR[VR_idx];
5501         ++VR_idx;
5502
5503         RegsToPass.push_back(std::make_pair(VReg, Arg));
5504       } else {
5505         if (CallConv == CallingConv::Fast)
5506           ComputePtrOff();
5507
5508         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5509                          true, isTailCall, true, MemOpChains,
5510                          TailCallArguments, dl);
5511         if (CallConv == CallingConv::Fast)
5512           ArgOffset += 16;
5513       }
5514
5515       if (CallConv != CallingConv::Fast)
5516         ArgOffset += 16;
5517       break;
5518       } // not QPX
5519
5520       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5521              "Invalid QPX parameter type");
5522
5523       /* fall through */
5524     case MVT::v4f64:
5525     case MVT::v4i1: {
5526       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5527       if (isVarArg) {
5528         // We could elide this store in the case where the object fits
5529         // entirely in R registers.  Maybe later.
5530         SDValue Store =
5531             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5532         MemOpChains.push_back(Store);
5533         if (QFPR_idx != NumQFPRs) {
5534           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5535                                      PtrOff, MachinePointerInfo());
5536           MemOpChains.push_back(Load.getValue(1));
5537           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5538         }
5539         ArgOffset += (IsF32 ? 16 : 32);
5540         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5541           if (GPR_idx == NumGPRs)
5542             break;
5543           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5544                                    DAG.getConstant(i, dl, PtrVT));
5545           SDValue Load =
5546               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5547           MemOpChains.push_back(Load.getValue(1));
5548           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5549         }
5550         break;
5551       }
5552
5553       // Non-varargs QPX params go into registers or on the stack.
5554       if (QFPR_idx != NumQFPRs) {
5555         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5556       } else {
5557         if (CallConv == CallingConv::Fast)
5558           ComputePtrOff();
5559
5560         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5561                          true, isTailCall, true, MemOpChains,
5562                          TailCallArguments, dl);
5563         if (CallConv == CallingConv::Fast)
5564           ArgOffset += (IsF32 ? 16 : 32);
5565       }
5566
5567       if (CallConv != CallingConv::Fast)
5568         ArgOffset += (IsF32 ? 16 : 32);
5569       break;
5570       }
5571     }
5572   }
5573
5574   assert(NumBytesActuallyUsed == ArgOffset);
5575   (void)NumBytesActuallyUsed;
5576
5577   if (!MemOpChains.empty())
5578     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5579
5580   // Check if this is an indirect call (MTCTR/BCTRL).
5581   // See PrepareCall() for more information about calls through function
5582   // pointers in the 64-bit SVR4 ABI.
5583   if (!isTailCall && !isPatchPoint &&
5584       !isFunctionGlobalAddress(Callee) &&
5585       !isa<ExternalSymbolSDNode>(Callee)) {
5586     // Load r2 into a virtual register and store it to the TOC save area.
5587     setUsesTOCBasePtr(DAG);
5588     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5589     // TOC save area offset.
5590     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5591     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5592     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5593     Chain = DAG.getStore(
5594         Val.getValue(1), dl, Val, AddPtr,
5595         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5596     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5597     // This does not mean the MTCTR instruction must use R12; it's easier
5598     // to model this as an extra parameter, so do that.
5599     if (isELFv2ABI && !isPatchPoint)
5600       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5601   }
5602
5603   // Build a sequence of copy-to-reg nodes chained together with token chain
5604   // and flag operands which copy the outgoing args into the appropriate regs.
5605   SDValue InFlag;
5606   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5607     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5608                              RegsToPass[i].second, InFlag);
5609     InFlag = Chain.getValue(1);
5610   }
5611
5612   if (isTailCall && !IsSibCall)
5613     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5614                     TailCallArguments);
5615
5616   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5617                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5618                     SPDiff, NumBytes, Ins, InVals, CS);
5619 }
5620
5621 SDValue PPCTargetLowering::LowerCall_Darwin(
5622     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5623     bool isTailCall, bool isPatchPoint,
5624     const SmallVectorImpl<ISD::OutputArg> &Outs,
5625     const SmallVectorImpl<SDValue> &OutVals,
5626     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5627     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5628     ImmutableCallSite *CS) const {
5629
5630   unsigned NumOps = Outs.size();
5631
5632   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5633   bool isPPC64 = PtrVT == MVT::i64;
5634   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5635
5636   MachineFunction &MF = DAG.getMachineFunction();
5637
5638   // Mark this function as potentially containing a function that contains a
5639   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5640   // and restoring the callers stack pointer in this functions epilog. This is
5641   // done because by tail calling the called function might overwrite the value
5642   // in this function's (MF) stack pointer stack slot 0(SP).
5643   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5644       CallConv == CallingConv::Fast)
5645     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5646
5647   // Count how many bytes are to be pushed on the stack, including the linkage
5648   // area, and parameter passing area.  We start with 24/48 bytes, which is
5649   // prereserved space for [SP][CR][LR][3 x unused].
5650   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5651   unsigned NumBytes = LinkageSize;
5652
5653   // Add up all the space actually used.
5654   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5655   // they all go in registers, but we must reserve stack space for them for
5656   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5657   // assigned stack space in order, with padding so Altivec parameters are
5658   // 16-byte aligned.
5659   unsigned nAltivecParamsAtEnd = 0;
5660   for (unsigned i = 0; i != NumOps; ++i) {
5661     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5662     EVT ArgVT = Outs[i].VT;
5663     // Varargs Altivec parameters are padded to a 16 byte boundary.
5664     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5665         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5666         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5667       if (!isVarArg && !isPPC64) {
5668         // Non-varargs Altivec parameters go after all the non-Altivec
5669         // parameters; handle those later so we know how much padding we need.
5670         nAltivecParamsAtEnd++;
5671         continue;
5672       }
5673       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5674       NumBytes = ((NumBytes+15)/16)*16;
5675     }
5676     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5677   }
5678
5679   // Allow for Altivec parameters at the end, if needed.
5680   if (nAltivecParamsAtEnd) {
5681     NumBytes = ((NumBytes+15)/16)*16;
5682     NumBytes += 16*nAltivecParamsAtEnd;
5683   }
5684
5685   // The prolog code of the callee may store up to 8 GPR argument registers to
5686   // the stack, allowing va_start to index over them in memory if its varargs.
5687   // Because we cannot tell if this is needed on the caller side, we have to
5688   // conservatively assume that it is needed.  As such, make sure we have at
5689   // least enough stack space for the caller to store the 8 GPRs.
5690   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5691
5692   // Tail call needs the stack to be aligned.
5693   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5694       CallConv == CallingConv::Fast)
5695     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5696
5697   // Calculate by how many bytes the stack has to be adjusted in case of tail
5698   // call optimization.
5699   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5700
5701   // To protect arguments on the stack from being clobbered in a tail call,
5702   // force all the loads to happen before doing any other lowering.
5703   if (isTailCall)
5704     Chain = DAG.getStackArgumentTokenFactor(Chain);
5705
5706   // Adjust the stack pointer for the new arguments...
5707   // These operations are automatically eliminated by the prolog/epilog pass
5708   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5709                                dl);
5710   SDValue CallSeqStart = Chain;
5711
5712   // Load the return address and frame pointer so it can be move somewhere else
5713   // later.
5714   SDValue LROp, FPOp;
5715   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5716
5717   // Set up a copy of the stack pointer for use loading and storing any
5718   // arguments that may not fit in the registers available for argument
5719   // passing.
5720   SDValue StackPtr;
5721   if (isPPC64)
5722     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5723   else
5724     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5725
5726   // Figure out which arguments are going to go in registers, and which in
5727   // memory.  Also, if this is a vararg function, floating point operations
5728   // must be stored to our stack, and loaded into integer regs as well, if
5729   // any integer regs are available for argument passing.
5730   unsigned ArgOffset = LinkageSize;
5731   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5732
5733   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5734     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5735     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5736   };
5737   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5738     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5739     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5740   };
5741   static const MCPhysReg VR[] = {
5742     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5743     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5744   };
5745   const unsigned NumGPRs = array_lengthof(GPR_32);
5746   const unsigned NumFPRs = 13;
5747   const unsigned NumVRs  = array_lengthof(VR);
5748
5749   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5750
5751   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5752   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5753
5754   SmallVector<SDValue, 8> MemOpChains;
5755   for (unsigned i = 0; i != NumOps; ++i) {
5756     SDValue Arg = OutVals[i];
5757     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5758
5759     // PtrOff will be used to store the current argument to the stack if a
5760     // register cannot be found for it.
5761     SDValue PtrOff;
5762
5763     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5764
5765     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5766
5767     // On PPC64, promote integers to 64-bit values.
5768     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5769       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5770       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5771       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5772     }
5773
5774     // FIXME memcpy is used way more than necessary.  Correctness first.
5775     // Note: "by value" is code for passing a structure by value, not
5776     // basic types.
5777     if (Flags.isByVal()) {
5778       unsigned Size = Flags.getByValSize();
5779       // Very small objects are passed right-justified.  Everything else is
5780       // passed left-justified.
5781       if (Size==1 || Size==2) {
5782         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5783         if (GPR_idx != NumGPRs) {
5784           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5785                                         MachinePointerInfo(), VT);
5786           MemOpChains.push_back(Load.getValue(1));
5787           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5788
5789           ArgOffset += PtrByteSize;
5790         } else {
5791           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5792                                           PtrOff.getValueType());
5793           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5794           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5795                                                             CallSeqStart,
5796                                                             Flags, DAG, dl);
5797           ArgOffset += PtrByteSize;
5798         }
5799         continue;
5800       }
5801       // Copy entire object into memory.  There are cases where gcc-generated
5802       // code assumes it is there, even if it could be put entirely into
5803       // registers.  (This is not what the doc says.)
5804       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5805                                                         CallSeqStart,
5806                                                         Flags, DAG, dl);
5807
5808       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5809       // copy the pieces of the object that fit into registers from the
5810       // parameter save area.
5811       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5812         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5813         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5814         if (GPR_idx != NumGPRs) {
5815           SDValue Load =
5816               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5817           MemOpChains.push_back(Load.getValue(1));
5818           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5819           ArgOffset += PtrByteSize;
5820         } else {
5821           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5822           break;
5823         }
5824       }
5825       continue;
5826     }
5827
5828     switch (Arg.getSimpleValueType().SimpleTy) {
5829     default: llvm_unreachable("Unexpected ValueType for argument!");
5830     case MVT::i1:
5831     case MVT::i32:
5832     case MVT::i64:
5833       if (GPR_idx != NumGPRs) {
5834         if (Arg.getValueType() == MVT::i1)
5835           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5836
5837         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5838       } else {
5839         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5840                          isPPC64, isTailCall, false, MemOpChains,
5841                          TailCallArguments, dl);
5842       }
5843       ArgOffset += PtrByteSize;
5844       break;
5845     case MVT::f32:
5846     case MVT::f64:
5847       if (FPR_idx != NumFPRs) {
5848         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5849
5850         if (isVarArg) {
5851           SDValue Store =
5852               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5853           MemOpChains.push_back(Store);
5854
5855           // Float varargs are always shadowed in available integer registers
5856           if (GPR_idx != NumGPRs) {
5857             SDValue Load =
5858                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5859             MemOpChains.push_back(Load.getValue(1));
5860             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5861           }
5862           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5863             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5864             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5865             SDValue Load =
5866                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5867             MemOpChains.push_back(Load.getValue(1));
5868             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5869           }
5870         } else {
5871           // If we have any FPRs remaining, we may also have GPRs remaining.
5872           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5873           // GPRs.
5874           if (GPR_idx != NumGPRs)
5875             ++GPR_idx;
5876           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5877               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5878             ++GPR_idx;
5879         }
5880       } else
5881         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5882                          isPPC64, isTailCall, false, MemOpChains,
5883                          TailCallArguments, dl);
5884       if (isPPC64)
5885         ArgOffset += 8;
5886       else
5887         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5888       break;
5889     case MVT::v4f32:
5890     case MVT::v4i32:
5891     case MVT::v8i16:
5892     case MVT::v16i8:
5893       if (isVarArg) {
5894         // These go aligned on the stack, or in the corresponding R registers
5895         // when within range.  The Darwin PPC ABI doc claims they also go in
5896         // V registers; in fact gcc does this only for arguments that are
5897         // prototyped, not for those that match the ...  We do it for all
5898         // arguments, seems to work.
5899         while (ArgOffset % 16 !=0) {
5900           ArgOffset += PtrByteSize;
5901           if (GPR_idx != NumGPRs)
5902             GPR_idx++;
5903         }
5904         // We could elide this store in the case where the object fits
5905         // entirely in R registers.  Maybe later.
5906         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5907                              DAG.getConstant(ArgOffset, dl, PtrVT));
5908         SDValue Store =
5909             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5910         MemOpChains.push_back(Store);
5911         if (VR_idx != NumVRs) {
5912           SDValue Load =
5913               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5914           MemOpChains.push_back(Load.getValue(1));
5915           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5916         }
5917         ArgOffset += 16;
5918         for (unsigned i=0; i<16; i+=PtrByteSize) {
5919           if (GPR_idx == NumGPRs)
5920             break;
5921           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5922                                    DAG.getConstant(i, dl, PtrVT));
5923           SDValue Load =
5924               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5925           MemOpChains.push_back(Load.getValue(1));
5926           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5927         }
5928         break;
5929       }
5930
5931       // Non-varargs Altivec params generally go in registers, but have
5932       // stack space allocated at the end.
5933       if (VR_idx != NumVRs) {
5934         // Doesn't have GPR space allocated.
5935         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5936       } else if (nAltivecParamsAtEnd==0) {
5937         // We are emitting Altivec params in order.
5938         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5939                          isPPC64, isTailCall, true, MemOpChains,
5940                          TailCallArguments, dl);
5941         ArgOffset += 16;
5942       }
5943       break;
5944     }
5945   }
5946   // If all Altivec parameters fit in registers, as they usually do,
5947   // they get stack space following the non-Altivec parameters.  We
5948   // don't track this here because nobody below needs it.
5949   // If there are more Altivec parameters than fit in registers emit
5950   // the stores here.
5951   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5952     unsigned j = 0;
5953     // Offset is aligned; skip 1st 12 params which go in V registers.
5954     ArgOffset = ((ArgOffset+15)/16)*16;
5955     ArgOffset += 12*16;
5956     for (unsigned i = 0; i != NumOps; ++i) {
5957       SDValue Arg = OutVals[i];
5958       EVT ArgType = Outs[i].VT;
5959       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5960           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5961         if (++j > NumVRs) {
5962           SDValue PtrOff;
5963           // We are emitting Altivec params in order.
5964           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5965                            isPPC64, isTailCall, true, MemOpChains,
5966                            TailCallArguments, dl);
5967           ArgOffset += 16;
5968         }
5969       }
5970     }
5971   }
5972
5973   if (!MemOpChains.empty())
5974     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5975
5976   // On Darwin, R12 must contain the address of an indirect callee.  This does
5977   // not mean the MTCTR instruction must use R12; it's easier to model this as
5978   // an extra parameter, so do that.
5979   if (!isTailCall &&
5980       !isFunctionGlobalAddress(Callee) &&
5981       !isa<ExternalSymbolSDNode>(Callee) &&
5982       !isBLACompatibleAddress(Callee, DAG))
5983     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5984                                                    PPC::R12), Callee));
5985
5986   // Build a sequence of copy-to-reg nodes chained together with token chain
5987   // and flag operands which copy the outgoing args into the appropriate regs.
5988   SDValue InFlag;
5989   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5990     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5991                              RegsToPass[i].second, InFlag);
5992     InFlag = Chain.getValue(1);
5993   }
5994
5995   if (isTailCall)
5996     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5997                     TailCallArguments);
5998
5999   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6000                     /* unused except on PPC64 ELFv1 */ false, DAG,
6001                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6002                     NumBytes, Ins, InVals, CS);
6003 }
6004
6005 bool
6006 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6007                                   MachineFunction &MF, bool isVarArg,
6008                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6009                                   LLVMContext &Context) const {
6010   SmallVector<CCValAssign, 16> RVLocs;
6011   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6012   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6013 }
6014
6015 SDValue
6016 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6017                                bool isVarArg,
6018                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6019                                const SmallVectorImpl<SDValue> &OutVals,
6020                                const SDLoc &dl, SelectionDAG &DAG) const {
6021
6022   SmallVector<CCValAssign, 16> RVLocs;
6023   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6024                  *DAG.getContext());
6025   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6026
6027   SDValue Flag;
6028   SmallVector<SDValue, 4> RetOps(1, Chain);
6029
6030   // Copy the result values into the output registers.
6031   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6032     CCValAssign &VA = RVLocs[i];
6033     assert(VA.isRegLoc() && "Can only return in registers!");
6034
6035     SDValue Arg = OutVals[i];
6036
6037     switch (VA.getLocInfo()) {
6038     default: llvm_unreachable("Unknown loc info!");
6039     case CCValAssign::Full: break;
6040     case CCValAssign::AExt:
6041       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6042       break;
6043     case CCValAssign::ZExt:
6044       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6045       break;
6046     case CCValAssign::SExt:
6047       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6048       break;
6049     }
6050
6051     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6052     Flag = Chain.getValue(1);
6053     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6054   }
6055
6056   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6057   const MCPhysReg *I =
6058     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6059   if (I) {
6060     for (; *I; ++I) {
6061
6062       if (PPC::G8RCRegClass.contains(*I))
6063         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6064       else if (PPC::F8RCRegClass.contains(*I))
6065         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6066       else if (PPC::CRRCRegClass.contains(*I))
6067         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6068       else if (PPC::VRRCRegClass.contains(*I))
6069         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6070       else
6071         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6072     }
6073   }
6074
6075   RetOps[0] = Chain;  // Update chain.
6076
6077   // Add the flag if we have it.
6078   if (Flag.getNode())
6079     RetOps.push_back(Flag);
6080
6081   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6082 }
6083
6084 SDValue
6085 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6086                                                 SelectionDAG &DAG) const {
6087   SDLoc dl(Op);
6088
6089   // Get the corect type for integers.
6090   EVT IntVT = Op.getValueType();
6091
6092   // Get the inputs.
6093   SDValue Chain = Op.getOperand(0);
6094   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6095   // Build a DYNAREAOFFSET node.
6096   SDValue Ops[2] = {Chain, FPSIdx};
6097   SDVTList VTs = DAG.getVTList(IntVT);
6098   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6099 }
6100
6101 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6102                                              SelectionDAG &DAG) const {
6103   // When we pop the dynamic allocation we need to restore the SP link.
6104   SDLoc dl(Op);
6105
6106   // Get the corect type for pointers.
6107   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6108
6109   // Construct the stack pointer operand.
6110   bool isPPC64 = Subtarget.isPPC64();
6111   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6112   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6113
6114   // Get the operands for the STACKRESTORE.
6115   SDValue Chain = Op.getOperand(0);
6116   SDValue SaveSP = Op.getOperand(1);
6117
6118   // Load the old link SP.
6119   SDValue LoadLinkSP =
6120       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6121
6122   // Restore the stack pointer.
6123   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6124
6125   // Store the old link SP.
6126   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6127 }
6128
6129 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6130   MachineFunction &MF = DAG.getMachineFunction();
6131   bool isPPC64 = Subtarget.isPPC64();
6132   EVT PtrVT = getPointerTy(MF.getDataLayout());
6133
6134   // Get current frame pointer save index.  The users of this index will be
6135   // primarily DYNALLOC instructions.
6136   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6137   int RASI = FI->getReturnAddrSaveIndex();
6138
6139   // If the frame pointer save index hasn't been defined yet.
6140   if (!RASI) {
6141     // Find out what the fix offset of the frame pointer save area.
6142     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6143     // Allocate the frame index for frame pointer save area.
6144     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6145     // Save the result.
6146     FI->setReturnAddrSaveIndex(RASI);
6147   }
6148   return DAG.getFrameIndex(RASI, PtrVT);
6149 }
6150
6151 SDValue
6152 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6153   MachineFunction &MF = DAG.getMachineFunction();
6154   bool isPPC64 = Subtarget.isPPC64();
6155   EVT PtrVT = getPointerTy(MF.getDataLayout());
6156
6157   // Get current frame pointer save index.  The users of this index will be
6158   // primarily DYNALLOC instructions.
6159   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6160   int FPSI = FI->getFramePointerSaveIndex();
6161
6162   // If the frame pointer save index hasn't been defined yet.
6163   if (!FPSI) {
6164     // Find out what the fix offset of the frame pointer save area.
6165     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6166     // Allocate the frame index for frame pointer save area.
6167     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6168     // Save the result.
6169     FI->setFramePointerSaveIndex(FPSI);
6170   }
6171   return DAG.getFrameIndex(FPSI, PtrVT);
6172 }
6173
6174 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6175                                                    SelectionDAG &DAG) const {
6176   // Get the inputs.
6177   SDValue Chain = Op.getOperand(0);
6178   SDValue Size  = Op.getOperand(1);
6179   SDLoc dl(Op);
6180
6181   // Get the corect type for pointers.
6182   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6183   // Negate the size.
6184   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6185                                 DAG.getConstant(0, dl, PtrVT), Size);
6186   // Construct a node for the frame pointer save index.
6187   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6188   // Build a DYNALLOC node.
6189   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6190   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6191   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6192 }
6193
6194 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6195                                                      SelectionDAG &DAG) const {
6196   MachineFunction &MF = DAG.getMachineFunction();
6197
6198   bool isPPC64 = Subtarget.isPPC64();
6199   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6200
6201   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6202   return DAG.getFrameIndex(FI, PtrVT);
6203 }
6204
6205 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6206                                                SelectionDAG &DAG) const {
6207   SDLoc DL(Op);
6208   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6209                      DAG.getVTList(MVT::i32, MVT::Other),
6210                      Op.getOperand(0), Op.getOperand(1));
6211 }
6212
6213 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6214                                                 SelectionDAG &DAG) const {
6215   SDLoc DL(Op);
6216   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6217                      Op.getOperand(0), Op.getOperand(1));
6218 }
6219
6220 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6221   if (Op.getValueType().isVector())
6222     return LowerVectorLoad(Op, DAG);
6223
6224   assert(Op.getValueType() == MVT::i1 &&
6225          "Custom lowering only for i1 loads");
6226
6227   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6228
6229   SDLoc dl(Op);
6230   LoadSDNode *LD = cast<LoadSDNode>(Op);
6231
6232   SDValue Chain = LD->getChain();
6233   SDValue BasePtr = LD->getBasePtr();
6234   MachineMemOperand *MMO = LD->getMemOperand();
6235
6236   SDValue NewLD =
6237       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6238                      BasePtr, MVT::i8, MMO);
6239   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6240
6241   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6242   return DAG.getMergeValues(Ops, dl);
6243 }
6244
6245 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6246   if (Op.getOperand(1).getValueType().isVector())
6247     return LowerVectorStore(Op, DAG);
6248
6249   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6250          "Custom lowering only for i1 stores");
6251
6252   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6253
6254   SDLoc dl(Op);
6255   StoreSDNode *ST = cast<StoreSDNode>(Op);
6256
6257   SDValue Chain = ST->getChain();
6258   SDValue BasePtr = ST->getBasePtr();
6259   SDValue Value = ST->getValue();
6260   MachineMemOperand *MMO = ST->getMemOperand();
6261
6262   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6263                       Value);
6264   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6265 }
6266
6267 // FIXME: Remove this once the ANDI glue bug is fixed:
6268 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6269   assert(Op.getValueType() == MVT::i1 &&
6270          "Custom lowering only for i1 results");
6271
6272   SDLoc DL(Op);
6273   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6274                      Op.getOperand(0));
6275 }
6276
6277 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6278 /// possible.
6279 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6280   // Not FP? Not a fsel.
6281   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6282       !Op.getOperand(2).getValueType().isFloatingPoint())
6283     return Op;
6284
6285   // We might be able to do better than this under some circumstances, but in
6286   // general, fsel-based lowering of select is a finite-math-only optimization.
6287   // For more information, see section F.3 of the 2.06 ISA specification.
6288   if (!DAG.getTarget().Options.NoInfsFPMath ||
6289       !DAG.getTarget().Options.NoNaNsFPMath)
6290     return Op;
6291   // TODO: Propagate flags from the select rather than global settings.
6292   SDNodeFlags Flags;
6293   Flags.setNoInfs(true);
6294   Flags.setNoNaNs(true);
6295
6296   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6297
6298   EVT ResVT = Op.getValueType();
6299   EVT CmpVT = Op.getOperand(0).getValueType();
6300   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6301   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6302   SDLoc dl(Op);
6303
6304   // If the RHS of the comparison is a 0.0, we don't need to do the
6305   // subtraction at all.
6306   SDValue Sel1;
6307   if (isFloatingPointZero(RHS))
6308     switch (CC) {
6309     default: break;       // SETUO etc aren't handled by fsel.
6310     case ISD::SETNE:
6311       std::swap(TV, FV);
6312     case ISD::SETEQ:
6313       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6314         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6315       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6316       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6317         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6318       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6319                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6320     case ISD::SETULT:
6321     case ISD::SETLT:
6322       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6323     case ISD::SETOGE:
6324     case ISD::SETGE:
6325       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6326         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6327       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6328     case ISD::SETUGT:
6329     case ISD::SETGT:
6330       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6331     case ISD::SETOLE:
6332     case ISD::SETLE:
6333       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6334         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6335       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6336                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6337     }
6338
6339   SDValue Cmp;
6340   switch (CC) {
6341   default: break;       // SETUO etc aren't handled by fsel.
6342   case ISD::SETNE:
6343     std::swap(TV, FV);
6344   case ISD::SETEQ:
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     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6349     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6350       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6351     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6352                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6353   case ISD::SETULT:
6354   case ISD::SETLT:
6355     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6356     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6357       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6358     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6359   case ISD::SETOGE:
6360   case ISD::SETGE:
6361     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6362     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6363       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6364     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6365   case ISD::SETUGT:
6366   case ISD::SETGT:
6367     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6368     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6369       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6370     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6371   case ISD::SETOLE:
6372   case ISD::SETLE:
6373     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6374     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6375       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6376     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6377   }
6378   return Op;
6379 }
6380
6381 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6382                                                SelectionDAG &DAG,
6383                                                const SDLoc &dl) const {
6384   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6385   SDValue Src = Op.getOperand(0);
6386   if (Src.getValueType() == MVT::f32)
6387     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6388
6389   SDValue Tmp;
6390   switch (Op.getSimpleValueType().SimpleTy) {
6391   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6392   case MVT::i32:
6393     Tmp = DAG.getNode(
6394         Op.getOpcode() == ISD::FP_TO_SINT
6395             ? PPCISD::FCTIWZ
6396             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6397         dl, MVT::f64, Src);
6398     break;
6399   case MVT::i64:
6400     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6401            "i64 FP_TO_UINT is supported only with FPCVT");
6402     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6403                                                         PPCISD::FCTIDUZ,
6404                       dl, MVT::f64, Src);
6405     break;
6406   }
6407
6408   // Convert the FP value to an int value through memory.
6409   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6410     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6411   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6412   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6413   MachinePointerInfo MPI =
6414       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6415
6416   // Emit a store to the stack slot.
6417   SDValue Chain;
6418   if (i32Stack) {
6419     MachineFunction &MF = DAG.getMachineFunction();
6420     MachineMemOperand *MMO =
6421       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6422     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6423     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6424               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6425   } else
6426     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6427
6428   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6429   // add in a bias on big endian.
6430   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6431     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6432                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6433     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6434   }
6435
6436   RLI.Chain = Chain;
6437   RLI.Ptr = FIPtr;
6438   RLI.MPI = MPI;
6439 }
6440
6441 /// \brief Custom lowers floating point to integer conversions to use
6442 /// the direct move instructions available in ISA 2.07 to avoid the
6443 /// need for load/store combinations.
6444 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6445                                                     SelectionDAG &DAG,
6446                                                     const SDLoc &dl) const {
6447   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6448   SDValue Src = Op.getOperand(0);
6449
6450   if (Src.getValueType() == MVT::f32)
6451     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6452
6453   SDValue Tmp;
6454   switch (Op.getSimpleValueType().SimpleTy) {
6455   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6456   case MVT::i32:
6457     Tmp = DAG.getNode(
6458         Op.getOpcode() == ISD::FP_TO_SINT
6459             ? PPCISD::FCTIWZ
6460             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6461         dl, MVT::f64, Src);
6462     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6463     break;
6464   case MVT::i64:
6465     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6466            "i64 FP_TO_UINT is supported only with FPCVT");
6467     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6468                                                         PPCISD::FCTIDUZ,
6469                       dl, MVT::f64, Src);
6470     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6471     break;
6472   }
6473   return Tmp;
6474 }
6475
6476 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6477                                           const SDLoc &dl) const {
6478   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6479     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6480
6481   ReuseLoadInfo RLI;
6482   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6483
6484   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6485                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6486 }
6487
6488 // We're trying to insert a regular store, S, and then a load, L. If the
6489 // incoming value, O, is a load, we might just be able to have our load use the
6490 // address used by O. However, we don't know if anything else will store to
6491 // that address before we can load from it. To prevent this situation, we need
6492 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6493 // the same chain operand as O, we create a token factor from the chain results
6494 // of O and L, and we replace all uses of O's chain result with that token
6495 // factor (see spliceIntoChain below for this last part).
6496 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6497                                             ReuseLoadInfo &RLI,
6498                                             SelectionDAG &DAG,
6499                                             ISD::LoadExtType ET) const {
6500   SDLoc dl(Op);
6501   if (ET == ISD::NON_EXTLOAD &&
6502       (Op.getOpcode() == ISD::FP_TO_UINT ||
6503        Op.getOpcode() == ISD::FP_TO_SINT) &&
6504       isOperationLegalOrCustom(Op.getOpcode(),
6505                                Op.getOperand(0).getValueType())) {
6506
6507     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6508     return true;
6509   }
6510
6511   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6512   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6513       LD->isNonTemporal())
6514     return false;
6515   if (LD->getMemoryVT() != MemVT)
6516     return false;
6517
6518   RLI.Ptr = LD->getBasePtr();
6519   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6520     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6521            "Non-pre-inc AM on PPC?");
6522     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6523                           LD->getOffset());
6524   }
6525
6526   RLI.Chain = LD->getChain();
6527   RLI.MPI = LD->getPointerInfo();
6528   RLI.IsDereferenceable = LD->isDereferenceable();
6529   RLI.IsInvariant = LD->isInvariant();
6530   RLI.Alignment = LD->getAlignment();
6531   RLI.AAInfo = LD->getAAInfo();
6532   RLI.Ranges = LD->getRanges();
6533
6534   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6535   return true;
6536 }
6537
6538 // Given the head of the old chain, ResChain, insert a token factor containing
6539 // it and NewResChain, and make users of ResChain now be users of that token
6540 // factor.
6541 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6542                                         SDValue NewResChain,
6543                                         SelectionDAG &DAG) const {
6544   if (!ResChain)
6545     return;
6546
6547   SDLoc dl(NewResChain);
6548
6549   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6550                            NewResChain, DAG.getUNDEF(MVT::Other));
6551   assert(TF.getNode() != NewResChain.getNode() &&
6552          "A new TF really is required here");
6553
6554   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6555   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6556 }
6557
6558 /// \brief Analyze profitability of direct move
6559 /// prefer float load to int load plus direct move
6560 /// when there is no integer use of int load
6561 static bool directMoveIsProfitable(const SDValue &Op) {
6562   SDNode *Origin = Op.getOperand(0).getNode();
6563   if (Origin->getOpcode() != ISD::LOAD)
6564     return true;
6565
6566   for (SDNode::use_iterator UI = Origin->use_begin(),
6567                             UE = Origin->use_end();
6568        UI != UE; ++UI) {
6569
6570     // Only look at the users of the loaded value.
6571     if (UI.getUse().get().getResNo() != 0)
6572       continue;
6573
6574     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6575         UI->getOpcode() != ISD::UINT_TO_FP)
6576       return true;
6577   }
6578
6579   return false;
6580 }
6581
6582 /// \brief Custom lowers integer to floating point conversions to use
6583 /// the direct move instructions available in ISA 2.07 to avoid the
6584 /// need for load/store combinations.
6585 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6586                                                     SelectionDAG &DAG,
6587                                                     const SDLoc &dl) const {
6588   assert((Op.getValueType() == MVT::f32 ||
6589           Op.getValueType() == MVT::f64) &&
6590          "Invalid floating point type as target of conversion");
6591   assert(Subtarget.hasFPCVT() &&
6592          "Int to FP conversions with direct moves require FPCVT");
6593   SDValue FP;
6594   SDValue Src = Op.getOperand(0);
6595   bool SinglePrec = Op.getValueType() == MVT::f32;
6596   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6597   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6598   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6599                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6600
6601   if (WordInt) {
6602     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6603                      dl, MVT::f64, Src);
6604     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6605   }
6606   else {
6607     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6608     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6609   }
6610
6611   return FP;
6612 }
6613
6614 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6615                                           SelectionDAG &DAG) const {
6616   SDLoc dl(Op);
6617
6618   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6619     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6620       return SDValue();
6621
6622     SDValue Value = Op.getOperand(0);
6623     // The values are now known to be -1 (false) or 1 (true). To convert this
6624     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6625     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6626     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6627
6628     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6629
6630     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6631
6632     if (Op.getValueType() != MVT::v4f64)
6633       Value = DAG.getNode(ISD::FP_ROUND, dl,
6634                           Op.getValueType(), Value,
6635                           DAG.getIntPtrConstant(1, dl));
6636     return Value;
6637   }
6638
6639   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6640   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6641     return SDValue();
6642
6643   if (Op.getOperand(0).getValueType() == MVT::i1)
6644     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6645                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6646                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6647
6648   // If we have direct moves, we can do all the conversion, skip the store/load
6649   // however, without FPCVT we can't do most conversions.
6650   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6651       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6652     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6653
6654   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6655          "UINT_TO_FP is supported only with FPCVT");
6656
6657   // If we have FCFIDS, then use it when converting to single-precision.
6658   // Otherwise, convert to double-precision and then round.
6659   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6660                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6661                                                             : PPCISD::FCFIDS)
6662                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6663                                                             : PPCISD::FCFID);
6664   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6665                   ? MVT::f32
6666                   : MVT::f64;
6667
6668   if (Op.getOperand(0).getValueType() == MVT::i64) {
6669     SDValue SINT = Op.getOperand(0);
6670     // When converting to single-precision, we actually need to convert
6671     // to double-precision first and then round to single-precision.
6672     // To avoid double-rounding effects during that operation, we have
6673     // to prepare the input operand.  Bits that might be truncated when
6674     // converting to double-precision are replaced by a bit that won't
6675     // be lost at this stage, but is below the single-precision rounding
6676     // position.
6677     //
6678     // However, if -enable-unsafe-fp-math is in effect, accept double
6679     // rounding to avoid the extra overhead.
6680     if (Op.getValueType() == MVT::f32 &&
6681         !Subtarget.hasFPCVT() &&
6682         !DAG.getTarget().Options.UnsafeFPMath) {
6683
6684       // Twiddle input to make sure the low 11 bits are zero.  (If this
6685       // is the case, we are guaranteed the value will fit into the 53 bit
6686       // mantissa of an IEEE double-precision value without rounding.)
6687       // If any of those low 11 bits were not zero originally, make sure
6688       // bit 12 (value 2048) is set instead, so that the final rounding
6689       // to single-precision gets the correct result.
6690       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6691                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6692       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6693                           Round, DAG.getConstant(2047, dl, MVT::i64));
6694       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6695       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6696                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6697
6698       // However, we cannot use that value unconditionally: if the magnitude
6699       // of the input value is small, the bit-twiddling we did above might
6700       // end up visibly changing the output.  Fortunately, in that case, we
6701       // don't need to twiddle bits since the original input will convert
6702       // exactly to double-precision floating-point already.  Therefore,
6703       // construct a conditional to use the original value if the top 11
6704       // bits are all sign-bit copies, and use the rounded value computed
6705       // above otherwise.
6706       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6707                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6708       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6709                          Cond, DAG.getConstant(1, dl, MVT::i64));
6710       Cond = DAG.getSetCC(dl, MVT::i32,
6711                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6712
6713       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6714     }
6715
6716     ReuseLoadInfo RLI;
6717     SDValue Bits;
6718
6719     MachineFunction &MF = DAG.getMachineFunction();
6720     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6721       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6722                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6723       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6724     } else if (Subtarget.hasLFIWAX() &&
6725                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6726       MachineMemOperand *MMO =
6727         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6728                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6729       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6730       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6731                                      DAG.getVTList(MVT::f64, MVT::Other),
6732                                      Ops, MVT::i32, MMO);
6733       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6734     } else if (Subtarget.hasFPCVT() &&
6735                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6736       MachineMemOperand *MMO =
6737         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6738                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6739       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6740       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6741                                      DAG.getVTList(MVT::f64, MVT::Other),
6742                                      Ops, MVT::i32, MMO);
6743       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6744     } else if (((Subtarget.hasLFIWAX() &&
6745                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6746                 (Subtarget.hasFPCVT() &&
6747                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6748                SINT.getOperand(0).getValueType() == MVT::i32) {
6749       MachineFrameInfo &MFI = MF.getFrameInfo();
6750       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6751
6752       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6753       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6754
6755       SDValue Store =
6756           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6757                        MachinePointerInfo::getFixedStack(
6758                            DAG.getMachineFunction(), FrameIdx));
6759
6760       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6761              "Expected an i32 store");
6762
6763       RLI.Ptr = FIdx;
6764       RLI.Chain = Store;
6765       RLI.MPI =
6766           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6767       RLI.Alignment = 4;
6768
6769       MachineMemOperand *MMO =
6770         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6771                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6772       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6773       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6774                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6775                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6776                                      Ops, MVT::i32, MMO);
6777     } else
6778       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6779
6780     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6781
6782     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6783       FP = DAG.getNode(ISD::FP_ROUND, dl,
6784                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6785     return FP;
6786   }
6787
6788   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6789          "Unhandled INT_TO_FP type in custom expander!");
6790   // Since we only generate this in 64-bit mode, we can take advantage of
6791   // 64-bit registers.  In particular, sign extend the input value into the
6792   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6793   // then lfd it and fcfid it.
6794   MachineFunction &MF = DAG.getMachineFunction();
6795   MachineFrameInfo &MFI = MF.getFrameInfo();
6796   EVT PtrVT = getPointerTy(MF.getDataLayout());
6797
6798   SDValue Ld;
6799   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6800     ReuseLoadInfo RLI;
6801     bool ReusingLoad;
6802     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6803                                             DAG))) {
6804       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6805       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6806
6807       SDValue Store =
6808           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6809                        MachinePointerInfo::getFixedStack(
6810                            DAG.getMachineFunction(), FrameIdx));
6811
6812       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6813              "Expected an i32 store");
6814
6815       RLI.Ptr = FIdx;
6816       RLI.Chain = Store;
6817       RLI.MPI =
6818           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6819       RLI.Alignment = 4;
6820     }
6821
6822     MachineMemOperand *MMO =
6823       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6824                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6825     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6826     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6827                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6828                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6829                                  Ops, MVT::i32, MMO);
6830     if (ReusingLoad)
6831       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6832   } else {
6833     assert(Subtarget.isPPC64() &&
6834            "i32->FP without LFIWAX supported only on PPC64");
6835
6836     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6837     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6838
6839     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6840                                 Op.getOperand(0));
6841
6842     // STD the extended value into the stack slot.
6843     SDValue Store = DAG.getStore(
6844         DAG.getEntryNode(), dl, Ext64, FIdx,
6845         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6846
6847     // Load the value as a double.
6848     Ld = DAG.getLoad(
6849         MVT::f64, dl, Store, FIdx,
6850         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6851   }
6852
6853   // FCFID it and return it.
6854   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6855   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6856     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6857                      DAG.getIntPtrConstant(0, dl));
6858   return FP;
6859 }
6860
6861 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6862                                             SelectionDAG &DAG) const {
6863   SDLoc dl(Op);
6864   /*
6865    The rounding mode is in bits 30:31 of FPSR, and has the following
6866    settings:
6867      00 Round to nearest
6868      01 Round to 0
6869      10 Round to +inf
6870      11 Round to -inf
6871
6872   FLT_ROUNDS, on the other hand, expects the following:
6873     -1 Undefined
6874      0 Round to 0
6875      1 Round to nearest
6876      2 Round to +inf
6877      3 Round to -inf
6878
6879   To perform the conversion, we do:
6880     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6881   */
6882
6883   MachineFunction &MF = DAG.getMachineFunction();
6884   EVT VT = Op.getValueType();
6885   EVT PtrVT = getPointerTy(MF.getDataLayout());
6886
6887   // Save FP Control Word to register
6888   EVT NodeTys[] = {
6889     MVT::f64,    // return register
6890     MVT::Glue    // unused in this context
6891   };
6892   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6893
6894   // Save FP register to stack slot
6895   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
6896   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6897   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
6898                                MachinePointerInfo());
6899
6900   // Load FP Control Word from low 32 bits of stack slot.
6901   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6902   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6903   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
6904
6905   // Transform as necessary
6906   SDValue CWD1 =
6907     DAG.getNode(ISD::AND, dl, MVT::i32,
6908                 CWD, DAG.getConstant(3, dl, MVT::i32));
6909   SDValue CWD2 =
6910     DAG.getNode(ISD::SRL, dl, MVT::i32,
6911                 DAG.getNode(ISD::AND, dl, MVT::i32,
6912                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6913                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6914                             DAG.getConstant(3, dl, MVT::i32)),
6915                 DAG.getConstant(1, dl, MVT::i32));
6916
6917   SDValue RetVal =
6918     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6919
6920   return DAG.getNode((VT.getSizeInBits() < 16 ?
6921                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6922 }
6923
6924 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6925   EVT VT = Op.getValueType();
6926   unsigned BitWidth = VT.getSizeInBits();
6927   SDLoc dl(Op);
6928   assert(Op.getNumOperands() == 3 &&
6929          VT == Op.getOperand(1).getValueType() &&
6930          "Unexpected SHL!");
6931
6932   // Expand into a bunch of logical ops.  Note that these ops
6933   // depend on the PPC behavior for oversized shift amounts.
6934   SDValue Lo = Op.getOperand(0);
6935   SDValue Hi = Op.getOperand(1);
6936   SDValue Amt = Op.getOperand(2);
6937   EVT AmtVT = Amt.getValueType();
6938
6939   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6940                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6941   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6942   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6943   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6944   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6945                              DAG.getConstant(-BitWidth, dl, AmtVT));
6946   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6947   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6948   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6949   SDValue OutOps[] = { OutLo, OutHi };
6950   return DAG.getMergeValues(OutOps, dl);
6951 }
6952
6953 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6954   EVT VT = Op.getValueType();
6955   SDLoc dl(Op);
6956   unsigned BitWidth = VT.getSizeInBits();
6957   assert(Op.getNumOperands() == 3 &&
6958          VT == Op.getOperand(1).getValueType() &&
6959          "Unexpected SRL!");
6960
6961   // Expand into a bunch of logical ops.  Note that these ops
6962   // depend on the PPC behavior for oversized shift amounts.
6963   SDValue Lo = Op.getOperand(0);
6964   SDValue Hi = Op.getOperand(1);
6965   SDValue Amt = Op.getOperand(2);
6966   EVT AmtVT = Amt.getValueType();
6967
6968   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6969                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6970   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6971   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6972   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6973   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6974                              DAG.getConstant(-BitWidth, dl, AmtVT));
6975   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6976   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6977   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6978   SDValue OutOps[] = { OutLo, OutHi };
6979   return DAG.getMergeValues(OutOps, dl);
6980 }
6981
6982 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6983   SDLoc dl(Op);
6984   EVT VT = Op.getValueType();
6985   unsigned BitWidth = VT.getSizeInBits();
6986   assert(Op.getNumOperands() == 3 &&
6987          VT == Op.getOperand(1).getValueType() &&
6988          "Unexpected SRA!");
6989
6990   // Expand into a bunch of logical ops, followed by a select_cc.
6991   SDValue Lo = Op.getOperand(0);
6992   SDValue Hi = Op.getOperand(1);
6993   SDValue Amt = Op.getOperand(2);
6994   EVT AmtVT = Amt.getValueType();
6995
6996   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6997                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6998   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6999   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7000   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7001   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7002                              DAG.getConstant(-BitWidth, dl, AmtVT));
7003   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7004   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7005   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7006                                   Tmp4, Tmp6, ISD::SETLE);
7007   SDValue OutOps[] = { OutLo, OutHi };
7008   return DAG.getMergeValues(OutOps, dl);
7009 }
7010
7011 //===----------------------------------------------------------------------===//
7012 // Vector related lowering.
7013 //
7014
7015 /// BuildSplatI - Build a canonical splati of Val with an element size of
7016 /// SplatSize.  Cast the result to VT.
7017 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7018                            SelectionDAG &DAG, const SDLoc &dl) {
7019   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7020
7021   static const MVT VTys[] = { // canonical VT to use for each size.
7022     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7023   };
7024
7025   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7026
7027   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7028   if (Val == -1)
7029     SplatSize = 1;
7030
7031   EVT CanonicalVT = VTys[SplatSize-1];
7032
7033   // Build a canonical splat for this value.
7034   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7035 }
7036
7037 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7038 /// specified intrinsic ID.
7039 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7040                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7041   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7042   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7043                      DAG.getConstant(IID, dl, MVT::i32), Op);
7044 }
7045
7046 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7047 /// specified intrinsic ID.
7048 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7049                                 SelectionDAG &DAG, const SDLoc &dl,
7050                                 EVT DestVT = MVT::Other) {
7051   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7052   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7053                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7054 }
7055
7056 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7057 /// specified intrinsic ID.
7058 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7059                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7060                                 EVT DestVT = MVT::Other) {
7061   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7062   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7063                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7064 }
7065
7066 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7067 /// amount.  The result has the specified value type.
7068 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7069                            SelectionDAG &DAG, const SDLoc &dl) {
7070   // Force LHS/RHS to be the right type.
7071   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7072   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7073
7074   int Ops[16];
7075   for (unsigned i = 0; i != 16; ++i)
7076     Ops[i] = i + Amt;
7077   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7078   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7079 }
7080
7081 // If this is a case we can't handle, return null and let the default
7082 // expansion code take care of it.  If we CAN select this case, and if it
7083 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7084 // this case more efficiently than a constant pool load, lower it to the
7085 // sequence of ops that should be used.
7086 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7087                                              SelectionDAG &DAG) const {
7088   SDLoc dl(Op);
7089   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7090   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7091
7092   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7093     // We first build an i32 vector, load it into a QPX register,
7094     // then convert it to a floating-point vector and compare it
7095     // to a zero vector to get the boolean result.
7096     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7097     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7098     MachinePointerInfo PtrInfo =
7099         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7100     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7101     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7102
7103     assert(BVN->getNumOperands() == 4 &&
7104       "BUILD_VECTOR for v4i1 does not have 4 operands");
7105
7106     bool IsConst = true;
7107     for (unsigned i = 0; i < 4; ++i) {
7108       if (BVN->getOperand(i).isUndef()) continue;
7109       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7110         IsConst = false;
7111         break;
7112       }
7113     }
7114
7115     if (IsConst) {
7116       Constant *One =
7117         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7118       Constant *NegOne =
7119         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7120
7121       Constant *CV[4];
7122       for (unsigned i = 0; i < 4; ++i) {
7123         if (BVN->getOperand(i).isUndef())
7124           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7125         else if (isNullConstant(BVN->getOperand(i)))
7126           CV[i] = NegOne;
7127         else
7128           CV[i] = One;
7129       }
7130
7131       Constant *CP = ConstantVector::get(CV);
7132       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7133                                           16 /* alignment */);
7134
7135       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7136       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7137       return DAG.getMemIntrinsicNode(
7138           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7139           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7140     }
7141
7142     SmallVector<SDValue, 4> Stores;
7143     for (unsigned i = 0; i < 4; ++i) {
7144       if (BVN->getOperand(i).isUndef()) continue;
7145
7146       unsigned Offset = 4*i;
7147       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7148       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7149
7150       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7151       if (StoreSize > 4) {
7152         Stores.push_back(
7153             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7154                               PtrInfo.getWithOffset(Offset), MVT::i32));
7155       } else {
7156         SDValue StoreValue = BVN->getOperand(i);
7157         if (StoreSize < 4)
7158           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7159
7160         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7161                                       PtrInfo.getWithOffset(Offset)));
7162       }
7163     }
7164
7165     SDValue StoreChain;
7166     if (!Stores.empty())
7167       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7168     else
7169       StoreChain = DAG.getEntryNode();
7170
7171     // Now load from v4i32 into the QPX register; this will extend it to
7172     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7173     // is typed as v4f64 because the QPX register integer states are not
7174     // explicitly represented.
7175
7176     SDValue Ops[] = {StoreChain,
7177                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7178                      FIdx};
7179     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7180
7181     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7182       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7183     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7184       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7185       LoadedVect);
7186
7187     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7188
7189     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7190   }
7191
7192   // All other QPX vectors are handled by generic code.
7193   if (Subtarget.hasQPX())
7194     return SDValue();
7195
7196   // Check if this is a splat of a constant value.
7197   APInt APSplatBits, APSplatUndef;
7198   unsigned SplatBitSize;
7199   bool HasAnyUndefs;
7200   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7201                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7202       SplatBitSize > 32)
7203     return SDValue();
7204
7205   unsigned SplatBits = APSplatBits.getZExtValue();
7206   unsigned SplatUndef = APSplatUndef.getZExtValue();
7207   unsigned SplatSize = SplatBitSize / 8;
7208
7209   // First, handle single instruction cases.
7210
7211   // All zeros?
7212   if (SplatBits == 0) {
7213     // Canonicalize all zero vectors to be v4i32.
7214     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7215       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7216       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7217     }
7218     return Op;
7219   }
7220
7221   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7222   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7223                     (32-SplatBitSize));
7224   if (SextVal >= -16 && SextVal <= 15)
7225     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7226
7227   // Two instruction sequences.
7228
7229   // If this value is in the range [-32,30] and is even, use:
7230   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7231   // If this value is in the range [17,31] and is odd, use:
7232   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7233   // If this value is in the range [-31,-17] and is odd, use:
7234   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7235   // Note the last two are three-instruction sequences.
7236   if (SextVal >= -32 && SextVal <= 31) {
7237     // To avoid having these optimizations undone by constant folding,
7238     // we convert to a pseudo that will be expanded later into one of
7239     // the above forms.
7240     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7241     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7242               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7243     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7244     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7245     if (VT == Op.getValueType())
7246       return RetVal;
7247     else
7248       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7249   }
7250
7251   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7252   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7253   // for fneg/fabs.
7254   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7255     // Make -1 and vspltisw -1:
7256     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7257
7258     // Make the VSLW intrinsic, computing 0x8000_0000.
7259     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7260                                    OnesV, DAG, dl);
7261
7262     // xor by OnesV to invert it.
7263     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7264     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7265   }
7266
7267   // Check to see if this is a wide variety of vsplti*, binop self cases.
7268   static const signed char SplatCsts[] = {
7269     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7270     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7271   };
7272
7273   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7274     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7275     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7276     int i = SplatCsts[idx];
7277
7278     // Figure out what shift amount will be used by altivec if shifted by i in
7279     // this splat size.
7280     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7281
7282     // vsplti + shl 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_vslb, Intrinsic::ppc_altivec_vslh, 0,
7287         Intrinsic::ppc_altivec_vslw
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 + srl 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_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7298         Intrinsic::ppc_altivec_vsrw
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 + sra self.
7305     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7306       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7307       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7308         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7309         Intrinsic::ppc_altivec_vsraw
7310       };
7311       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7312       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7313     }
7314
7315     // vsplti + rol self.
7316     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7317                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7318       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7319       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7320         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7321         Intrinsic::ppc_altivec_vrlw
7322       };
7323       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7324       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7325     }
7326
7327     // t = vsplti c, result = vsldoi t, t, 1
7328     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7329       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7330       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7331       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7332     }
7333     // t = vsplti c, result = vsldoi t, t, 2
7334     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7335       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7336       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7337       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7338     }
7339     // t = vsplti c, result = vsldoi t, t, 3
7340     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7341       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7342       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7343       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7344     }
7345   }
7346
7347   return SDValue();
7348 }
7349
7350 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7351 /// the specified operations to build the shuffle.
7352 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7353                                       SDValue RHS, SelectionDAG &DAG,
7354                                       const SDLoc &dl) {
7355   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7356   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7357   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7358
7359   enum {
7360     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7361     OP_VMRGHW,
7362     OP_VMRGLW,
7363     OP_VSPLTISW0,
7364     OP_VSPLTISW1,
7365     OP_VSPLTISW2,
7366     OP_VSPLTISW3,
7367     OP_VSLDOI4,
7368     OP_VSLDOI8,
7369     OP_VSLDOI12
7370   };
7371
7372   if (OpNum == OP_COPY) {
7373     if (LHSID == (1*9+2)*9+3) return LHS;
7374     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7375     return RHS;
7376   }
7377
7378   SDValue OpLHS, OpRHS;
7379   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7380   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7381
7382   int ShufIdxs[16];
7383   switch (OpNum) {
7384   default: llvm_unreachable("Unknown i32 permute!");
7385   case OP_VMRGHW:
7386     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7387     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7388     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7389     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7390     break;
7391   case OP_VMRGLW:
7392     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7393     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7394     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7395     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7396     break;
7397   case OP_VSPLTISW0:
7398     for (unsigned i = 0; i != 16; ++i)
7399       ShufIdxs[i] = (i&3)+0;
7400     break;
7401   case OP_VSPLTISW1:
7402     for (unsigned i = 0; i != 16; ++i)
7403       ShufIdxs[i] = (i&3)+4;
7404     break;
7405   case OP_VSPLTISW2:
7406     for (unsigned i = 0; i != 16; ++i)
7407       ShufIdxs[i] = (i&3)+8;
7408     break;
7409   case OP_VSPLTISW3:
7410     for (unsigned i = 0; i != 16; ++i)
7411       ShufIdxs[i] = (i&3)+12;
7412     break;
7413   case OP_VSLDOI4:
7414     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7415   case OP_VSLDOI8:
7416     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7417   case OP_VSLDOI12:
7418     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7419   }
7420   EVT VT = OpLHS.getValueType();
7421   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7422   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7423   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7424   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7425 }
7426
7427 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7428 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7429 /// return the code it can be lowered into.  Worst case, it can always be
7430 /// lowered into a vperm.
7431 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7432                                                SelectionDAG &DAG) const {
7433   SDLoc dl(Op);
7434   SDValue V1 = Op.getOperand(0);
7435   SDValue V2 = Op.getOperand(1);
7436   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7437   EVT VT = Op.getValueType();
7438   bool isLittleEndian = Subtarget.isLittleEndian();
7439
7440   unsigned ShiftElts, InsertAtByte;
7441   bool Swap;
7442   if (Subtarget.hasP9Vector() &&
7443       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7444                            isLittleEndian)) {
7445     if (Swap)
7446       std::swap(V1, V2);
7447     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7448     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7449     if (ShiftElts) {
7450       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7451                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7452       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7453                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7454       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7455     }
7456     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7457                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7458     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7459   }
7460
7461   if (Subtarget.hasVSX()) {
7462     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7463       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7464       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7465       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7466                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7467       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7468     }
7469
7470     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7471     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7472       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7473       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7474       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7475     }
7476
7477   }
7478
7479   if (Subtarget.hasQPX()) {
7480     if (VT.getVectorNumElements() != 4)
7481       return SDValue();
7482
7483     if (V2.isUndef()) V2 = V1;
7484
7485     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7486     if (AlignIdx != -1) {
7487       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7488                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7489     } else if (SVOp->isSplat()) {
7490       int SplatIdx = SVOp->getSplatIndex();
7491       if (SplatIdx >= 4) {
7492         std::swap(V1, V2);
7493         SplatIdx -= 4;
7494       }
7495
7496       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7497                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7498     }
7499
7500     // Lower this into a qvgpci/qvfperm pair.
7501
7502     // Compute the qvgpci literal
7503     unsigned idx = 0;
7504     for (unsigned i = 0; i < 4; ++i) {
7505       int m = SVOp->getMaskElt(i);
7506       unsigned mm = m >= 0 ? (unsigned) m : i;
7507       idx |= mm << (3-i)*3;
7508     }
7509
7510     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7511                              DAG.getConstant(idx, dl, MVT::i32));
7512     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7513   }
7514
7515   // Cases that are handled by instructions that take permute immediates
7516   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7517   // selected by the instruction selector.
7518   if (V2.isUndef()) {
7519     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7520         PPC::isSplatShuffleMask(SVOp, 2) ||
7521         PPC::isSplatShuffleMask(SVOp, 4) ||
7522         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7523         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7524         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7525         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7526         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7527         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7528         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7529         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7530         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7531         (Subtarget.hasP8Altivec() && (
7532          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7533          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7534          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7535       return Op;
7536     }
7537   }
7538
7539   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7540   // and produce a fixed permutation.  If any of these match, do not lower to
7541   // VPERM.
7542   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7543   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7544       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7545       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7546       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7547       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7548       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7549       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7550       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7551       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7552       (Subtarget.hasP8Altivec() && (
7553        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7554        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7555        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7556     return Op;
7557
7558   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7559   // perfect shuffle table to emit an optimal matching sequence.
7560   ArrayRef<int> PermMask = SVOp->getMask();
7561
7562   unsigned PFIndexes[4];
7563   bool isFourElementShuffle = true;
7564   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7565     unsigned EltNo = 8;   // Start out undef.
7566     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7567       if (PermMask[i*4+j] < 0)
7568         continue;   // Undef, ignore it.
7569
7570       unsigned ByteSource = PermMask[i*4+j];
7571       if ((ByteSource & 3) != j) {
7572         isFourElementShuffle = false;
7573         break;
7574       }
7575
7576       if (EltNo == 8) {
7577         EltNo = ByteSource/4;
7578       } else if (EltNo != ByteSource/4) {
7579         isFourElementShuffle = false;
7580         break;
7581       }
7582     }
7583     PFIndexes[i] = EltNo;
7584   }
7585
7586   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7587   // perfect shuffle vector to determine if it is cost effective to do this as
7588   // discrete instructions, or whether we should use a vperm.
7589   // For now, we skip this for little endian until such time as we have a
7590   // little-endian perfect shuffle table.
7591   if (isFourElementShuffle && !isLittleEndian) {
7592     // Compute the index in the perfect shuffle table.
7593     unsigned PFTableIndex =
7594       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7595
7596     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7597     unsigned Cost  = (PFEntry >> 30);
7598
7599     // Determining when to avoid vperm is tricky.  Many things affect the cost
7600     // of vperm, particularly how many times the perm mask needs to be computed.
7601     // For example, if the perm mask can be hoisted out of a loop or is already
7602     // used (perhaps because there are multiple permutes with the same shuffle
7603     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7604     // the loop requires an extra register.
7605     //
7606     // As a compromise, we only emit discrete instructions if the shuffle can be
7607     // generated in 3 or fewer operations.  When we have loop information
7608     // available, if this block is within a loop, we should avoid using vperm
7609     // for 3-operation perms and use a constant pool load instead.
7610     if (Cost < 3)
7611       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7612   }
7613
7614   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7615   // vector that will get spilled to the constant pool.
7616   if (V2.isUndef()) V2 = V1;
7617
7618   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7619   // that it is in input element units, not in bytes.  Convert now.
7620
7621   // For little endian, the order of the input vectors is reversed, and
7622   // the permutation mask is complemented with respect to 31.  This is
7623   // necessary to produce proper semantics with the big-endian-biased vperm
7624   // instruction.
7625   EVT EltVT = V1.getValueType().getVectorElementType();
7626   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7627
7628   SmallVector<SDValue, 16> ResultMask;
7629   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7630     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7631
7632     for (unsigned j = 0; j != BytesPerElement; ++j)
7633       if (isLittleEndian)
7634         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7635                                              dl, MVT::i32));
7636       else
7637         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7638                                              MVT::i32));
7639   }
7640
7641   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7642   if (isLittleEndian)
7643     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7644                        V2, V1, VPermMask);
7645   else
7646     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7647                        V1, V2, VPermMask);
7648 }
7649
7650 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7651 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7652 /// information about the intrinsic.
7653 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7654                                  bool &isDot, const PPCSubtarget &Subtarget) {
7655   unsigned IntrinsicID =
7656     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7657   CompareOpc = -1;
7658   isDot = false;
7659   switch (IntrinsicID) {
7660   default: return false;
7661     // Comparison predicates.
7662   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7663   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7664   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7665   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7666   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7667   case Intrinsic::ppc_altivec_vcmpequd_p:
7668     if (Subtarget.hasP8Altivec()) {
7669       CompareOpc = 199;
7670       isDot = 1;
7671     } else
7672       return false;
7673
7674     break;
7675   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7676   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7677   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7678   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7679   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7680   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7681     if (Subtarget.hasP8Altivec()) {
7682       CompareOpc = 967;
7683       isDot = 1;
7684     } else
7685       return false;
7686
7687     break;
7688   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7689   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7690   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7691   case Intrinsic::ppc_altivec_vcmpgtud_p:
7692     if (Subtarget.hasP8Altivec()) {
7693       CompareOpc = 711;
7694       isDot = 1;
7695     } else
7696       return false;
7697
7698     break;
7699     // VSX predicate comparisons use the same infrastructure
7700   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7701   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7702   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7703   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7704   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7705   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7706     if (Subtarget.hasVSX()) {
7707       switch (IntrinsicID) {
7708       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7709       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7710       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7711       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7712       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7713       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7714       }
7715       isDot = 1;
7716     }
7717     else
7718       return false;
7719
7720     break;
7721
7722     // Normal Comparisons.
7723   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7724   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7725   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7726   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7727   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7728   case Intrinsic::ppc_altivec_vcmpequd:
7729     if (Subtarget.hasP8Altivec()) {
7730       CompareOpc = 199;
7731       isDot = 0;
7732     } else
7733       return false;
7734
7735     break;
7736   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7737   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7738   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7739   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7740   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7741   case Intrinsic::ppc_altivec_vcmpgtsd:
7742     if (Subtarget.hasP8Altivec()) {
7743       CompareOpc = 967;
7744       isDot = 0;
7745     } else
7746       return false;
7747
7748     break;
7749   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7750   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7751   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7752   case Intrinsic::ppc_altivec_vcmpgtud:
7753     if (Subtarget.hasP8Altivec()) {
7754       CompareOpc = 711;
7755       isDot = 0;
7756     } else
7757       return false;
7758
7759     break;
7760   }
7761   return true;
7762 }
7763
7764 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7765 /// lower, do it, otherwise return null.
7766 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7767                                                    SelectionDAG &DAG) const {
7768   unsigned IntrinsicID =
7769     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7770
7771   if (IntrinsicID == Intrinsic::thread_pointer) {
7772     // Reads the thread pointer register, used for __builtin_thread_pointer.
7773     bool is64bit = Subtarget.isPPC64();
7774     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
7775                            is64bit ? MVT::i64 : MVT::i32);
7776   }
7777
7778   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7779   // opcode number of the comparison.
7780   SDLoc dl(Op);
7781   int CompareOpc;
7782   bool isDot;
7783   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7784     return SDValue();    // Don't custom lower most intrinsics.
7785
7786   // If this is a non-dot comparison, make the VCMP node and we are done.
7787   if (!isDot) {
7788     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7789                               Op.getOperand(1), Op.getOperand(2),
7790                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7791     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7792   }
7793
7794   // Create the PPCISD altivec 'dot' comparison node.
7795   SDValue Ops[] = {
7796     Op.getOperand(2),  // LHS
7797     Op.getOperand(3),  // RHS
7798     DAG.getConstant(CompareOpc, dl, MVT::i32)
7799   };
7800   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7801   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7802
7803   // Now that we have the comparison, emit a copy from the CR to a GPR.
7804   // This is flagged to the above dot comparison.
7805   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7806                                 DAG.getRegister(PPC::CR6, MVT::i32),
7807                                 CompNode.getValue(1));
7808
7809   // Unpack the result based on how the target uses it.
7810   unsigned BitNo;   // Bit # of CR6.
7811   bool InvertBit;   // Invert result?
7812   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7813   default:  // Can't happen, don't crash on invalid number though.
7814   case 0:   // Return the value of the EQ bit of CR6.
7815     BitNo = 0; InvertBit = false;
7816     break;
7817   case 1:   // Return the inverted value of the EQ bit of CR6.
7818     BitNo = 0; InvertBit = true;
7819     break;
7820   case 2:   // Return the value of the LT bit of CR6.
7821     BitNo = 2; InvertBit = false;
7822     break;
7823   case 3:   // Return the inverted value of the LT bit of CR6.
7824     BitNo = 2; InvertBit = true;
7825     break;
7826   }
7827
7828   // Shift the bit into the low position.
7829   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7830                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7831   // Isolate the bit.
7832   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7833                       DAG.getConstant(1, dl, MVT::i32));
7834
7835   // If we are supposed to, toggle the bit.
7836   if (InvertBit)
7837     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7838                         DAG.getConstant(1, dl, MVT::i32));
7839   return Flags;
7840 }
7841
7842 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7843                                                   SelectionDAG &DAG) const {
7844   SDLoc dl(Op);
7845   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7846   // instructions), but for smaller types, we need to first extend up to v2i32
7847   // before doing going farther.
7848   if (Op.getValueType() == MVT::v2i64) {
7849     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7850     if (ExtVT != MVT::v2i32) {
7851       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7852       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7853                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7854                                         ExtVT.getVectorElementType(), 4)));
7855       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7856       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7857                        DAG.getValueType(MVT::v2i32));
7858     }
7859
7860     return Op;
7861   }
7862
7863   return SDValue();
7864 }
7865
7866 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7867                                                    SelectionDAG &DAG) const {
7868   SDLoc dl(Op);
7869   // Create a stack slot that is 16-byte aligned.
7870   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7871   int FrameIdx = MFI.CreateStackObject(16, 16, false);
7872   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7873   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7874
7875   // Store the input value into Value#0 of the stack slot.
7876   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7877                                MachinePointerInfo());
7878   // Load it out.
7879   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
7880 }
7881
7882 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7883                                                    SelectionDAG &DAG) const {
7884   SDLoc dl(Op);
7885   SDNode *N = Op.getNode();
7886
7887   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7888          "Unknown extract_vector_elt type");
7889
7890   SDValue Value = N->getOperand(0);
7891
7892   // The first part of this is like the store lowering except that we don't
7893   // need to track the chain.
7894
7895   // The values are now known to be -1 (false) or 1 (true). To convert this
7896   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7897   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7898   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7899
7900   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7901   // understand how to form the extending load.
7902   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7903
7904   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7905
7906   // Now convert to an integer and store.
7907   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7908     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7909     Value);
7910
7911   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7912   int FrameIdx = MFI.CreateStackObject(16, 16, false);
7913   MachinePointerInfo PtrInfo =
7914       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7915   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7916   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7917
7918   SDValue StoreChain = DAG.getEntryNode();
7919   SDValue Ops[] = {StoreChain,
7920                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
7921                    Value, FIdx};
7922   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
7923
7924   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7925     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7926
7927   // Extract the value requested.
7928   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7929   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7930   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7931
7932   SDValue IntVal =
7933       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
7934
7935   if (!Subtarget.useCRBits())
7936     return IntVal;
7937
7938   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7939 }
7940
7941 /// Lowering for QPX v4i1 loads
7942 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7943                                            SelectionDAG &DAG) const {
7944   SDLoc dl(Op);
7945   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7946   SDValue LoadChain = LN->getChain();
7947   SDValue BasePtr = LN->getBasePtr();
7948
7949   if (Op.getValueType() == MVT::v4f64 ||
7950       Op.getValueType() == MVT::v4f32) {
7951     EVT MemVT = LN->getMemoryVT();
7952     unsigned Alignment = LN->getAlignment();
7953
7954     // If this load is properly aligned, then it is legal.
7955     if (Alignment >= MemVT.getStoreSize())
7956       return Op;
7957
7958     EVT ScalarVT = Op.getValueType().getScalarType(),
7959         ScalarMemVT = MemVT.getScalarType();
7960     unsigned Stride = ScalarMemVT.getStoreSize();
7961
7962     SDValue Vals[4], LoadChains[4];
7963     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7964       SDValue Load;
7965       if (ScalarVT != ScalarMemVT)
7966         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7967                               BasePtr,
7968                               LN->getPointerInfo().getWithOffset(Idx * Stride),
7969                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
7970                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
7971       else
7972         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7973                            LN->getPointerInfo().getWithOffset(Idx * Stride),
7974                            MinAlign(Alignment, Idx * Stride),
7975                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
7976
7977       if (Idx == 0 && LN->isIndexed()) {
7978         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7979                "Unknown addressing mode on vector load");
7980         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7981                                   LN->getAddressingMode());
7982       }
7983
7984       Vals[Idx] = Load;
7985       LoadChains[Idx] = Load.getValue(1);
7986
7987       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7988                             DAG.getConstant(Stride, dl,
7989                                             BasePtr.getValueType()));
7990     }
7991
7992     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7993     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
7994
7995     if (LN->isIndexed()) {
7996       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7997       return DAG.getMergeValues(RetOps, dl);
7998     }
7999
8000     SDValue RetOps[] = { Value, TF };
8001     return DAG.getMergeValues(RetOps, dl);
8002   }
8003
8004   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8005   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8006
8007   // To lower v4i1 from a byte array, we load the byte elements of the
8008   // vector and then reuse the BUILD_VECTOR logic.
8009
8010   SDValue VectElmts[4], VectElmtChains[4];
8011   for (unsigned i = 0; i < 4; ++i) {
8012     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8013     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8014
8015     VectElmts[i] = DAG.getExtLoad(
8016         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8017         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8018         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8019     VectElmtChains[i] = VectElmts[i].getValue(1);
8020   }
8021
8022   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8023   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8024
8025   SDValue RVals[] = { Value, LoadChain };
8026   return DAG.getMergeValues(RVals, dl);
8027 }
8028
8029 /// Lowering for QPX v4i1 stores
8030 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8031                                             SelectionDAG &DAG) const {
8032   SDLoc dl(Op);
8033   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8034   SDValue StoreChain = SN->getChain();
8035   SDValue BasePtr = SN->getBasePtr();
8036   SDValue Value = SN->getValue();
8037
8038   if (Value.getValueType() == MVT::v4f64 ||
8039       Value.getValueType() == MVT::v4f32) {
8040     EVT MemVT = SN->getMemoryVT();
8041     unsigned Alignment = SN->getAlignment();
8042
8043     // If this store is properly aligned, then it is legal.
8044     if (Alignment >= MemVT.getStoreSize())
8045       return Op;
8046
8047     EVT ScalarVT = Value.getValueType().getScalarType(),
8048         ScalarMemVT = MemVT.getScalarType();
8049     unsigned Stride = ScalarMemVT.getStoreSize();
8050
8051     SDValue Stores[4];
8052     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8053       SDValue Ex = DAG.getNode(
8054           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8055           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8056       SDValue Store;
8057       if (ScalarVT != ScalarMemVT)
8058         Store =
8059             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8060                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8061                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8062                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8063       else
8064         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8065                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8066                              MinAlign(Alignment, Idx * Stride),
8067                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8068
8069       if (Idx == 0 && SN->isIndexed()) {
8070         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8071                "Unknown addressing mode on vector store");
8072         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8073                                     SN->getAddressingMode());
8074       }
8075
8076       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8077                             DAG.getConstant(Stride, dl,
8078                                             BasePtr.getValueType()));
8079       Stores[Idx] = Store;
8080     }
8081
8082     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8083
8084     if (SN->isIndexed()) {
8085       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8086       return DAG.getMergeValues(RetOps, dl);
8087     }
8088
8089     return TF;
8090   }
8091
8092   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8093   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8094
8095   // The values are now known to be -1 (false) or 1 (true). To convert this
8096   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8097   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8098   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8099
8100   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8101   // understand how to form the extending load.
8102   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8103
8104   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8105
8106   // Now convert to an integer and store.
8107   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8108     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8109     Value);
8110
8111   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8112   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8113   MachinePointerInfo PtrInfo =
8114       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8115   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8116   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8117
8118   SDValue Ops[] = {StoreChain,
8119                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8120                    Value, FIdx};
8121   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8122
8123   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8124     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8125
8126   // Move data into the byte array.
8127   SDValue Loads[4], LoadChains[4];
8128   for (unsigned i = 0; i < 4; ++i) {
8129     unsigned Offset = 4*i;
8130     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8131     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8132
8133     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8134                            PtrInfo.getWithOffset(Offset));
8135     LoadChains[i] = Loads[i].getValue(1);
8136   }
8137
8138   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8139
8140   SDValue Stores[4];
8141   for (unsigned i = 0; i < 4; ++i) {
8142     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8143     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8144
8145     Stores[i] = DAG.getTruncStore(
8146         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8147         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8148         SN->getAAInfo());
8149   }
8150
8151   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8152
8153   return StoreChain;
8154 }
8155
8156 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8157   SDLoc dl(Op);
8158   if (Op.getValueType() == MVT::v4i32) {
8159     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8160
8161     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8162     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8163
8164     SDValue RHSSwap =   // = vrlw RHS, 16
8165       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8166
8167     // Shrinkify inputs to v8i16.
8168     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8169     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8170     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8171
8172     // Low parts multiplied together, generating 32-bit results (we ignore the
8173     // top parts).
8174     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8175                                         LHS, RHS, DAG, dl, MVT::v4i32);
8176
8177     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8178                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8179     // Shift the high parts up 16 bits.
8180     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8181                               Neg16, DAG, dl);
8182     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8183   } else if (Op.getValueType() == MVT::v8i16) {
8184     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8185
8186     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8187
8188     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8189                             LHS, RHS, Zero, DAG, dl);
8190   } else if (Op.getValueType() == MVT::v16i8) {
8191     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8192     bool isLittleEndian = Subtarget.isLittleEndian();
8193
8194     // Multiply the even 8-bit parts, producing 16-bit sums.
8195     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8196                                            LHS, RHS, DAG, dl, MVT::v8i16);
8197     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8198
8199     // Multiply the odd 8-bit parts, producing 16-bit sums.
8200     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8201                                           LHS, RHS, DAG, dl, MVT::v8i16);
8202     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8203
8204     // Merge the results together.  Because vmuleub and vmuloub are
8205     // instructions with a big-endian bias, we must reverse the
8206     // element numbering and reverse the meaning of "odd" and "even"
8207     // when generating little endian code.
8208     int Ops[16];
8209     for (unsigned i = 0; i != 8; ++i) {
8210       if (isLittleEndian) {
8211         Ops[i*2  ] = 2*i;
8212         Ops[i*2+1] = 2*i+16;
8213       } else {
8214         Ops[i*2  ] = 2*i+1;
8215         Ops[i*2+1] = 2*i+1+16;
8216       }
8217     }
8218     if (isLittleEndian)
8219       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8220     else
8221       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8222   } else {
8223     llvm_unreachable("Unknown mul to lower!");
8224   }
8225 }
8226
8227 /// LowerOperation - Provide custom lowering hooks for some operations.
8228 ///
8229 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8230   switch (Op.getOpcode()) {
8231   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8232   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8233   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8234   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8235   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8236   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8237   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8238   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8239   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8240   case ISD::VASTART:
8241     return LowerVASTART(Op, DAG);
8242
8243   case ISD::VAARG:
8244     return LowerVAARG(Op, DAG);
8245
8246   case ISD::VACOPY:
8247     return LowerVACOPY(Op, DAG);
8248
8249   case ISD::STACKRESTORE:
8250     return LowerSTACKRESTORE(Op, DAG);
8251
8252   case ISD::DYNAMIC_STACKALLOC:
8253     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8254
8255   case ISD::GET_DYNAMIC_AREA_OFFSET:
8256     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8257
8258   case ISD::EH_DWARF_CFA:
8259     return LowerEH_DWARF_CFA(Op, DAG);
8260
8261   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8262   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8263
8264   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8265   case ISD::STORE:              return LowerSTORE(Op, DAG);
8266   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8267   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8268   case ISD::FP_TO_UINT:
8269   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8270                                                       SDLoc(Op));
8271   case ISD::UINT_TO_FP:
8272   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8273   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8274
8275   // Lower 64-bit shifts.
8276   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8277   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8278   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8279
8280   // Vector-related lowering.
8281   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8282   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8283   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8284   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8285   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8286   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8287   case ISD::MUL:                return LowerMUL(Op, DAG);
8288
8289   // For counter-based loop handling.
8290   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8291
8292   // Frame & Return address.
8293   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8294   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8295   }
8296 }
8297
8298 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8299                                            SmallVectorImpl<SDValue>&Results,
8300                                            SelectionDAG &DAG) const {
8301   SDLoc dl(N);
8302   switch (N->getOpcode()) {
8303   default:
8304     llvm_unreachable("Do not know how to custom type legalize this operation!");
8305   case ISD::READCYCLECOUNTER: {
8306     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8307     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8308
8309     Results.push_back(RTB);
8310     Results.push_back(RTB.getValue(1));
8311     Results.push_back(RTB.getValue(2));
8312     break;
8313   }
8314   case ISD::INTRINSIC_W_CHAIN: {
8315     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8316         Intrinsic::ppc_is_decremented_ctr_nonzero)
8317       break;
8318
8319     assert(N->getValueType(0) == MVT::i1 &&
8320            "Unexpected result type for CTR decrement intrinsic");
8321     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8322                                  N->getValueType(0));
8323     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8324     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8325                                  N->getOperand(1));
8326
8327     Results.push_back(NewInt);
8328     Results.push_back(NewInt.getValue(1));
8329     break;
8330   }
8331   case ISD::VAARG: {
8332     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8333       return;
8334
8335     EVT VT = N->getValueType(0);
8336
8337     if (VT == MVT::i64) {
8338       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8339
8340       Results.push_back(NewNode);
8341       Results.push_back(NewNode.getValue(1));
8342     }
8343     return;
8344   }
8345   case ISD::FP_ROUND_INREG: {
8346     assert(N->getValueType(0) == MVT::ppcf128);
8347     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8348     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8349                              MVT::f64, N->getOperand(0),
8350                              DAG.getIntPtrConstant(0, dl));
8351     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8352                              MVT::f64, N->getOperand(0),
8353                              DAG.getIntPtrConstant(1, dl));
8354
8355     // Add the two halves of the long double in round-to-zero mode.
8356     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8357
8358     // We know the low half is about to be thrown away, so just use something
8359     // convenient.
8360     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8361                                 FPreg, FPreg));
8362     return;
8363   }
8364   case ISD::FP_TO_SINT:
8365   case ISD::FP_TO_UINT:
8366     // LowerFP_TO_INT() can only handle f32 and f64.
8367     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8368       return;
8369     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8370     return;
8371   }
8372 }
8373
8374 //===----------------------------------------------------------------------===//
8375 //  Other Lowering Code
8376 //===----------------------------------------------------------------------===//
8377
8378 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8379   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8380   Function *Func = Intrinsic::getDeclaration(M, Id);
8381   return Builder.CreateCall(Func, {});
8382 }
8383
8384 // The mappings for emitLeading/TrailingFence is taken from
8385 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8386 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8387                                          AtomicOrdering Ord, bool IsStore,
8388                                          bool IsLoad) const {
8389   if (Ord == AtomicOrdering::SequentiallyConsistent)
8390     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8391   if (isReleaseOrStronger(Ord))
8392     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8393   return nullptr;
8394 }
8395
8396 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8397                                           AtomicOrdering Ord, bool IsStore,
8398                                           bool IsLoad) const {
8399   if (IsLoad && isAcquireOrStronger(Ord))
8400     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8401   // FIXME: this is too conservative, a dependent branch + isync is enough.
8402   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8403   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8404   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8405   return nullptr;
8406 }
8407
8408 MachineBasicBlock *
8409 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8410                                     unsigned AtomicSize,
8411                                     unsigned BinOpcode,
8412                                     unsigned CmpOpcode,
8413                                     unsigned CmpPred) const {
8414   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8415   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8416
8417   auto LoadMnemonic = PPC::LDARX;
8418   auto StoreMnemonic = PPC::STDCX;
8419   switch (AtomicSize) {
8420   default:
8421     llvm_unreachable("Unexpected size of atomic entity");
8422   case 1:
8423     LoadMnemonic = PPC::LBARX;
8424     StoreMnemonic = PPC::STBCX;
8425     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8426     break;
8427   case 2:
8428     LoadMnemonic = PPC::LHARX;
8429     StoreMnemonic = PPC::STHCX;
8430     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8431     break;
8432   case 4:
8433     LoadMnemonic = PPC::LWARX;
8434     StoreMnemonic = PPC::STWCX;
8435     break;
8436   case 8:
8437     LoadMnemonic = PPC::LDARX;
8438     StoreMnemonic = PPC::STDCX;
8439     break;
8440   }
8441
8442   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8443   MachineFunction *F = BB->getParent();
8444   MachineFunction::iterator It = ++BB->getIterator();
8445
8446   unsigned dest = MI.getOperand(0).getReg();
8447   unsigned ptrA = MI.getOperand(1).getReg();
8448   unsigned ptrB = MI.getOperand(2).getReg();
8449   unsigned incr = MI.getOperand(3).getReg();
8450   DebugLoc dl = MI.getDebugLoc();
8451
8452   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8453   MachineBasicBlock *loop2MBB =
8454     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8455   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8456   F->insert(It, loopMBB);
8457   if (CmpOpcode)
8458     F->insert(It, loop2MBB);
8459   F->insert(It, exitMBB);
8460   exitMBB->splice(exitMBB->begin(), BB,
8461                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8462   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8463
8464   MachineRegisterInfo &RegInfo = F->getRegInfo();
8465   unsigned TmpReg = (!BinOpcode) ? incr :
8466     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8467                                            : &PPC::GPRCRegClass);
8468
8469   //  thisMBB:
8470   //   ...
8471   //   fallthrough --> loopMBB
8472   BB->addSuccessor(loopMBB);
8473
8474   //  loopMBB:
8475   //   l[wd]arx dest, ptr
8476   //   add r0, dest, incr
8477   //   st[wd]cx. r0, ptr
8478   //   bne- loopMBB
8479   //   fallthrough --> exitMBB
8480
8481   // For max/min...
8482   //  loopMBB:
8483   //   l[wd]arx dest, ptr
8484   //   cmpl?[wd] incr, dest
8485   //   bgt exitMBB
8486   //  loop2MBB:
8487   //   st[wd]cx. dest, ptr
8488   //   bne- loopMBB
8489   //   fallthrough --> exitMBB
8490
8491   BB = loopMBB;
8492   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8493     .addReg(ptrA).addReg(ptrB);
8494   if (BinOpcode)
8495     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8496   if (CmpOpcode) {
8497     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8498       .addReg(incr).addReg(dest);
8499     BuildMI(BB, dl, TII->get(PPC::BCC))
8500       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8501     BB->addSuccessor(loop2MBB);
8502     BB->addSuccessor(exitMBB);
8503     BB = loop2MBB;
8504   }
8505   BuildMI(BB, dl, TII->get(StoreMnemonic))
8506     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8507   BuildMI(BB, dl, TII->get(PPC::BCC))
8508     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8509   BB->addSuccessor(loopMBB);
8510   BB->addSuccessor(exitMBB);
8511
8512   //  exitMBB:
8513   //   ...
8514   BB = exitMBB;
8515   return BB;
8516 }
8517
8518 MachineBasicBlock *
8519 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8520                                             MachineBasicBlock *BB,
8521                                             bool is8bit, // operation
8522                                             unsigned BinOpcode,
8523                                             unsigned CmpOpcode,
8524                                             unsigned CmpPred) const {
8525   // If we support part-word atomic mnemonics, just use them
8526   if (Subtarget.hasPartwordAtomics())
8527     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8528                             CmpOpcode, CmpPred);
8529
8530   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8531   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8532   // In 64 bit mode we have to use 64 bits for addresses, even though the
8533   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8534   // registers without caring whether they're 32 or 64, but here we're
8535   // doing actual arithmetic on the addresses.
8536   bool is64bit = Subtarget.isPPC64();
8537   bool isLittleEndian = Subtarget.isLittleEndian();
8538   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8539
8540   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8541   MachineFunction *F = BB->getParent();
8542   MachineFunction::iterator It = ++BB->getIterator();
8543
8544   unsigned dest = MI.getOperand(0).getReg();
8545   unsigned ptrA = MI.getOperand(1).getReg();
8546   unsigned ptrB = MI.getOperand(2).getReg();
8547   unsigned incr = MI.getOperand(3).getReg();
8548   DebugLoc dl = MI.getDebugLoc();
8549
8550   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8551   MachineBasicBlock *loop2MBB =
8552     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8553   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8554   F->insert(It, loopMBB);
8555   if (CmpOpcode)
8556     F->insert(It, loop2MBB);
8557   F->insert(It, exitMBB);
8558   exitMBB->splice(exitMBB->begin(), BB,
8559                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8560   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8561
8562   MachineRegisterInfo &RegInfo = F->getRegInfo();
8563   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8564                                           : &PPC::GPRCRegClass;
8565   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8566   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8567   unsigned ShiftReg =
8568     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8569   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8570   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8571   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8572   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8573   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8574   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8575   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8576   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8577   unsigned Ptr1Reg;
8578   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8579
8580   //  thisMBB:
8581   //   ...
8582   //   fallthrough --> loopMBB
8583   BB->addSuccessor(loopMBB);
8584
8585   // The 4-byte load must be aligned, while a char or short may be
8586   // anywhere in the word.  Hence all this nasty bookkeeping code.
8587   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8588   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8589   //   xori shift, shift1, 24 [16]
8590   //   rlwinm ptr, ptr1, 0, 0, 29
8591   //   slw incr2, incr, shift
8592   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8593   //   slw mask, mask2, shift
8594   //  loopMBB:
8595   //   lwarx tmpDest, ptr
8596   //   add tmp, tmpDest, incr2
8597   //   andc tmp2, tmpDest, mask
8598   //   and tmp3, tmp, mask
8599   //   or tmp4, tmp3, tmp2
8600   //   stwcx. tmp4, ptr
8601   //   bne- loopMBB
8602   //   fallthrough --> exitMBB
8603   //   srw dest, tmpDest, shift
8604   if (ptrA != ZeroReg) {
8605     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8606     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8607       .addReg(ptrA).addReg(ptrB);
8608   } else {
8609     Ptr1Reg = ptrB;
8610   }
8611   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8612       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8613   if (!isLittleEndian)
8614     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8615         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8616   if (is64bit)
8617     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8618       .addReg(Ptr1Reg).addImm(0).addImm(61);
8619   else
8620     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8621       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8622   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8623       .addReg(incr).addReg(ShiftReg);
8624   if (is8bit)
8625     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8626   else {
8627     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8628     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8629   }
8630   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8631       .addReg(Mask2Reg).addReg(ShiftReg);
8632
8633   BB = loopMBB;
8634   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8635     .addReg(ZeroReg).addReg(PtrReg);
8636   if (BinOpcode)
8637     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8638       .addReg(Incr2Reg).addReg(TmpDestReg);
8639   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8640     .addReg(TmpDestReg).addReg(MaskReg);
8641   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8642     .addReg(TmpReg).addReg(MaskReg);
8643   if (CmpOpcode) {
8644     // For unsigned comparisons, we can directly compare the shifted values.
8645     // For signed comparisons we shift and sign extend.
8646     unsigned SReg = RegInfo.createVirtualRegister(RC);
8647     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
8648       .addReg(TmpDestReg).addReg(MaskReg);
8649     unsigned ValueReg = SReg;
8650     unsigned CmpReg = Incr2Reg;
8651     if (CmpOpcode == PPC::CMPW) {
8652       ValueReg = RegInfo.createVirtualRegister(RC);
8653       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
8654         .addReg(SReg).addReg(ShiftReg);
8655       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
8656       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
8657         .addReg(ValueReg);
8658       ValueReg = ValueSReg;
8659       CmpReg = incr;
8660     }
8661     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8662       .addReg(CmpReg).addReg(ValueReg);
8663     BuildMI(BB, dl, TII->get(PPC::BCC))
8664       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8665     BB->addSuccessor(loop2MBB);
8666     BB->addSuccessor(exitMBB);
8667     BB = loop2MBB;
8668   }
8669   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8670     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8671   BuildMI(BB, dl, TII->get(PPC::STWCX))
8672     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8673   BuildMI(BB, dl, TII->get(PPC::BCC))
8674     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8675   BB->addSuccessor(loopMBB);
8676   BB->addSuccessor(exitMBB);
8677
8678   //  exitMBB:
8679   //   ...
8680   BB = exitMBB;
8681   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8682     .addReg(ShiftReg);
8683   return BB;
8684 }
8685
8686 llvm::MachineBasicBlock *
8687 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
8688                                     MachineBasicBlock *MBB) const {
8689   DebugLoc DL = MI.getDebugLoc();
8690   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8691
8692   MachineFunction *MF = MBB->getParent();
8693   MachineRegisterInfo &MRI = MF->getRegInfo();
8694
8695   const BasicBlock *BB = MBB->getBasicBlock();
8696   MachineFunction::iterator I = ++MBB->getIterator();
8697
8698   // Memory Reference
8699   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8700   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8701
8702   unsigned DstReg = MI.getOperand(0).getReg();
8703   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8704   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8705   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8706   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8707
8708   MVT PVT = getPointerTy(MF->getDataLayout());
8709   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8710          "Invalid Pointer Size!");
8711   // For v = setjmp(buf), we generate
8712   //
8713   // thisMBB:
8714   //  SjLjSetup mainMBB
8715   //  bl mainMBB
8716   //  v_restore = 1
8717   //  b sinkMBB
8718   //
8719   // mainMBB:
8720   //  buf[LabelOffset] = LR
8721   //  v_main = 0
8722   //
8723   // sinkMBB:
8724   //  v = phi(main, restore)
8725   //
8726
8727   MachineBasicBlock *thisMBB = MBB;
8728   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8729   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8730   MF->insert(I, mainMBB);
8731   MF->insert(I, sinkMBB);
8732
8733   MachineInstrBuilder MIB;
8734
8735   // Transfer the remainder of BB and its successor edges to sinkMBB.
8736   sinkMBB->splice(sinkMBB->begin(), MBB,
8737                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8738   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8739
8740   // Note that the structure of the jmp_buf used here is not compatible
8741   // with that used by libc, and is not designed to be. Specifically, it
8742   // stores only those 'reserved' registers that LLVM does not otherwise
8743   // understand how to spill. Also, by convention, by the time this
8744   // intrinsic is called, Clang has already stored the frame address in the
8745   // first slot of the buffer and stack address in the third. Following the
8746   // X86 target code, we'll store the jump address in the second slot. We also
8747   // need to save the TOC pointer (R2) to handle jumps between shared
8748   // libraries, and that will be stored in the fourth slot. The thread
8749   // identifier (R13) is not affected.
8750
8751   // thisMBB:
8752   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8753   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8754   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8755
8756   // Prepare IP either in reg.
8757   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8758   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8759   unsigned BufReg = MI.getOperand(1).getReg();
8760
8761   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8762     setUsesTOCBasePtr(*MBB->getParent());
8763     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8764             .addReg(PPC::X2)
8765             .addImm(TOCOffset)
8766             .addReg(BufReg);
8767     MIB.setMemRefs(MMOBegin, MMOEnd);
8768   }
8769
8770   // Naked functions never have a base pointer, and so we use r1. For all
8771   // other functions, this decision must be delayed until during PEI.
8772   unsigned BaseReg;
8773   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8774     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8775   else
8776     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8777
8778   MIB = BuildMI(*thisMBB, MI, DL,
8779                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8780             .addReg(BaseReg)
8781             .addImm(BPOffset)
8782             .addReg(BufReg);
8783   MIB.setMemRefs(MMOBegin, MMOEnd);
8784
8785   // Setup
8786   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8787   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8788   MIB.addRegMask(TRI->getNoPreservedMask());
8789
8790   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8791
8792   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8793           .addMBB(mainMBB);
8794   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8795
8796   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8797   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8798
8799   // mainMBB:
8800   //  mainDstReg = 0
8801   MIB =
8802       BuildMI(mainMBB, DL,
8803               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8804
8805   // Store IP
8806   if (Subtarget.isPPC64()) {
8807     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8808             .addReg(LabelReg)
8809             .addImm(LabelOffset)
8810             .addReg(BufReg);
8811   } else {
8812     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8813             .addReg(LabelReg)
8814             .addImm(LabelOffset)
8815             .addReg(BufReg);
8816   }
8817
8818   MIB.setMemRefs(MMOBegin, MMOEnd);
8819
8820   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8821   mainMBB->addSuccessor(sinkMBB);
8822
8823   // sinkMBB:
8824   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8825           TII->get(PPC::PHI), DstReg)
8826     .addReg(mainDstReg).addMBB(mainMBB)
8827     .addReg(restoreDstReg).addMBB(thisMBB);
8828
8829   MI.eraseFromParent();
8830   return sinkMBB;
8831 }
8832
8833 MachineBasicBlock *
8834 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
8835                                      MachineBasicBlock *MBB) const {
8836   DebugLoc DL = MI.getDebugLoc();
8837   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8838
8839   MachineFunction *MF = MBB->getParent();
8840   MachineRegisterInfo &MRI = MF->getRegInfo();
8841
8842   // Memory Reference
8843   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
8844   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
8845
8846   MVT PVT = getPointerTy(MF->getDataLayout());
8847   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8848          "Invalid Pointer Size!");
8849
8850   const TargetRegisterClass *RC =
8851     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8852   unsigned Tmp = MRI.createVirtualRegister(RC);
8853   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8854   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8855   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8856   unsigned BP =
8857       (PVT == MVT::i64)
8858           ? PPC::X30
8859           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
8860                                                               : PPC::R30);
8861
8862   MachineInstrBuilder MIB;
8863
8864   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8865   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8866   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8867   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8868
8869   unsigned BufReg = MI.getOperand(0).getReg();
8870
8871   // Reload FP (the jumped-to function may not have had a
8872   // frame pointer, and if so, then its r31 will be restored
8873   // as necessary).
8874   if (PVT == MVT::i64) {
8875     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8876             .addImm(0)
8877             .addReg(BufReg);
8878   } else {
8879     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8880             .addImm(0)
8881             .addReg(BufReg);
8882   }
8883   MIB.setMemRefs(MMOBegin, MMOEnd);
8884
8885   // Reload IP
8886   if (PVT == MVT::i64) {
8887     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8888             .addImm(LabelOffset)
8889             .addReg(BufReg);
8890   } else {
8891     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8892             .addImm(LabelOffset)
8893             .addReg(BufReg);
8894   }
8895   MIB.setMemRefs(MMOBegin, MMOEnd);
8896
8897   // Reload SP
8898   if (PVT == MVT::i64) {
8899     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8900             .addImm(SPOffset)
8901             .addReg(BufReg);
8902   } else {
8903     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8904             .addImm(SPOffset)
8905             .addReg(BufReg);
8906   }
8907   MIB.setMemRefs(MMOBegin, MMOEnd);
8908
8909   // Reload BP
8910   if (PVT == MVT::i64) {
8911     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8912             .addImm(BPOffset)
8913             .addReg(BufReg);
8914   } else {
8915     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8916             .addImm(BPOffset)
8917             .addReg(BufReg);
8918   }
8919   MIB.setMemRefs(MMOBegin, MMOEnd);
8920
8921   // Reload TOC
8922   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8923     setUsesTOCBasePtr(*MBB->getParent());
8924     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8925             .addImm(TOCOffset)
8926             .addReg(BufReg);
8927
8928     MIB.setMemRefs(MMOBegin, MMOEnd);
8929   }
8930
8931   // Jump
8932   BuildMI(*MBB, MI, DL,
8933           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8934   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8935
8936   MI.eraseFromParent();
8937   return MBB;
8938 }
8939
8940 MachineBasicBlock *
8941 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8942                                                MachineBasicBlock *BB) const {
8943   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
8944       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8945     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8946         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
8947       // Call lowering should have added an r2 operand to indicate a dependence
8948       // on the TOC base pointer value. It can't however, because there is no
8949       // way to mark the dependence as implicit there, and so the stackmap code
8950       // will confuse it with a regular operand. Instead, add the dependence
8951       // here.
8952       setUsesTOCBasePtr(*BB->getParent());
8953       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8954     }
8955
8956     return emitPatchPoint(MI, BB);
8957   }
8958
8959   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8960       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
8961     return emitEHSjLjSetJmp(MI, BB);
8962   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8963              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
8964     return emitEHSjLjLongJmp(MI, BB);
8965   }
8966
8967   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8968
8969   // To "insert" these instructions we actually have to insert their
8970   // control-flow patterns.
8971   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8972   MachineFunction::iterator It = ++BB->getIterator();
8973
8974   MachineFunction *F = BB->getParent();
8975
8976   if (Subtarget.hasISEL() &&
8977       (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8978        MI.getOpcode() == PPC::SELECT_CC_I8 ||
8979        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
8980     SmallVector<MachineOperand, 2> Cond;
8981     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8982         MI.getOpcode() == PPC::SELECT_CC_I8)
8983       Cond.push_back(MI.getOperand(4));
8984     else
8985       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8986     Cond.push_back(MI.getOperand(1));
8987
8988     DebugLoc dl = MI.getDebugLoc();
8989     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
8990                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
8991   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
8992              MI.getOpcode() == PPC::SELECT_CC_I8 ||
8993              MI.getOpcode() == PPC::SELECT_CC_F4 ||
8994              MI.getOpcode() == PPC::SELECT_CC_F8 ||
8995              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
8996              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
8997              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
8998              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
8999              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9000              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9001              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9002              MI.getOpcode() == PPC::SELECT_I4 ||
9003              MI.getOpcode() == PPC::SELECT_I8 ||
9004              MI.getOpcode() == PPC::SELECT_F4 ||
9005              MI.getOpcode() == PPC::SELECT_F8 ||
9006              MI.getOpcode() == PPC::SELECT_QFRC ||
9007              MI.getOpcode() == PPC::SELECT_QSRC ||
9008              MI.getOpcode() == PPC::SELECT_QBRC ||
9009              MI.getOpcode() == PPC::SELECT_VRRC ||
9010              MI.getOpcode() == PPC::SELECT_VSFRC ||
9011              MI.getOpcode() == PPC::SELECT_VSSRC ||
9012              MI.getOpcode() == PPC::SELECT_VSRC) {
9013     // The incoming instruction knows the destination vreg to set, the
9014     // condition code register to branch on, the true/false values to
9015     // select between, and a branch opcode to use.
9016
9017     //  thisMBB:
9018     //  ...
9019     //   TrueVal = ...
9020     //   cmpTY ccX, r1, r2
9021     //   bCC copy1MBB
9022     //   fallthrough --> copy0MBB
9023     MachineBasicBlock *thisMBB = BB;
9024     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9025     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9026     DebugLoc dl = MI.getDebugLoc();
9027     F->insert(It, copy0MBB);
9028     F->insert(It, sinkMBB);
9029
9030     // Transfer the remainder of BB and its successor edges to sinkMBB.
9031     sinkMBB->splice(sinkMBB->begin(), BB,
9032                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9033     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9034
9035     // Next, add the true and fallthrough blocks as its successors.
9036     BB->addSuccessor(copy0MBB);
9037     BB->addSuccessor(sinkMBB);
9038
9039     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9040         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9041         MI.getOpcode() == PPC::SELECT_QFRC ||
9042         MI.getOpcode() == PPC::SELECT_QSRC ||
9043         MI.getOpcode() == PPC::SELECT_QBRC ||
9044         MI.getOpcode() == PPC::SELECT_VRRC ||
9045         MI.getOpcode() == PPC::SELECT_VSFRC ||
9046         MI.getOpcode() == PPC::SELECT_VSSRC ||
9047         MI.getOpcode() == PPC::SELECT_VSRC) {
9048       BuildMI(BB, dl, TII->get(PPC::BC))
9049           .addReg(MI.getOperand(1).getReg())
9050           .addMBB(sinkMBB);
9051     } else {
9052       unsigned SelectPred = MI.getOperand(4).getImm();
9053       BuildMI(BB, dl, TII->get(PPC::BCC))
9054           .addImm(SelectPred)
9055           .addReg(MI.getOperand(1).getReg())
9056           .addMBB(sinkMBB);
9057     }
9058
9059     //  copy0MBB:
9060     //   %FalseValue = ...
9061     //   # fallthrough to sinkMBB
9062     BB = copy0MBB;
9063
9064     // Update machine-CFG edges
9065     BB->addSuccessor(sinkMBB);
9066
9067     //  sinkMBB:
9068     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9069     //  ...
9070     BB = sinkMBB;
9071     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9072         .addReg(MI.getOperand(3).getReg())
9073         .addMBB(copy0MBB)
9074         .addReg(MI.getOperand(2).getReg())
9075         .addMBB(thisMBB);
9076   } else if (MI.getOpcode() == PPC::ReadTB) {
9077     // To read the 64-bit time-base register on a 32-bit target, we read the
9078     // two halves. Should the counter have wrapped while it was being read, we
9079     // need to try again.
9080     // ...
9081     // readLoop:
9082     // mfspr Rx,TBU # load from TBU
9083     // mfspr Ry,TB  # load from TB
9084     // mfspr Rz,TBU # load from TBU
9085     // cmpw crX,Rx,Rz # check if 'old'='new'
9086     // bne readLoop   # branch if they're not equal
9087     // ...
9088
9089     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9090     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9091     DebugLoc dl = MI.getDebugLoc();
9092     F->insert(It, readMBB);
9093     F->insert(It, sinkMBB);
9094
9095     // Transfer the remainder of BB and its successor edges to sinkMBB.
9096     sinkMBB->splice(sinkMBB->begin(), BB,
9097                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9098     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9099
9100     BB->addSuccessor(readMBB);
9101     BB = readMBB;
9102
9103     MachineRegisterInfo &RegInfo = F->getRegInfo();
9104     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9105     unsigned LoReg = MI.getOperand(0).getReg();
9106     unsigned HiReg = MI.getOperand(1).getReg();
9107
9108     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9109     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9110     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9111
9112     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9113
9114     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9115       .addReg(HiReg).addReg(ReadAgainReg);
9116     BuildMI(BB, dl, TII->get(PPC::BCC))
9117       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9118
9119     BB->addSuccessor(readMBB);
9120     BB->addSuccessor(sinkMBB);
9121   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9122     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9123   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9124     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9125   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9126     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9127   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9128     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9129
9130   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9131     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9132   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9133     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9134   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9135     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9136   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9137     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9138
9139   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9140     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9141   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9142     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9143   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9144     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9145   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9146     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9147
9148   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9149     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9150   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9151     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9152   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9153     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9154   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9155     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9156
9157   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9158     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9159   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9160     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9161   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9162     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9163   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9164     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9165
9166   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9167     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9168   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9169     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9170   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9171     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9172   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9173     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9174
9175   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9176     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9177   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9178     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9179   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9180     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9181   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9182     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9183
9184   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9185     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9186   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9187     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9188   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9189     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9190   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9191     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9192
9193   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9194     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9195   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9196     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9197   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9198     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9199   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9200     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9201
9202   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9203     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9204   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9205     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9206   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9207     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9208   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9209     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9210
9211   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9212     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9213   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9214     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9215   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9216     BB = EmitAtomicBinary(MI, BB, 4, 0);
9217   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9218     BB = EmitAtomicBinary(MI, BB, 8, 0);
9219
9220   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9221            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9222            (Subtarget.hasPartwordAtomics() &&
9223             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9224            (Subtarget.hasPartwordAtomics() &&
9225             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9226     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9227
9228     auto LoadMnemonic = PPC::LDARX;
9229     auto StoreMnemonic = PPC::STDCX;
9230     switch (MI.getOpcode()) {
9231     default:
9232       llvm_unreachable("Compare and swap of unknown size");
9233     case PPC::ATOMIC_CMP_SWAP_I8:
9234       LoadMnemonic = PPC::LBARX;
9235       StoreMnemonic = PPC::STBCX;
9236       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9237       break;
9238     case PPC::ATOMIC_CMP_SWAP_I16:
9239       LoadMnemonic = PPC::LHARX;
9240       StoreMnemonic = PPC::STHCX;
9241       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9242       break;
9243     case PPC::ATOMIC_CMP_SWAP_I32:
9244       LoadMnemonic = PPC::LWARX;
9245       StoreMnemonic = PPC::STWCX;
9246       break;
9247     case PPC::ATOMIC_CMP_SWAP_I64:
9248       LoadMnemonic = PPC::LDARX;
9249       StoreMnemonic = PPC::STDCX;
9250       break;
9251     }
9252     unsigned dest = MI.getOperand(0).getReg();
9253     unsigned ptrA = MI.getOperand(1).getReg();
9254     unsigned ptrB = MI.getOperand(2).getReg();
9255     unsigned oldval = MI.getOperand(3).getReg();
9256     unsigned newval = MI.getOperand(4).getReg();
9257     DebugLoc dl = MI.getDebugLoc();
9258
9259     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9260     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9261     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9262     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9263     F->insert(It, loop1MBB);
9264     F->insert(It, loop2MBB);
9265     F->insert(It, midMBB);
9266     F->insert(It, exitMBB);
9267     exitMBB->splice(exitMBB->begin(), BB,
9268                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9269     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9270
9271     //  thisMBB:
9272     //   ...
9273     //   fallthrough --> loopMBB
9274     BB->addSuccessor(loop1MBB);
9275
9276     // loop1MBB:
9277     //   l[bhwd]arx dest, ptr
9278     //   cmp[wd] dest, oldval
9279     //   bne- midMBB
9280     // loop2MBB:
9281     //   st[bhwd]cx. newval, ptr
9282     //   bne- loopMBB
9283     //   b exitBB
9284     // midMBB:
9285     //   st[bhwd]cx. dest, ptr
9286     // exitBB:
9287     BB = loop1MBB;
9288     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9289       .addReg(ptrA).addReg(ptrB);
9290     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9291       .addReg(oldval).addReg(dest);
9292     BuildMI(BB, dl, TII->get(PPC::BCC))
9293       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9294     BB->addSuccessor(loop2MBB);
9295     BB->addSuccessor(midMBB);
9296
9297     BB = loop2MBB;
9298     BuildMI(BB, dl, TII->get(StoreMnemonic))
9299       .addReg(newval).addReg(ptrA).addReg(ptrB);
9300     BuildMI(BB, dl, TII->get(PPC::BCC))
9301       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9302     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9303     BB->addSuccessor(loop1MBB);
9304     BB->addSuccessor(exitMBB);
9305
9306     BB = midMBB;
9307     BuildMI(BB, dl, TII->get(StoreMnemonic))
9308       .addReg(dest).addReg(ptrA).addReg(ptrB);
9309     BB->addSuccessor(exitMBB);
9310
9311     //  exitMBB:
9312     //   ...
9313     BB = exitMBB;
9314   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9315              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9316     // We must use 64-bit registers for addresses when targeting 64-bit,
9317     // since we're actually doing arithmetic on them.  Other registers
9318     // can be 32-bit.
9319     bool is64bit = Subtarget.isPPC64();
9320     bool isLittleEndian = Subtarget.isLittleEndian();
9321     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9322
9323     unsigned dest = MI.getOperand(0).getReg();
9324     unsigned ptrA = MI.getOperand(1).getReg();
9325     unsigned ptrB = MI.getOperand(2).getReg();
9326     unsigned oldval = MI.getOperand(3).getReg();
9327     unsigned newval = MI.getOperand(4).getReg();
9328     DebugLoc dl = MI.getDebugLoc();
9329
9330     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9331     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9332     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9333     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9334     F->insert(It, loop1MBB);
9335     F->insert(It, loop2MBB);
9336     F->insert(It, midMBB);
9337     F->insert(It, exitMBB);
9338     exitMBB->splice(exitMBB->begin(), BB,
9339                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9340     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9341
9342     MachineRegisterInfo &RegInfo = F->getRegInfo();
9343     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9344                                             : &PPC::GPRCRegClass;
9345     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9346     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9347     unsigned ShiftReg =
9348       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9349     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9350     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9351     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9352     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9353     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9354     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9355     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9356     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9357     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9358     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9359     unsigned Ptr1Reg;
9360     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9361     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9362     //  thisMBB:
9363     //   ...
9364     //   fallthrough --> loopMBB
9365     BB->addSuccessor(loop1MBB);
9366
9367     // The 4-byte load must be aligned, while a char or short may be
9368     // anywhere in the word.  Hence all this nasty bookkeeping code.
9369     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9370     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9371     //   xori shift, shift1, 24 [16]
9372     //   rlwinm ptr, ptr1, 0, 0, 29
9373     //   slw newval2, newval, shift
9374     //   slw oldval2, oldval,shift
9375     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9376     //   slw mask, mask2, shift
9377     //   and newval3, newval2, mask
9378     //   and oldval3, oldval2, mask
9379     // loop1MBB:
9380     //   lwarx tmpDest, ptr
9381     //   and tmp, tmpDest, mask
9382     //   cmpw tmp, oldval3
9383     //   bne- midMBB
9384     // loop2MBB:
9385     //   andc tmp2, tmpDest, mask
9386     //   or tmp4, tmp2, newval3
9387     //   stwcx. tmp4, ptr
9388     //   bne- loop1MBB
9389     //   b exitBB
9390     // midMBB:
9391     //   stwcx. tmpDest, ptr
9392     // exitBB:
9393     //   srw dest, tmpDest, shift
9394     if (ptrA != ZeroReg) {
9395       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9396       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9397         .addReg(ptrA).addReg(ptrB);
9398     } else {
9399       Ptr1Reg = ptrB;
9400     }
9401     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9402         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9403     if (!isLittleEndian)
9404       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9405           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9406     if (is64bit)
9407       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9408         .addReg(Ptr1Reg).addImm(0).addImm(61);
9409     else
9410       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9411         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9412     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9413         .addReg(newval).addReg(ShiftReg);
9414     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9415         .addReg(oldval).addReg(ShiftReg);
9416     if (is8bit)
9417       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9418     else {
9419       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9420       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9421         .addReg(Mask3Reg).addImm(65535);
9422     }
9423     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9424         .addReg(Mask2Reg).addReg(ShiftReg);
9425     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9426         .addReg(NewVal2Reg).addReg(MaskReg);
9427     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9428         .addReg(OldVal2Reg).addReg(MaskReg);
9429
9430     BB = loop1MBB;
9431     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9432         .addReg(ZeroReg).addReg(PtrReg);
9433     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9434         .addReg(TmpDestReg).addReg(MaskReg);
9435     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9436         .addReg(TmpReg).addReg(OldVal3Reg);
9437     BuildMI(BB, dl, TII->get(PPC::BCC))
9438         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9439     BB->addSuccessor(loop2MBB);
9440     BB->addSuccessor(midMBB);
9441
9442     BB = loop2MBB;
9443     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9444         .addReg(TmpDestReg).addReg(MaskReg);
9445     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9446         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9447     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9448         .addReg(ZeroReg).addReg(PtrReg);
9449     BuildMI(BB, dl, TII->get(PPC::BCC))
9450       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9451     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9452     BB->addSuccessor(loop1MBB);
9453     BB->addSuccessor(exitMBB);
9454
9455     BB = midMBB;
9456     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9457       .addReg(ZeroReg).addReg(PtrReg);
9458     BB->addSuccessor(exitMBB);
9459
9460     //  exitMBB:
9461     //   ...
9462     BB = exitMBB;
9463     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9464       .addReg(ShiftReg);
9465   } else if (MI.getOpcode() == PPC::FADDrtz) {
9466     // This pseudo performs an FADD with rounding mode temporarily forced
9467     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9468     // is not modeled at the SelectionDAG level.
9469     unsigned Dest = MI.getOperand(0).getReg();
9470     unsigned Src1 = MI.getOperand(1).getReg();
9471     unsigned Src2 = MI.getOperand(2).getReg();
9472     DebugLoc dl = MI.getDebugLoc();
9473
9474     MachineRegisterInfo &RegInfo = F->getRegInfo();
9475     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9476
9477     // Save FPSCR value.
9478     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9479
9480     // Set rounding mode to round-to-zero.
9481     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9482     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9483
9484     // Perform addition.
9485     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9486
9487     // Restore FPSCR value.
9488     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9489   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9490              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9491              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9492              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9493     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9494                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9495                           ? PPC::ANDIo8
9496                           : PPC::ANDIo;
9497     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9498                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9499
9500     MachineRegisterInfo &RegInfo = F->getRegInfo();
9501     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9502                                                   &PPC::GPRCRegClass :
9503                                                   &PPC::G8RCRegClass);
9504
9505     DebugLoc dl = MI.getDebugLoc();
9506     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9507         .addReg(MI.getOperand(1).getReg())
9508         .addImm(1);
9509     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9510             MI.getOperand(0).getReg())
9511         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9512   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9513     DebugLoc Dl = MI.getDebugLoc();
9514     MachineRegisterInfo &RegInfo = F->getRegInfo();
9515     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9516     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9517     return BB;
9518   } else {
9519     llvm_unreachable("Unexpected instr type to insert");
9520   }
9521
9522   MI.eraseFromParent(); // The pseudo instruction is gone now.
9523   return BB;
9524 }
9525
9526 //===----------------------------------------------------------------------===//
9527 // Target Optimization Hooks
9528 //===----------------------------------------------------------------------===//
9529
9530 static std::string getRecipOp(const char *Base, EVT VT) {
9531   std::string RecipOp(Base);
9532   if (VT.getScalarType() == MVT::f64)
9533     RecipOp += "d";
9534   else
9535     RecipOp += "f";
9536
9537   if (VT.isVector())
9538     RecipOp = "vec-" + RecipOp;
9539
9540   return RecipOp;
9541 }
9542
9543 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9544                                             DAGCombinerInfo &DCI,
9545                                             unsigned &RefinementSteps,
9546                                             bool &UseOneConstNR) const {
9547   EVT VT = Operand.getValueType();
9548   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9549       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9550       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9551       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9552       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9553       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9554     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9555     std::string RecipOp = getRecipOp("sqrt", VT);
9556     if (!Recips.isEnabled(RecipOp))
9557       return SDValue();
9558
9559     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9560     UseOneConstNR = true;
9561     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9562   }
9563   return SDValue();
9564 }
9565
9566 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9567                                             DAGCombinerInfo &DCI,
9568                                             unsigned &RefinementSteps) const {
9569   EVT VT = Operand.getValueType();
9570   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9571       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9572       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9573       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9574       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9575       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9576     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9577     std::string RecipOp = getRecipOp("div", VT);
9578     if (!Recips.isEnabled(RecipOp))
9579       return SDValue();
9580
9581     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9582     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9583   }
9584   return SDValue();
9585 }
9586
9587 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9588   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9589   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9590   // enabled for division), this functionality is redundant with the default
9591   // combiner logic (once the division -> reciprocal/multiply transformation
9592   // has taken place). As a result, this matters more for older cores than for
9593   // newer ones.
9594
9595   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9596   // reciprocal if there are two or more FDIVs (for embedded cores with only
9597   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9598   switch (Subtarget.getDarwinDirective()) {
9599   default:
9600     return 3;
9601   case PPC::DIR_440:
9602   case PPC::DIR_A2:
9603   case PPC::DIR_E500mc:
9604   case PPC::DIR_E5500:
9605     return 2;
9606   }
9607 }
9608
9609 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9610 // collapsed, and so we need to look through chains of them.
9611 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9612                                      int64_t& Offset, SelectionDAG &DAG) {
9613   if (DAG.isBaseWithConstantOffset(Loc)) {
9614     Base = Loc.getOperand(0);
9615     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9616
9617     // The base might itself be a base plus an offset, and if so, accumulate
9618     // that as well.
9619     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9620   }
9621 }
9622
9623 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9624                             unsigned Bytes, int Dist,
9625                             SelectionDAG &DAG) {
9626   if (VT.getSizeInBits() / 8 != Bytes)
9627     return false;
9628
9629   SDValue BaseLoc = Base->getBasePtr();
9630   if (Loc.getOpcode() == ISD::FrameIndex) {
9631     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9632       return false;
9633     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9634     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9635     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9636     int FS  = MFI.getObjectSize(FI);
9637     int BFS = MFI.getObjectSize(BFI);
9638     if (FS != BFS || FS != (int)Bytes) return false;
9639     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
9640   }
9641
9642   SDValue Base1 = Loc, Base2 = BaseLoc;
9643   int64_t Offset1 = 0, Offset2 = 0;
9644   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9645   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9646   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9647     return true;
9648
9649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9650   const GlobalValue *GV1 = nullptr;
9651   const GlobalValue *GV2 = nullptr;
9652   Offset1 = 0;
9653   Offset2 = 0;
9654   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9655   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9656   if (isGA1 && isGA2 && GV1 == GV2)
9657     return Offset1 == (Offset2 + Dist*Bytes);
9658   return false;
9659 }
9660
9661 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9662 // not enforce equality of the chain operands.
9663 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9664                             unsigned Bytes, int Dist,
9665                             SelectionDAG &DAG) {
9666   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9667     EVT VT = LS->getMemoryVT();
9668     SDValue Loc = LS->getBasePtr();
9669     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9670   }
9671
9672   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9673     EVT VT;
9674     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9675     default: return false;
9676     case Intrinsic::ppc_qpx_qvlfd:
9677     case Intrinsic::ppc_qpx_qvlfda:
9678       VT = MVT::v4f64;
9679       break;
9680     case Intrinsic::ppc_qpx_qvlfs:
9681     case Intrinsic::ppc_qpx_qvlfsa:
9682       VT = MVT::v4f32;
9683       break;
9684     case Intrinsic::ppc_qpx_qvlfcd:
9685     case Intrinsic::ppc_qpx_qvlfcda:
9686       VT = MVT::v2f64;
9687       break;
9688     case Intrinsic::ppc_qpx_qvlfcs:
9689     case Intrinsic::ppc_qpx_qvlfcsa:
9690       VT = MVT::v2f32;
9691       break;
9692     case Intrinsic::ppc_qpx_qvlfiwa:
9693     case Intrinsic::ppc_qpx_qvlfiwz:
9694     case Intrinsic::ppc_altivec_lvx:
9695     case Intrinsic::ppc_altivec_lvxl:
9696     case Intrinsic::ppc_vsx_lxvw4x:
9697       VT = MVT::v4i32;
9698       break;
9699     case Intrinsic::ppc_vsx_lxvd2x:
9700       VT = MVT::v2f64;
9701       break;
9702     case Intrinsic::ppc_altivec_lvebx:
9703       VT = MVT::i8;
9704       break;
9705     case Intrinsic::ppc_altivec_lvehx:
9706       VT = MVT::i16;
9707       break;
9708     case Intrinsic::ppc_altivec_lvewx:
9709       VT = MVT::i32;
9710       break;
9711     }
9712
9713     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9714   }
9715
9716   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9717     EVT VT;
9718     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9719     default: return false;
9720     case Intrinsic::ppc_qpx_qvstfd:
9721     case Intrinsic::ppc_qpx_qvstfda:
9722       VT = MVT::v4f64;
9723       break;
9724     case Intrinsic::ppc_qpx_qvstfs:
9725     case Intrinsic::ppc_qpx_qvstfsa:
9726       VT = MVT::v4f32;
9727       break;
9728     case Intrinsic::ppc_qpx_qvstfcd:
9729     case Intrinsic::ppc_qpx_qvstfcda:
9730       VT = MVT::v2f64;
9731       break;
9732     case Intrinsic::ppc_qpx_qvstfcs:
9733     case Intrinsic::ppc_qpx_qvstfcsa:
9734       VT = MVT::v2f32;
9735       break;
9736     case Intrinsic::ppc_qpx_qvstfiw:
9737     case Intrinsic::ppc_qpx_qvstfiwa:
9738     case Intrinsic::ppc_altivec_stvx:
9739     case Intrinsic::ppc_altivec_stvxl:
9740     case Intrinsic::ppc_vsx_stxvw4x:
9741       VT = MVT::v4i32;
9742       break;
9743     case Intrinsic::ppc_vsx_stxvd2x:
9744       VT = MVT::v2f64;
9745       break;
9746     case Intrinsic::ppc_altivec_stvebx:
9747       VT = MVT::i8;
9748       break;
9749     case Intrinsic::ppc_altivec_stvehx:
9750       VT = MVT::i16;
9751       break;
9752     case Intrinsic::ppc_altivec_stvewx:
9753       VT = MVT::i32;
9754       break;
9755     }
9756
9757     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9758   }
9759
9760   return false;
9761 }
9762
9763 // Return true is there is a nearyby consecutive load to the one provided
9764 // (regardless of alignment). We search up and down the chain, looking though
9765 // token factors and other loads (but nothing else). As a result, a true result
9766 // indicates that it is safe to create a new consecutive load adjacent to the
9767 // load provided.
9768 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9769   SDValue Chain = LD->getChain();
9770   EVT VT = LD->getMemoryVT();
9771
9772   SmallSet<SDNode *, 16> LoadRoots;
9773   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9774   SmallSet<SDNode *, 16> Visited;
9775
9776   // First, search up the chain, branching to follow all token-factor operands.
9777   // If we find a consecutive load, then we're done, otherwise, record all
9778   // nodes just above the top-level loads and token factors.
9779   while (!Queue.empty()) {
9780     SDNode *ChainNext = Queue.pop_back_val();
9781     if (!Visited.insert(ChainNext).second)
9782       continue;
9783
9784     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9785       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9786         return true;
9787
9788       if (!Visited.count(ChainLD->getChain().getNode()))
9789         Queue.push_back(ChainLD->getChain().getNode());
9790     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9791       for (const SDUse &O : ChainNext->ops())
9792         if (!Visited.count(O.getNode()))
9793           Queue.push_back(O.getNode());
9794     } else
9795       LoadRoots.insert(ChainNext);
9796   }
9797
9798   // Second, search down the chain, starting from the top-level nodes recorded
9799   // in the first phase. These top-level nodes are the nodes just above all
9800   // loads and token factors. Starting with their uses, recursively look though
9801   // all loads (just the chain uses) and token factors to find a consecutive
9802   // load.
9803   Visited.clear();
9804   Queue.clear();
9805
9806   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9807        IE = LoadRoots.end(); I != IE; ++I) {
9808     Queue.push_back(*I);
9809
9810     while (!Queue.empty()) {
9811       SDNode *LoadRoot = Queue.pop_back_val();
9812       if (!Visited.insert(LoadRoot).second)
9813         continue;
9814
9815       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9816         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9817           return true;
9818
9819       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9820            UE = LoadRoot->use_end(); UI != UE; ++UI)
9821         if (((isa<MemSDNode>(*UI) &&
9822             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9823             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9824           Queue.push_back(*UI);
9825     }
9826   }
9827
9828   return false;
9829 }
9830
9831 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9832                                                   DAGCombinerInfo &DCI) const {
9833   SelectionDAG &DAG = DCI.DAG;
9834   SDLoc dl(N);
9835
9836   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9837   // If we're tracking CR bits, we need to be careful that we don't have:
9838   //   trunc(binary-ops(zext(x), zext(y)))
9839   // or
9840   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9841   // such that we're unnecessarily moving things into GPRs when it would be
9842   // better to keep them in CR bits.
9843
9844   // Note that trunc here can be an actual i1 trunc, or can be the effective
9845   // truncation that comes from a setcc or select_cc.
9846   if (N->getOpcode() == ISD::TRUNCATE &&
9847       N->getValueType(0) != MVT::i1)
9848     return SDValue();
9849
9850   if (N->getOperand(0).getValueType() != MVT::i32 &&
9851       N->getOperand(0).getValueType() != MVT::i64)
9852     return SDValue();
9853
9854   if (N->getOpcode() == ISD::SETCC ||
9855       N->getOpcode() == ISD::SELECT_CC) {
9856     // If we're looking at a comparison, then we need to make sure that the
9857     // high bits (all except for the first) don't matter the result.
9858     ISD::CondCode CC =
9859       cast<CondCodeSDNode>(N->getOperand(
9860         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9861     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9862
9863     if (ISD::isSignedIntSetCC(CC)) {
9864       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9865           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9866         return SDValue();
9867     } else if (ISD::isUnsignedIntSetCC(CC)) {
9868       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9869                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9870           !DAG.MaskedValueIsZero(N->getOperand(1),
9871                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9872         return SDValue();
9873     } else {
9874       // This is neither a signed nor an unsigned comparison, just make sure
9875       // that the high bits are equal.
9876       APInt Op1Zero, Op1One;
9877       APInt Op2Zero, Op2One;
9878       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9879       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9880
9881       // We don't really care about what is known about the first bit (if
9882       // anything), so clear it in all masks prior to comparing them.
9883       Op1Zero.clearBit(0); Op1One.clearBit(0);
9884       Op2Zero.clearBit(0); Op2One.clearBit(0);
9885
9886       if (Op1Zero != Op2Zero || Op1One != Op2One)
9887         return SDValue();
9888     }
9889   }
9890
9891   // We now know that the higher-order bits are irrelevant, we just need to
9892   // make sure that all of the intermediate operations are bit operations, and
9893   // all inputs are extensions.
9894   if (N->getOperand(0).getOpcode() != ISD::AND &&
9895       N->getOperand(0).getOpcode() != ISD::OR  &&
9896       N->getOperand(0).getOpcode() != ISD::XOR &&
9897       N->getOperand(0).getOpcode() != ISD::SELECT &&
9898       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9899       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9900       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9901       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9902       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9903     return SDValue();
9904
9905   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9906       N->getOperand(1).getOpcode() != ISD::AND &&
9907       N->getOperand(1).getOpcode() != ISD::OR  &&
9908       N->getOperand(1).getOpcode() != ISD::XOR &&
9909       N->getOperand(1).getOpcode() != ISD::SELECT &&
9910       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9911       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9912       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9913       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9914       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9915     return SDValue();
9916
9917   SmallVector<SDValue, 4> Inputs;
9918   SmallVector<SDValue, 8> BinOps, PromOps;
9919   SmallPtrSet<SDNode *, 16> Visited;
9920
9921   for (unsigned i = 0; i < 2; ++i) {
9922     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9923           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9924           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9925           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9926         isa<ConstantSDNode>(N->getOperand(i)))
9927       Inputs.push_back(N->getOperand(i));
9928     else
9929       BinOps.push_back(N->getOperand(i));
9930
9931     if (N->getOpcode() == ISD::TRUNCATE)
9932       break;
9933   }
9934
9935   // Visit all inputs, collect all binary operations (and, or, xor and
9936   // select) that are all fed by extensions.
9937   while (!BinOps.empty()) {
9938     SDValue BinOp = BinOps.back();
9939     BinOps.pop_back();
9940
9941     if (!Visited.insert(BinOp.getNode()).second)
9942       continue;
9943
9944     PromOps.push_back(BinOp);
9945
9946     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9947       // The condition of the select is not promoted.
9948       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9949         continue;
9950       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9951         continue;
9952
9953       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9954             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9955             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9956            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9957           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9958         Inputs.push_back(BinOp.getOperand(i));
9959       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9960                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9961                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9962                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9963                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9964                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9965                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9966                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9967                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9968         BinOps.push_back(BinOp.getOperand(i));
9969       } else {
9970         // We have an input that is not an extension or another binary
9971         // operation; we'll abort this transformation.
9972         return SDValue();
9973       }
9974     }
9975   }
9976
9977   // Make sure that this is a self-contained cluster of operations (which
9978   // is not quite the same thing as saying that everything has only one
9979   // use).
9980   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9981     if (isa<ConstantSDNode>(Inputs[i]))
9982       continue;
9983
9984     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9985                               UE = Inputs[i].getNode()->use_end();
9986          UI != UE; ++UI) {
9987       SDNode *User = *UI;
9988       if (User != N && !Visited.count(User))
9989         return SDValue();
9990
9991       // Make sure that we're not going to promote the non-output-value
9992       // operand(s) or SELECT or SELECT_CC.
9993       // FIXME: Although we could sometimes handle this, and it does occur in
9994       // practice that one of the condition inputs to the select is also one of
9995       // the outputs, we currently can't deal with this.
9996       if (User->getOpcode() == ISD::SELECT) {
9997         if (User->getOperand(0) == Inputs[i])
9998           return SDValue();
9999       } else if (User->getOpcode() == ISD::SELECT_CC) {
10000         if (User->getOperand(0) == Inputs[i] ||
10001             User->getOperand(1) == Inputs[i])
10002           return SDValue();
10003       }
10004     }
10005   }
10006
10007   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10008     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10009                               UE = PromOps[i].getNode()->use_end();
10010          UI != UE; ++UI) {
10011       SDNode *User = *UI;
10012       if (User != N && !Visited.count(User))
10013         return SDValue();
10014
10015       // Make sure that we're not going to promote the non-output-value
10016       // operand(s) or SELECT or SELECT_CC.
10017       // FIXME: Although we could sometimes handle this, and it does occur in
10018       // practice that one of the condition inputs to the select is also one of
10019       // the outputs, we currently can't deal with this.
10020       if (User->getOpcode() == ISD::SELECT) {
10021         if (User->getOperand(0) == PromOps[i])
10022           return SDValue();
10023       } else if (User->getOpcode() == ISD::SELECT_CC) {
10024         if (User->getOperand(0) == PromOps[i] ||
10025             User->getOperand(1) == PromOps[i])
10026           return SDValue();
10027       }
10028     }
10029   }
10030
10031   // Replace all inputs with the extension operand.
10032   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10033     // Constants may have users outside the cluster of to-be-promoted nodes,
10034     // and so we need to replace those as we do the promotions.
10035     if (isa<ConstantSDNode>(Inputs[i]))
10036       continue;
10037     else
10038       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10039   }
10040
10041   std::list<HandleSDNode> PromOpHandles;
10042   for (auto &PromOp : PromOps)
10043     PromOpHandles.emplace_back(PromOp);
10044
10045   // Replace all operations (these are all the same, but have a different
10046   // (i1) return type). DAG.getNode will validate that the types of
10047   // a binary operator match, so go through the list in reverse so that
10048   // we've likely promoted both operands first. Any intermediate truncations or
10049   // extensions disappear.
10050   while (!PromOpHandles.empty()) {
10051     SDValue PromOp = PromOpHandles.back().getValue();
10052     PromOpHandles.pop_back();
10053
10054     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10055         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10056         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10057         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10058       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10059           PromOp.getOperand(0).getValueType() != MVT::i1) {
10060         // The operand is not yet ready (see comment below).
10061         PromOpHandles.emplace_front(PromOp);
10062         continue;
10063       }
10064
10065       SDValue RepValue = PromOp.getOperand(0);
10066       if (isa<ConstantSDNode>(RepValue))
10067         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10068
10069       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10070       continue;
10071     }
10072
10073     unsigned C;
10074     switch (PromOp.getOpcode()) {
10075     default:             C = 0; break;
10076     case ISD::SELECT:    C = 1; break;
10077     case ISD::SELECT_CC: C = 2; break;
10078     }
10079
10080     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10081          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10082         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10083          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10084       // The to-be-promoted operands of this node have not yet been
10085       // promoted (this should be rare because we're going through the
10086       // list backward, but if one of the operands has several users in
10087       // this cluster of to-be-promoted nodes, it is possible).
10088       PromOpHandles.emplace_front(PromOp);
10089       continue;
10090     }
10091
10092     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10093                                 PromOp.getNode()->op_end());
10094
10095     // If there are any constant inputs, make sure they're replaced now.
10096     for (unsigned i = 0; i < 2; ++i)
10097       if (isa<ConstantSDNode>(Ops[C+i]))
10098         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10099
10100     DAG.ReplaceAllUsesOfValueWith(PromOp,
10101       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10102   }
10103
10104   // Now we're left with the initial truncation itself.
10105   if (N->getOpcode() == ISD::TRUNCATE)
10106     return N->getOperand(0);
10107
10108   // Otherwise, this is a comparison. The operands to be compared have just
10109   // changed type (to i1), but everything else is the same.
10110   return SDValue(N, 0);
10111 }
10112
10113 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10114                                                   DAGCombinerInfo &DCI) const {
10115   SelectionDAG &DAG = DCI.DAG;
10116   SDLoc dl(N);
10117
10118   // If we're tracking CR bits, we need to be careful that we don't have:
10119   //   zext(binary-ops(trunc(x), trunc(y)))
10120   // or
10121   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10122   // such that we're unnecessarily moving things into CR bits that can more
10123   // efficiently stay in GPRs. Note that if we're not certain that the high
10124   // bits are set as required by the final extension, we still may need to do
10125   // some masking to get the proper behavior.
10126
10127   // This same functionality is important on PPC64 when dealing with
10128   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10129   // the return values of functions. Because it is so similar, it is handled
10130   // here as well.
10131
10132   if (N->getValueType(0) != MVT::i32 &&
10133       N->getValueType(0) != MVT::i64)
10134     return SDValue();
10135
10136   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10137         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10138     return SDValue();
10139
10140   if (N->getOperand(0).getOpcode() != ISD::AND &&
10141       N->getOperand(0).getOpcode() != ISD::OR  &&
10142       N->getOperand(0).getOpcode() != ISD::XOR &&
10143       N->getOperand(0).getOpcode() != ISD::SELECT &&
10144       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10145     return SDValue();
10146
10147   SmallVector<SDValue, 4> Inputs;
10148   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10149   SmallPtrSet<SDNode *, 16> Visited;
10150
10151   // Visit all inputs, collect all binary operations (and, or, xor and
10152   // select) that are all fed by truncations.
10153   while (!BinOps.empty()) {
10154     SDValue BinOp = BinOps.back();
10155     BinOps.pop_back();
10156
10157     if (!Visited.insert(BinOp.getNode()).second)
10158       continue;
10159
10160     PromOps.push_back(BinOp);
10161
10162     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10163       // The condition of the select is not promoted.
10164       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10165         continue;
10166       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10167         continue;
10168
10169       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10170           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10171         Inputs.push_back(BinOp.getOperand(i));
10172       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10173                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10174                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10175                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10176                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10177         BinOps.push_back(BinOp.getOperand(i));
10178       } else {
10179         // We have an input that is not a truncation or another binary
10180         // operation; we'll abort this transformation.
10181         return SDValue();
10182       }
10183     }
10184   }
10185
10186   // The operands of a select that must be truncated when the select is
10187   // promoted because the operand is actually part of the to-be-promoted set.
10188   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10189
10190   // Make sure that this is a self-contained cluster of operations (which
10191   // is not quite the same thing as saying that everything has only one
10192   // use).
10193   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10194     if (isa<ConstantSDNode>(Inputs[i]))
10195       continue;
10196
10197     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10198                               UE = Inputs[i].getNode()->use_end();
10199          UI != UE; ++UI) {
10200       SDNode *User = *UI;
10201       if (User != N && !Visited.count(User))
10202         return SDValue();
10203
10204       // If we're going to promote the non-output-value operand(s) or SELECT or
10205       // SELECT_CC, record them for truncation.
10206       if (User->getOpcode() == ISD::SELECT) {
10207         if (User->getOperand(0) == Inputs[i])
10208           SelectTruncOp[0].insert(std::make_pair(User,
10209                                     User->getOperand(0).getValueType()));
10210       } else if (User->getOpcode() == ISD::SELECT_CC) {
10211         if (User->getOperand(0) == Inputs[i])
10212           SelectTruncOp[0].insert(std::make_pair(User,
10213                                     User->getOperand(0).getValueType()));
10214         if (User->getOperand(1) == Inputs[i])
10215           SelectTruncOp[1].insert(std::make_pair(User,
10216                                     User->getOperand(1).getValueType()));
10217       }
10218     }
10219   }
10220
10221   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10222     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10223                               UE = PromOps[i].getNode()->use_end();
10224          UI != UE; ++UI) {
10225       SDNode *User = *UI;
10226       if (User != N && !Visited.count(User))
10227         return SDValue();
10228
10229       // If we're going to promote the non-output-value operand(s) or SELECT or
10230       // SELECT_CC, record them for truncation.
10231       if (User->getOpcode() == ISD::SELECT) {
10232         if (User->getOperand(0) == PromOps[i])
10233           SelectTruncOp[0].insert(std::make_pair(User,
10234                                     User->getOperand(0).getValueType()));
10235       } else if (User->getOpcode() == ISD::SELECT_CC) {
10236         if (User->getOperand(0) == PromOps[i])
10237           SelectTruncOp[0].insert(std::make_pair(User,
10238                                     User->getOperand(0).getValueType()));
10239         if (User->getOperand(1) == PromOps[i])
10240           SelectTruncOp[1].insert(std::make_pair(User,
10241                                     User->getOperand(1).getValueType()));
10242       }
10243     }
10244   }
10245
10246   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10247   bool ReallyNeedsExt = false;
10248   if (N->getOpcode() != ISD::ANY_EXTEND) {
10249     // If all of the inputs are not already sign/zero extended, then
10250     // we'll still need to do that at the end.
10251     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10252       if (isa<ConstantSDNode>(Inputs[i]))
10253         continue;
10254
10255       unsigned OpBits =
10256         Inputs[i].getOperand(0).getValueSizeInBits();
10257       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10258
10259       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10260            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10261                                   APInt::getHighBitsSet(OpBits,
10262                                                         OpBits-PromBits))) ||
10263           (N->getOpcode() == ISD::SIGN_EXTEND &&
10264            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10265              (OpBits-(PromBits-1)))) {
10266         ReallyNeedsExt = true;
10267         break;
10268       }
10269     }
10270   }
10271
10272   // Replace all inputs, either with the truncation operand, or a
10273   // truncation or extension to the final output type.
10274   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10275     // Constant inputs need to be replaced with the to-be-promoted nodes that
10276     // use them because they might have users outside of the cluster of
10277     // promoted nodes.
10278     if (isa<ConstantSDNode>(Inputs[i]))
10279       continue;
10280
10281     SDValue InSrc = Inputs[i].getOperand(0);
10282     if (Inputs[i].getValueType() == N->getValueType(0))
10283       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10284     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10285       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10286         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10287     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10288       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10289         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10290     else
10291       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10292         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10293   }
10294
10295   std::list<HandleSDNode> PromOpHandles;
10296   for (auto &PromOp : PromOps)
10297     PromOpHandles.emplace_back(PromOp);
10298
10299   // Replace all operations (these are all the same, but have a different
10300   // (promoted) return type). DAG.getNode will validate that the types of
10301   // a binary operator match, so go through the list in reverse so that
10302   // we've likely promoted both operands first.
10303   while (!PromOpHandles.empty()) {
10304     SDValue PromOp = PromOpHandles.back().getValue();
10305     PromOpHandles.pop_back();
10306
10307     unsigned C;
10308     switch (PromOp.getOpcode()) {
10309     default:             C = 0; break;
10310     case ISD::SELECT:    C = 1; break;
10311     case ISD::SELECT_CC: C = 2; break;
10312     }
10313
10314     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10315          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10316         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10317          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10318       // The to-be-promoted operands of this node have not yet been
10319       // promoted (this should be rare because we're going through the
10320       // list backward, but if one of the operands has several users in
10321       // this cluster of to-be-promoted nodes, it is possible).
10322       PromOpHandles.emplace_front(PromOp);
10323       continue;
10324     }
10325
10326     // For SELECT and SELECT_CC nodes, we do a similar check for any
10327     // to-be-promoted comparison inputs.
10328     if (PromOp.getOpcode() == ISD::SELECT ||
10329         PromOp.getOpcode() == ISD::SELECT_CC) {
10330       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10331            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10332           (SelectTruncOp[1].count(PromOp.getNode()) &&
10333            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10334         PromOpHandles.emplace_front(PromOp);
10335         continue;
10336       }
10337     }
10338
10339     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10340                                 PromOp.getNode()->op_end());
10341
10342     // If this node has constant inputs, then they'll need to be promoted here.
10343     for (unsigned i = 0; i < 2; ++i) {
10344       if (!isa<ConstantSDNode>(Ops[C+i]))
10345         continue;
10346       if (Ops[C+i].getValueType() == N->getValueType(0))
10347         continue;
10348
10349       if (N->getOpcode() == ISD::SIGN_EXTEND)
10350         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10351       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10352         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10353       else
10354         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10355     }
10356
10357     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10358     // truncate them again to the original value type.
10359     if (PromOp.getOpcode() == ISD::SELECT ||
10360         PromOp.getOpcode() == ISD::SELECT_CC) {
10361       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10362       if (SI0 != SelectTruncOp[0].end())
10363         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10364       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10365       if (SI1 != SelectTruncOp[1].end())
10366         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10367     }
10368
10369     DAG.ReplaceAllUsesOfValueWith(PromOp,
10370       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10371   }
10372
10373   // Now we're left with the initial extension itself.
10374   if (!ReallyNeedsExt)
10375     return N->getOperand(0);
10376
10377   // To zero extend, just mask off everything except for the first bit (in the
10378   // i1 case).
10379   if (N->getOpcode() == ISD::ZERO_EXTEND)
10380     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10381                        DAG.getConstant(APInt::getLowBitsSet(
10382                                          N->getValueSizeInBits(0), PromBits),
10383                                        dl, N->getValueType(0)));
10384
10385   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10386          "Invalid extension type");
10387   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10388   SDValue ShiftCst =
10389       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10390   return DAG.getNode(
10391       ISD::SRA, dl, N->getValueType(0),
10392       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10393       ShiftCst);
10394 }
10395
10396 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
10397                                                  DAGCombinerInfo &DCI) const {
10398   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10399          "Should be called with a BUILD_VECTOR node");
10400
10401   SelectionDAG &DAG = DCI.DAG;
10402   SDLoc dl(N);
10403   if (N->getValueType(0) != MVT::v2f64 || !Subtarget.hasVSX())
10404     return SDValue();
10405
10406   // Looking for:
10407   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
10408   if (N->getOperand(0).getOpcode() != ISD::SINT_TO_FP &&
10409       N->getOperand(0).getOpcode() != ISD::UINT_TO_FP)
10410     return SDValue();
10411   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
10412       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
10413     return SDValue();
10414   if (N->getOperand(0).getOpcode() != N->getOperand(1).getOpcode())
10415     return SDValue();
10416
10417   SDValue Ext1 = N->getOperand(0).getOperand(0);
10418   SDValue Ext2 = N->getOperand(1).getOperand(0);
10419   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10420      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10421     return SDValue();
10422
10423   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
10424   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
10425   if (!Ext1Op || !Ext2Op)
10426     return SDValue();
10427   if (Ext1.getValueType() != MVT::i32 ||
10428       Ext2.getValueType() != MVT::i32)
10429   if (Ext1.getOperand(0) != Ext2.getOperand(0))
10430     return SDValue();
10431
10432   int FirstElem = Ext1Op->getZExtValue();
10433   int SecondElem = Ext2Op->getZExtValue();
10434   int SubvecIdx;
10435   if (FirstElem == 0 && SecondElem == 1)
10436     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
10437   else if (FirstElem == 2 && SecondElem == 3)
10438     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
10439   else
10440     return SDValue();
10441
10442   SDValue SrcVec = Ext1.getOperand(0);
10443   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
10444     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
10445   return DAG.getNode(NodeType, dl, MVT::v2f64,
10446                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
10447 }
10448
10449 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
10450                                               DAGCombinerInfo &DCI) const {
10451   assert((N->getOpcode() == ISD::SINT_TO_FP ||
10452           N->getOpcode() == ISD::UINT_TO_FP) &&
10453          "Need an int -> FP conversion node here");
10454
10455   if (!Subtarget.has64BitSupport())
10456     return SDValue();
10457
10458   SelectionDAG &DAG = DCI.DAG;
10459   SDLoc dl(N);
10460   SDValue Op(N, 0);
10461
10462   // Don't handle ppc_fp128 here or i1 conversions.
10463   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10464     return SDValue();
10465   if (Op.getOperand(0).getValueType() == MVT::i1)
10466     return SDValue();
10467
10468   // For i32 intermediate values, unfortunately, the conversion functions
10469   // leave the upper 32 bits of the value are undefined. Within the set of
10470   // scalar instructions, we have no method for zero- or sign-extending the
10471   // value. Thus, we cannot handle i32 intermediate values here.
10472   if (Op.getOperand(0).getValueType() == MVT::i32)
10473     return SDValue();
10474
10475   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10476          "UINT_TO_FP is supported only with FPCVT");
10477
10478   // If we have FCFIDS, then use it when converting to single-precision.
10479   // Otherwise, convert to double-precision and then round.
10480   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10481                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10482                                                             : PPCISD::FCFIDS)
10483                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10484                                                             : PPCISD::FCFID);
10485   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10486                   ? MVT::f32
10487                   : MVT::f64;
10488
10489   // If we're converting from a float, to an int, and back to a float again,
10490   // then we don't need the store/load pair at all.
10491   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10492        Subtarget.hasFPCVT()) ||
10493       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10494     SDValue Src = Op.getOperand(0).getOperand(0);
10495     if (Src.getValueType() == MVT::f32) {
10496       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10497       DCI.AddToWorklist(Src.getNode());
10498     } else if (Src.getValueType() != MVT::f64) {
10499       // Make sure that we don't pick up a ppc_fp128 source value.
10500       return SDValue();
10501     }
10502
10503     unsigned FCTOp =
10504       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10505                                                         PPCISD::FCTIDUZ;
10506
10507     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10508     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10509
10510     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10511       FP = DAG.getNode(ISD::FP_ROUND, dl,
10512                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10513       DCI.AddToWorklist(FP.getNode());
10514     }
10515
10516     return FP;
10517   }
10518
10519   return SDValue();
10520 }
10521
10522 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10523 // builtins) into loads with swaps.
10524 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10525                                               DAGCombinerInfo &DCI) const {
10526   SelectionDAG &DAG = DCI.DAG;
10527   SDLoc dl(N);
10528   SDValue Chain;
10529   SDValue Base;
10530   MachineMemOperand *MMO;
10531
10532   switch (N->getOpcode()) {
10533   default:
10534     llvm_unreachable("Unexpected opcode for little endian VSX load");
10535   case ISD::LOAD: {
10536     LoadSDNode *LD = cast<LoadSDNode>(N);
10537     Chain = LD->getChain();
10538     Base = LD->getBasePtr();
10539     MMO = LD->getMemOperand();
10540     // If the MMO suggests this isn't a load of a full vector, leave
10541     // things alone.  For a built-in, we have to make the change for
10542     // correctness, so if there is a size problem that will be a bug.
10543     if (MMO->getSize() < 16)
10544       return SDValue();
10545     break;
10546   }
10547   case ISD::INTRINSIC_W_CHAIN: {
10548     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10549     Chain = Intrin->getChain();
10550     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10551     // us what we want. Get operand 2 instead.
10552     Base = Intrin->getOperand(2);
10553     MMO = Intrin->getMemOperand();
10554     break;
10555   }
10556   }
10557
10558   MVT VecTy = N->getValueType(0).getSimpleVT();
10559   SDValue LoadOps[] = { Chain, Base };
10560   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10561                                          DAG.getVTList(MVT::v2f64, MVT::Other),
10562                                          LoadOps, MVT::v2f64, MMO);
10563
10564   DCI.AddToWorklist(Load.getNode());
10565   Chain = Load.getValue(1);
10566   SDValue Swap = DAG.getNode(
10567       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
10568   DCI.AddToWorklist(Swap.getNode());
10569
10570   // Add a bitcast if the resulting load type doesn't match v2f64.
10571   if (VecTy != MVT::v2f64) {
10572     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
10573     DCI.AddToWorklist(N.getNode());
10574     // Package {bitcast value, swap's chain} to match Load's shape.
10575     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
10576                        N, Swap.getValue(1));
10577   }
10578
10579   return Swap;
10580 }
10581
10582 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10583 // builtins) into stores with swaps.
10584 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10585                                                DAGCombinerInfo &DCI) const {
10586   SelectionDAG &DAG = DCI.DAG;
10587   SDLoc dl(N);
10588   SDValue Chain;
10589   SDValue Base;
10590   unsigned SrcOpnd;
10591   MachineMemOperand *MMO;
10592
10593   switch (N->getOpcode()) {
10594   default:
10595     llvm_unreachable("Unexpected opcode for little endian VSX store");
10596   case ISD::STORE: {
10597     StoreSDNode *ST = cast<StoreSDNode>(N);
10598     Chain = ST->getChain();
10599     Base = ST->getBasePtr();
10600     MMO = ST->getMemOperand();
10601     SrcOpnd = 1;
10602     // If the MMO suggests this isn't a store of a full vector, leave
10603     // things alone.  For a built-in, we have to make the change for
10604     // correctness, so if there is a size problem that will be a bug.
10605     if (MMO->getSize() < 16)
10606       return SDValue();
10607     break;
10608   }
10609   case ISD::INTRINSIC_VOID: {
10610     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10611     Chain = Intrin->getChain();
10612     // Intrin->getBasePtr() oddly does not get what we want.
10613     Base = Intrin->getOperand(3);
10614     MMO = Intrin->getMemOperand();
10615     SrcOpnd = 2;
10616     break;
10617   }
10618   }
10619
10620   SDValue Src = N->getOperand(SrcOpnd);
10621   MVT VecTy = Src.getValueType().getSimpleVT();
10622
10623   // All stores are done as v2f64 and possible bit cast.
10624   if (VecTy != MVT::v2f64) {
10625     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
10626     DCI.AddToWorklist(Src.getNode());
10627   }
10628
10629   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10630                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
10631   DCI.AddToWorklist(Swap.getNode());
10632   Chain = Swap.getValue(1);
10633   SDValue StoreOps[] = { Chain, Swap, Base };
10634   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10635                                           DAG.getVTList(MVT::Other),
10636                                           StoreOps, VecTy, MMO);
10637   DCI.AddToWorklist(Store.getNode());
10638   return Store;
10639 }
10640
10641 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10642                                              DAGCombinerInfo &DCI) const {
10643   SelectionDAG &DAG = DCI.DAG;
10644   SDLoc dl(N);
10645   switch (N->getOpcode()) {
10646   default: break;
10647   case PPCISD::SHL:
10648     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10649         return N->getOperand(0);
10650     break;
10651   case PPCISD::SRL:
10652     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10653         return N->getOperand(0);
10654     break;
10655   case PPCISD::SRA:
10656     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10657       if (C->isNullValue() ||   //  0 >>s V -> 0.
10658           C->isAllOnesValue())    // -1 >>s V -> -1.
10659         return N->getOperand(0);
10660     }
10661     break;
10662   case ISD::SIGN_EXTEND:
10663   case ISD::ZERO_EXTEND:
10664   case ISD::ANY_EXTEND:
10665     return DAGCombineExtBoolTrunc(N, DCI);
10666   case ISD::TRUNCATE:
10667   case ISD::SETCC:
10668   case ISD::SELECT_CC:
10669     return DAGCombineTruncBoolExt(N, DCI);
10670   case ISD::SINT_TO_FP:
10671   case ISD::UINT_TO_FP:
10672     return combineFPToIntToFP(N, DCI);
10673   case ISD::STORE: {
10674     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10675     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10676         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10677         N->getOperand(1).getValueType() == MVT::i32 &&
10678         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10679       SDValue Val = N->getOperand(1).getOperand(0);
10680       if (Val.getValueType() == MVT::f32) {
10681         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10682         DCI.AddToWorklist(Val.getNode());
10683       }
10684       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10685       DCI.AddToWorklist(Val.getNode());
10686
10687       SDValue Ops[] = {
10688         N->getOperand(0), Val, N->getOperand(2),
10689         DAG.getValueType(N->getOperand(1).getValueType())
10690       };
10691
10692       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10693               DAG.getVTList(MVT::Other), Ops,
10694               cast<StoreSDNode>(N)->getMemoryVT(),
10695               cast<StoreSDNode>(N)->getMemOperand());
10696       DCI.AddToWorklist(Val.getNode());
10697       return Val;
10698     }
10699
10700     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10701     if (cast<StoreSDNode>(N)->isUnindexed() &&
10702         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10703         N->getOperand(1).getNode()->hasOneUse() &&
10704         (N->getOperand(1).getValueType() == MVT::i32 ||
10705          N->getOperand(1).getValueType() == MVT::i16 ||
10706          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10707           N->getOperand(1).getValueType() == MVT::i64))) {
10708       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10709       // Do an any-extend to 32-bits if this is a half-word input.
10710       if (BSwapOp.getValueType() == MVT::i16)
10711         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10712
10713       SDValue Ops[] = {
10714         N->getOperand(0), BSwapOp, N->getOperand(2),
10715         DAG.getValueType(N->getOperand(1).getValueType())
10716       };
10717       return
10718         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10719                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10720                                 cast<StoreSDNode>(N)->getMemOperand());
10721     }
10722
10723     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10724     EVT VT = N->getOperand(1).getValueType();
10725     if (VT.isSimple()) {
10726       MVT StoreVT = VT.getSimpleVT();
10727       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10728           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10729            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10730         return expandVSXStoreForLE(N, DCI);
10731     }
10732     break;
10733   }
10734   case ISD::LOAD: {
10735     LoadSDNode *LD = cast<LoadSDNode>(N);
10736     EVT VT = LD->getValueType(0);
10737
10738     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10739     if (VT.isSimple()) {
10740       MVT LoadVT = VT.getSimpleVT();
10741       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10742           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10743            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10744         return expandVSXLoadForLE(N, DCI);
10745     }
10746
10747     // We sometimes end up with a 64-bit integer load, from which we extract
10748     // two single-precision floating-point numbers. This happens with
10749     // std::complex<float>, and other similar structures, because of the way we
10750     // canonicalize structure copies. However, if we lack direct moves,
10751     // then the final bitcasts from the extracted integer values to the
10752     // floating-point numbers turn into store/load pairs. Even with direct moves,
10753     // just loading the two floating-point numbers is likely better.
10754     auto ReplaceTwoFloatLoad = [&]() {
10755       if (VT != MVT::i64)
10756         return false;
10757
10758       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
10759           LD->isVolatile())
10760         return false;
10761
10762       //  We're looking for a sequence like this:
10763       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
10764       //      t16: i64 = srl t13, Constant:i32<32>
10765       //    t17: i32 = truncate t16
10766       //  t18: f32 = bitcast t17
10767       //    t19: i32 = truncate t13
10768       //  t20: f32 = bitcast t19
10769
10770       if (!LD->hasNUsesOfValue(2, 0))
10771         return false;
10772
10773       auto UI = LD->use_begin();
10774       while (UI.getUse().getResNo() != 0) ++UI;
10775       SDNode *Trunc = *UI++;
10776       while (UI.getUse().getResNo() != 0) ++UI;
10777       SDNode *RightShift = *UI;
10778       if (Trunc->getOpcode() != ISD::TRUNCATE)
10779         std::swap(Trunc, RightShift);
10780
10781       if (Trunc->getOpcode() != ISD::TRUNCATE ||
10782           Trunc->getValueType(0) != MVT::i32 ||
10783           !Trunc->hasOneUse())
10784         return false;
10785       if (RightShift->getOpcode() != ISD::SRL ||
10786           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
10787           RightShift->getConstantOperandVal(1) != 32 ||
10788           !RightShift->hasOneUse())
10789         return false;
10790
10791       SDNode *Trunc2 = *RightShift->use_begin();
10792       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
10793           Trunc2->getValueType(0) != MVT::i32 ||
10794           !Trunc2->hasOneUse())
10795         return false;
10796
10797       SDNode *Bitcast = *Trunc->use_begin();
10798       SDNode *Bitcast2 = *Trunc2->use_begin();
10799
10800       if (Bitcast->getOpcode() != ISD::BITCAST ||
10801           Bitcast->getValueType(0) != MVT::f32)
10802         return false;
10803       if (Bitcast2->getOpcode() != ISD::BITCAST ||
10804           Bitcast2->getValueType(0) != MVT::f32)
10805         return false;
10806
10807       if (Subtarget.isLittleEndian())
10808         std::swap(Bitcast, Bitcast2);
10809
10810       // Bitcast has the second float (in memory-layout order) and Bitcast2
10811       // has the first one.
10812
10813       SDValue BasePtr = LD->getBasePtr();
10814       if (LD->isIndexed()) {
10815         assert(LD->getAddressingMode() == ISD::PRE_INC &&
10816                "Non-pre-inc AM on PPC?");
10817         BasePtr =
10818           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10819                       LD->getOffset());
10820       }
10821
10822       auto MMOFlags =
10823           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
10824       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
10825                                       LD->getPointerInfo(), LD->getAlignment(),
10826                                       MMOFlags, LD->getAAInfo());
10827       SDValue AddPtr =
10828         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
10829                     BasePtr, DAG.getIntPtrConstant(4, dl));
10830       SDValue FloatLoad2 = DAG.getLoad(
10831           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
10832           LD->getPointerInfo().getWithOffset(4),
10833           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
10834
10835       if (LD->isIndexed()) {
10836         // Note that DAGCombine should re-form any pre-increment load(s) from
10837         // what is produced here if that makes sense.
10838         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
10839       }
10840
10841       DCI.CombineTo(Bitcast2, FloatLoad);
10842       DCI.CombineTo(Bitcast, FloatLoad2);
10843
10844       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
10845                                     SDValue(FloatLoad2.getNode(), 1));
10846       return true;
10847     };
10848
10849     if (ReplaceTwoFloatLoad())
10850       return SDValue(N, 0);
10851
10852     EVT MemVT = LD->getMemoryVT();
10853     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10854     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10855     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10856     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10857     if (LD->isUnindexed() && VT.isVector() &&
10858         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10859           // P8 and later hardware should just use LOAD.
10860           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10861                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10862          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10863           LD->getAlignment() >= ScalarABIAlignment)) &&
10864         LD->getAlignment() < ABIAlignment) {
10865       // This is a type-legal unaligned Altivec or QPX load.
10866       SDValue Chain = LD->getChain();
10867       SDValue Ptr = LD->getBasePtr();
10868       bool isLittleEndian = Subtarget.isLittleEndian();
10869
10870       // This implements the loading of unaligned vectors as described in
10871       // the venerable Apple Velocity Engine overview. Specifically:
10872       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10873       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10874       //
10875       // The general idea is to expand a sequence of one or more unaligned
10876       // loads into an alignment-based permutation-control instruction (lvsl
10877       // or lvsr), a series of regular vector loads (which always truncate
10878       // their input address to an aligned address), and a series of
10879       // permutations.  The results of these permutations are the requested
10880       // loaded values.  The trick is that the last "extra" load is not taken
10881       // from the address you might suspect (sizeof(vector) bytes after the
10882       // last requested load), but rather sizeof(vector) - 1 bytes after the
10883       // last requested vector. The point of this is to avoid a page fault if
10884       // the base address happened to be aligned. This works because if the
10885       // base address is aligned, then adding less than a full vector length
10886       // will cause the last vector in the sequence to be (re)loaded.
10887       // Otherwise, the next vector will be fetched as you might suspect was
10888       // necessary.
10889
10890       // We might be able to reuse the permutation generation from
10891       // a different base address offset from this one by an aligned amount.
10892       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10893       // optimization later.
10894       Intrinsic::ID Intr, IntrLD, IntrPerm;
10895       MVT PermCntlTy, PermTy, LDTy;
10896       if (Subtarget.hasAltivec()) {
10897         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10898                                  Intrinsic::ppc_altivec_lvsl;
10899         IntrLD = Intrinsic::ppc_altivec_lvx;
10900         IntrPerm = Intrinsic::ppc_altivec_vperm;
10901         PermCntlTy = MVT::v16i8;
10902         PermTy = MVT::v4i32;
10903         LDTy = MVT::v4i32;
10904       } else {
10905         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10906                                        Intrinsic::ppc_qpx_qvlpcls;
10907         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10908                                        Intrinsic::ppc_qpx_qvlfs;
10909         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10910         PermCntlTy = MVT::v4f64;
10911         PermTy = MVT::v4f64;
10912         LDTy = MemVT.getSimpleVT();
10913       }
10914
10915       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10916
10917       // Create the new MMO for the new base load. It is like the original MMO,
10918       // but represents an area in memory almost twice the vector size centered
10919       // on the original address. If the address is unaligned, we might start
10920       // reading up to (sizeof(vector)-1) bytes below the address of the
10921       // original unaligned load.
10922       MachineFunction &MF = DAG.getMachineFunction();
10923       MachineMemOperand *BaseMMO =
10924         MF.getMachineMemOperand(LD->getMemOperand(),
10925                                 -(long)MemVT.getStoreSize()+1,
10926                                 2*MemVT.getStoreSize()-1);
10927
10928       // Create the new base load.
10929       SDValue LDXIntID =
10930           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10931       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10932       SDValue BaseLoad =
10933         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10934                                 DAG.getVTList(PermTy, MVT::Other),
10935                                 BaseLoadOps, LDTy, BaseMMO);
10936
10937       // Note that the value of IncOffset (which is provided to the next
10938       // load's pointer info offset value, and thus used to calculate the
10939       // alignment), and the value of IncValue (which is actually used to
10940       // increment the pointer value) are different! This is because we
10941       // require the next load to appear to be aligned, even though it
10942       // is actually offset from the base pointer by a lesser amount.
10943       int IncOffset = VT.getSizeInBits() / 8;
10944       int IncValue = IncOffset;
10945
10946       // Walk (both up and down) the chain looking for another load at the real
10947       // (aligned) offset (the alignment of the other load does not matter in
10948       // this case). If found, then do not use the offset reduction trick, as
10949       // that will prevent the loads from being later combined (as they would
10950       // otherwise be duplicates).
10951       if (!findConsecutiveLoad(LD, DAG))
10952         --IncValue;
10953
10954       SDValue Increment =
10955           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10956       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10957
10958       MachineMemOperand *ExtraMMO =
10959         MF.getMachineMemOperand(LD->getMemOperand(),
10960                                 1, 2*MemVT.getStoreSize()-1);
10961       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10962       SDValue ExtraLoad =
10963         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10964                                 DAG.getVTList(PermTy, MVT::Other),
10965                                 ExtraLoadOps, LDTy, ExtraMMO);
10966
10967       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10968         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10969
10970       // Because vperm has a big-endian bias, we must reverse the order
10971       // of the input vectors and complement the permute control vector
10972       // when generating little endian code.  We have already handled the
10973       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10974       // and ExtraLoad here.
10975       SDValue Perm;
10976       if (isLittleEndian)
10977         Perm = BuildIntrinsicOp(IntrPerm,
10978                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10979       else
10980         Perm = BuildIntrinsicOp(IntrPerm,
10981                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10982
10983       if (VT != PermTy)
10984         Perm = Subtarget.hasAltivec() ?
10985                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10986                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10987                                DAG.getTargetConstant(1, dl, MVT::i64));
10988                                // second argument is 1 because this rounding
10989                                // is always exact.
10990
10991       // The output of the permutation is our loaded result, the TokenFactor is
10992       // our new chain.
10993       DCI.CombineTo(N, Perm, TF);
10994       return SDValue(N, 0);
10995     }
10996     }
10997     break;
10998     case ISD::INTRINSIC_WO_CHAIN: {
10999       bool isLittleEndian = Subtarget.isLittleEndian();
11000       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11001       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11002                                            : Intrinsic::ppc_altivec_lvsl);
11003       if ((IID == Intr ||
11004            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11005            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11006         N->getOperand(1)->getOpcode() == ISD::ADD) {
11007         SDValue Add = N->getOperand(1);
11008
11009         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11010                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11011
11012         if (DAG.MaskedValueIsZero(
11013                 Add->getOperand(1),
11014                 APInt::getAllOnesValue(Bits /* alignment */)
11015                     .zext(
11016                         Add.getValueType().getScalarType().getSizeInBits()))) {
11017           SDNode *BasePtr = Add->getOperand(0).getNode();
11018           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11019                                     UE = BasePtr->use_end();
11020                UI != UE; ++UI) {
11021             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11022                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11023               // We've found another LVSL/LVSR, and this address is an aligned
11024               // multiple of that one. The results will be the same, so use the
11025               // one we've just found instead.
11026
11027               return SDValue(*UI, 0);
11028             }
11029           }
11030         }
11031
11032         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11033           SDNode *BasePtr = Add->getOperand(0).getNode();
11034           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11035                UE = BasePtr->use_end(); UI != UE; ++UI) {
11036             if (UI->getOpcode() == ISD::ADD &&
11037                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11038                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11039                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11040                 (1ULL << Bits) == 0) {
11041               SDNode *OtherAdd = *UI;
11042               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11043                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11044                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11045                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11046                   return SDValue(*VI, 0);
11047                 }
11048               }
11049             }
11050           }
11051         }
11052       }
11053     }
11054
11055     break;
11056   case ISD::INTRINSIC_W_CHAIN: {
11057     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11058     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
11059       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11060       default:
11061         break;
11062       case Intrinsic::ppc_vsx_lxvw4x:
11063       case Intrinsic::ppc_vsx_lxvd2x:
11064         return expandVSXLoadForLE(N, DCI);
11065       }
11066     }
11067     break;
11068   }
11069   case ISD::INTRINSIC_VOID: {
11070     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11071     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
11072       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11073       default:
11074         break;
11075       case Intrinsic::ppc_vsx_stxvw4x:
11076       case Intrinsic::ppc_vsx_stxvd2x:
11077         return expandVSXStoreForLE(N, DCI);
11078       }
11079     }
11080     break;
11081   }
11082   case ISD::BSWAP:
11083     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11084     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11085         N->getOperand(0).hasOneUse() &&
11086         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11087          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11088           N->getValueType(0) == MVT::i64))) {
11089       SDValue Load = N->getOperand(0);
11090       LoadSDNode *LD = cast<LoadSDNode>(Load);
11091       // Create the byte-swapping load.
11092       SDValue Ops[] = {
11093         LD->getChain(),    // Chain
11094         LD->getBasePtr(),  // Ptr
11095         DAG.getValueType(N->getValueType(0)) // VT
11096       };
11097       SDValue BSLoad =
11098         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11099                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11100                                               MVT::i64 : MVT::i32, MVT::Other),
11101                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11102
11103       // If this is an i16 load, insert the truncate.
11104       SDValue ResVal = BSLoad;
11105       if (N->getValueType(0) == MVT::i16)
11106         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11107
11108       // First, combine the bswap away.  This makes the value produced by the
11109       // load dead.
11110       DCI.CombineTo(N, ResVal);
11111
11112       // Next, combine the load away, we give it a bogus result value but a real
11113       // chain result.  The result value is dead because the bswap is dead.
11114       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11115
11116       // Return N so it doesn't get rechecked!
11117       return SDValue(N, 0);
11118     }
11119
11120     break;
11121   case PPCISD::VCMP: {
11122     // If a VCMPo node already exists with exactly the same operands as this
11123     // node, use its result instead of this node (VCMPo computes both a CR6 and
11124     // a normal output).
11125     //
11126     if (!N->getOperand(0).hasOneUse() &&
11127         !N->getOperand(1).hasOneUse() &&
11128         !N->getOperand(2).hasOneUse()) {
11129
11130       // Scan all of the users of the LHS, looking for VCMPo's that match.
11131       SDNode *VCMPoNode = nullptr;
11132
11133       SDNode *LHSN = N->getOperand(0).getNode();
11134       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11135            UI != E; ++UI)
11136         if (UI->getOpcode() == PPCISD::VCMPo &&
11137             UI->getOperand(1) == N->getOperand(1) &&
11138             UI->getOperand(2) == N->getOperand(2) &&
11139             UI->getOperand(0) == N->getOperand(0)) {
11140           VCMPoNode = *UI;
11141           break;
11142         }
11143
11144       // If there is no VCMPo node, or if the flag value has a single use, don't
11145       // transform this.
11146       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11147         break;
11148
11149       // Look at the (necessarily single) use of the flag value.  If it has a
11150       // chain, this transformation is more complex.  Note that multiple things
11151       // could use the value result, which we should ignore.
11152       SDNode *FlagUser = nullptr;
11153       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11154            FlagUser == nullptr; ++UI) {
11155         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11156         SDNode *User = *UI;
11157         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11158           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11159             FlagUser = User;
11160             break;
11161           }
11162         }
11163       }
11164
11165       // If the user is a MFOCRF instruction, we know this is safe.
11166       // Otherwise we give up for right now.
11167       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11168         return SDValue(VCMPoNode, 0);
11169     }
11170     break;
11171   }
11172   case ISD::BRCOND: {
11173     SDValue Cond = N->getOperand(1);
11174     SDValue Target = N->getOperand(2);
11175
11176     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11177         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11178           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11179
11180       // We now need to make the intrinsic dead (it cannot be instruction
11181       // selected).
11182       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11183       assert(Cond.getNode()->hasOneUse() &&
11184              "Counter decrement has more than one use");
11185
11186       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11187                          N->getOperand(0), Target);
11188     }
11189   }
11190   break;
11191   case ISD::BR_CC: {
11192     // If this is a branch on an altivec predicate comparison, lower this so
11193     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11194     // lowering is done pre-legalize, because the legalizer lowers the predicate
11195     // compare down to code that is difficult to reassemble.
11196     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11197     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11198
11199     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11200     // value. If so, pass-through the AND to get to the intrinsic.
11201     if (LHS.getOpcode() == ISD::AND &&
11202         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11203         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11204           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11205         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11206         !isNullConstant(LHS.getOperand(1)))
11207       LHS = LHS.getOperand(0);
11208
11209     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11210         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11211           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11212         isa<ConstantSDNode>(RHS)) {
11213       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11214              "Counter decrement comparison is not EQ or NE");
11215
11216       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11217       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11218                     (CC == ISD::SETNE && !Val);
11219
11220       // We now need to make the intrinsic dead (it cannot be instruction
11221       // selected).
11222       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11223       assert(LHS.getNode()->hasOneUse() &&
11224              "Counter decrement has more than one use");
11225
11226       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11227                          N->getOperand(0), N->getOperand(4));
11228     }
11229
11230     int CompareOpc;
11231     bool isDot;
11232
11233     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11234         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11235         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11236       assert(isDot && "Can't compare against a vector result!");
11237
11238       // If this is a comparison against something other than 0/1, then we know
11239       // that the condition is never/always true.
11240       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11241       if (Val != 0 && Val != 1) {
11242         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11243           return N->getOperand(0);
11244         // Always !=, turn it into an unconditional branch.
11245         return DAG.getNode(ISD::BR, dl, MVT::Other,
11246                            N->getOperand(0), N->getOperand(4));
11247       }
11248
11249       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11250
11251       // Create the PPCISD altivec 'dot' comparison node.
11252       SDValue Ops[] = {
11253         LHS.getOperand(2),  // LHS of compare
11254         LHS.getOperand(3),  // RHS of compare
11255         DAG.getConstant(CompareOpc, dl, MVT::i32)
11256       };
11257       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11258       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11259
11260       // Unpack the result based on how the target uses it.
11261       PPC::Predicate CompOpc;
11262       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11263       default:  // Can't happen, don't crash on invalid number though.
11264       case 0:   // Branch on the value of the EQ bit of CR6.
11265         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11266         break;
11267       case 1:   // Branch on the inverted value of the EQ bit of CR6.
11268         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11269         break;
11270       case 2:   // Branch on the value of the LT bit of CR6.
11271         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11272         break;
11273       case 3:   // Branch on the inverted value of the LT bit of CR6.
11274         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11275         break;
11276       }
11277
11278       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11279                          DAG.getConstant(CompOpc, dl, MVT::i32),
11280                          DAG.getRegister(PPC::CR6, MVT::i32),
11281                          N->getOperand(4), CompNode.getValue(1));
11282     }
11283     break;
11284   }
11285   case ISD::BUILD_VECTOR:
11286     return DAGCombineBuildVector(N, DCI);
11287   }
11288
11289   return SDValue();
11290 }
11291
11292 SDValue
11293 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11294                                   SelectionDAG &DAG,
11295                                   std::vector<SDNode *> *Created) const {
11296   // fold (sdiv X, pow2)
11297   EVT VT = N->getValueType(0);
11298   if (VT == MVT::i64 && !Subtarget.isPPC64())
11299     return SDValue();
11300   if ((VT != MVT::i32 && VT != MVT::i64) ||
11301       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
11302     return SDValue();
11303
11304   SDLoc DL(N);
11305   SDValue N0 = N->getOperand(0);
11306
11307   bool IsNegPow2 = (-Divisor).isPowerOf2();
11308   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
11309   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
11310
11311   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
11312   if (Created)
11313     Created->push_back(Op.getNode());
11314
11315   if (IsNegPow2) {
11316     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
11317     if (Created)
11318       Created->push_back(Op.getNode());
11319   }
11320
11321   return Op;
11322 }
11323
11324 //===----------------------------------------------------------------------===//
11325 // Inline Assembly Support
11326 //===----------------------------------------------------------------------===//
11327
11328 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
11329                                                       APInt &KnownZero,
11330                                                       APInt &KnownOne,
11331                                                       const SelectionDAG &DAG,
11332                                                       unsigned Depth) const {
11333   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
11334   switch (Op.getOpcode()) {
11335   default: break;
11336   case PPCISD::LBRX: {
11337     // lhbrx is known to have the top bits cleared out.
11338     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
11339       KnownZero = 0xFFFF0000;
11340     break;
11341   }
11342   case ISD::INTRINSIC_WO_CHAIN: {
11343     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
11344     default: break;
11345     case Intrinsic::ppc_altivec_vcmpbfp_p:
11346     case Intrinsic::ppc_altivec_vcmpeqfp_p:
11347     case Intrinsic::ppc_altivec_vcmpequb_p:
11348     case Intrinsic::ppc_altivec_vcmpequh_p:
11349     case Intrinsic::ppc_altivec_vcmpequw_p:
11350     case Intrinsic::ppc_altivec_vcmpequd_p:
11351     case Intrinsic::ppc_altivec_vcmpgefp_p:
11352     case Intrinsic::ppc_altivec_vcmpgtfp_p:
11353     case Intrinsic::ppc_altivec_vcmpgtsb_p:
11354     case Intrinsic::ppc_altivec_vcmpgtsh_p:
11355     case Intrinsic::ppc_altivec_vcmpgtsw_p:
11356     case Intrinsic::ppc_altivec_vcmpgtsd_p:
11357     case Intrinsic::ppc_altivec_vcmpgtub_p:
11358     case Intrinsic::ppc_altivec_vcmpgtuh_p:
11359     case Intrinsic::ppc_altivec_vcmpgtuw_p:
11360     case Intrinsic::ppc_altivec_vcmpgtud_p:
11361       KnownZero = ~1U;  // All bits but the low one are known to be zero.
11362       break;
11363     }
11364   }
11365   }
11366 }
11367
11368 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11369   switch (Subtarget.getDarwinDirective()) {
11370   default: break;
11371   case PPC::DIR_970:
11372   case PPC::DIR_PWR4:
11373   case PPC::DIR_PWR5:
11374   case PPC::DIR_PWR5X:
11375   case PPC::DIR_PWR6:
11376   case PPC::DIR_PWR6X:
11377   case PPC::DIR_PWR7:
11378   case PPC::DIR_PWR8:
11379   case PPC::DIR_PWR9: {
11380     if (!ML)
11381       break;
11382
11383     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11384
11385     // For small loops (between 5 and 8 instructions), align to a 32-byte
11386     // boundary so that the entire loop fits in one instruction-cache line.
11387     uint64_t LoopSize = 0;
11388     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
11389       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
11390         LoopSize += TII->getInstSizeInBytes(*J);
11391         if (LoopSize > 32)
11392           break;
11393       }
11394
11395     if (LoopSize > 16 && LoopSize <= 32)
11396       return 5;
11397
11398     break;
11399   }
11400   }
11401
11402   return TargetLowering::getPrefLoopAlignment(ML);
11403 }
11404
11405 /// getConstraintType - Given a constraint, return the type of
11406 /// constraint it is for this target.
11407 PPCTargetLowering::ConstraintType
11408 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
11409   if (Constraint.size() == 1) {
11410     switch (Constraint[0]) {
11411     default: break;
11412     case 'b':
11413     case 'r':
11414     case 'f':
11415     case 'd':
11416     case 'v':
11417     case 'y':
11418       return C_RegisterClass;
11419     case 'Z':
11420       // FIXME: While Z does indicate a memory constraint, it specifically
11421       // indicates an r+r address (used in conjunction with the 'y' modifier
11422       // in the replacement string). Currently, we're forcing the base
11423       // register to be r0 in the asm printer (which is interpreted as zero)
11424       // and forming the complete address in the second register. This is
11425       // suboptimal.
11426       return C_Memory;
11427     }
11428   } else if (Constraint == "wc") { // individual CR bits.
11429     return C_RegisterClass;
11430   } else if (Constraint == "wa" || Constraint == "wd" ||
11431              Constraint == "wf" || Constraint == "ws") {
11432     return C_RegisterClass; // VSX registers.
11433   }
11434   return TargetLowering::getConstraintType(Constraint);
11435 }
11436
11437 /// Examine constraint type and operand type and determine a weight value.
11438 /// This object must already have been set up with the operand type
11439 /// and the current alternative constraint selected.
11440 TargetLowering::ConstraintWeight
11441 PPCTargetLowering::getSingleConstraintMatchWeight(
11442     AsmOperandInfo &info, const char *constraint) const {
11443   ConstraintWeight weight = CW_Invalid;
11444   Value *CallOperandVal = info.CallOperandVal;
11445     // If we don't have a value, we can't do a match,
11446     // but allow it at the lowest weight.
11447   if (!CallOperandVal)
11448     return CW_Default;
11449   Type *type = CallOperandVal->getType();
11450
11451   // Look at the constraint type.
11452   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
11453     return CW_Register; // an individual CR bit.
11454   else if ((StringRef(constraint) == "wa" ||
11455             StringRef(constraint) == "wd" ||
11456             StringRef(constraint) == "wf") &&
11457            type->isVectorTy())
11458     return CW_Register;
11459   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
11460     return CW_Register;
11461
11462   switch (*constraint) {
11463   default:
11464     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11465     break;
11466   case 'b':
11467     if (type->isIntegerTy())
11468       weight = CW_Register;
11469     break;
11470   case 'f':
11471     if (type->isFloatTy())
11472       weight = CW_Register;
11473     break;
11474   case 'd':
11475     if (type->isDoubleTy())
11476       weight = CW_Register;
11477     break;
11478   case 'v':
11479     if (type->isVectorTy())
11480       weight = CW_Register;
11481     break;
11482   case 'y':
11483     weight = CW_Register;
11484     break;
11485   case 'Z':
11486     weight = CW_Memory;
11487     break;
11488   }
11489   return weight;
11490 }
11491
11492 std::pair<unsigned, const TargetRegisterClass *>
11493 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11494                                                 StringRef Constraint,
11495                                                 MVT VT) const {
11496   if (Constraint.size() == 1) {
11497     // GCC RS6000 Constraint Letters
11498     switch (Constraint[0]) {
11499     case 'b':   // R1-R31
11500       if (VT == MVT::i64 && Subtarget.isPPC64())
11501         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
11502       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
11503     case 'r':   // R0-R31
11504       if (VT == MVT::i64 && Subtarget.isPPC64())
11505         return std::make_pair(0U, &PPC::G8RCRegClass);
11506       return std::make_pair(0U, &PPC::GPRCRegClass);
11507     // 'd' and 'f' constraints are both defined to be "the floating point
11508     // registers", where one is for 32-bit and the other for 64-bit. We don't
11509     // really care overly much here so just give them all the same reg classes.
11510     case 'd':
11511     case 'f':
11512       if (VT == MVT::f32 || VT == MVT::i32)
11513         return std::make_pair(0U, &PPC::F4RCRegClass);
11514       if (VT == MVT::f64 || VT == MVT::i64)
11515         return std::make_pair(0U, &PPC::F8RCRegClass);
11516       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11517         return std::make_pair(0U, &PPC::QFRCRegClass);
11518       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11519         return std::make_pair(0U, &PPC::QSRCRegClass);
11520       break;
11521     case 'v':
11522       if (VT == MVT::v4f64 && Subtarget.hasQPX())
11523         return std::make_pair(0U, &PPC::QFRCRegClass);
11524       if (VT == MVT::v4f32 && Subtarget.hasQPX())
11525         return std::make_pair(0U, &PPC::QSRCRegClass);
11526       if (Subtarget.hasAltivec())
11527         return std::make_pair(0U, &PPC::VRRCRegClass);
11528     case 'y':   // crrc
11529       return std::make_pair(0U, &PPC::CRRCRegClass);
11530     }
11531   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
11532     // An individual CR bit.
11533     return std::make_pair(0U, &PPC::CRBITRCRegClass);
11534   } else if ((Constraint == "wa" || Constraint == "wd" ||
11535              Constraint == "wf") && Subtarget.hasVSX()) {
11536     return std::make_pair(0U, &PPC::VSRCRegClass);
11537   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
11538     if (VT == MVT::f32 && Subtarget.hasP8Vector())
11539       return std::make_pair(0U, &PPC::VSSRCRegClass);
11540     else
11541       return std::make_pair(0U, &PPC::VSFRCRegClass);
11542   }
11543
11544   std::pair<unsigned, const TargetRegisterClass *> R =
11545       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11546
11547   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
11548   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
11549   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
11550   // register.
11551   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
11552   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
11553   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
11554       PPC::GPRCRegClass.contains(R.first))
11555     return std::make_pair(TRI->getMatchingSuperReg(R.first,
11556                             PPC::sub_32, &PPC::G8RCRegClass),
11557                           &PPC::G8RCRegClass);
11558
11559   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
11560   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
11561     R.first = PPC::CR0;
11562     R.second = &PPC::CRRCRegClass;
11563   }
11564
11565   return R;
11566 }
11567
11568 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11569 /// vector.  If it is invalid, don't add anything to Ops.
11570 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11571                                                      std::string &Constraint,
11572                                                      std::vector<SDValue>&Ops,
11573                                                      SelectionDAG &DAG) const {
11574   SDValue Result;
11575
11576   // Only support length 1 constraints.
11577   if (Constraint.length() > 1) return;
11578
11579   char Letter = Constraint[0];
11580   switch (Letter) {
11581   default: break;
11582   case 'I':
11583   case 'J':
11584   case 'K':
11585   case 'L':
11586   case 'M':
11587   case 'N':
11588   case 'O':
11589   case 'P': {
11590     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
11591     if (!CST) return; // Must be an immediate to match.
11592     SDLoc dl(Op);
11593     int64_t Value = CST->getSExtValue();
11594     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11595                          // numbers are printed as such.
11596     switch (Letter) {
11597     default: llvm_unreachable("Unknown constraint letter!");
11598     case 'I':  // "I" is a signed 16-bit constant.
11599       if (isInt<16>(Value))
11600         Result = DAG.getTargetConstant(Value, dl, TCVT);
11601       break;
11602     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11603       if (isShiftedUInt<16, 16>(Value))
11604         Result = DAG.getTargetConstant(Value, dl, TCVT);
11605       break;
11606     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11607       if (isShiftedInt<16, 16>(Value))
11608         Result = DAG.getTargetConstant(Value, dl, TCVT);
11609       break;
11610     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11611       if (isUInt<16>(Value))
11612         Result = DAG.getTargetConstant(Value, dl, TCVT);
11613       break;
11614     case 'M':  // "M" is a constant that is greater than 31.
11615       if (Value > 31)
11616         Result = DAG.getTargetConstant(Value, dl, TCVT);
11617       break;
11618     case 'N':  // "N" is a positive constant that is an exact power of two.
11619       if (Value > 0 && isPowerOf2_64(Value))
11620         Result = DAG.getTargetConstant(Value, dl, TCVT);
11621       break;
11622     case 'O':  // "O" is the constant zero.
11623       if (Value == 0)
11624         Result = DAG.getTargetConstant(Value, dl, TCVT);
11625       break;
11626     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11627       if (isInt<16>(-Value))
11628         Result = DAG.getTargetConstant(Value, dl, TCVT);
11629       break;
11630     }
11631     break;
11632   }
11633   }
11634
11635   if (Result.getNode()) {
11636     Ops.push_back(Result);
11637     return;
11638   }
11639
11640   // Handle standard constraint letters.
11641   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11642 }
11643
11644 // isLegalAddressingMode - Return true if the addressing mode represented
11645 // by AM is legal for this target, for a load/store of the specified type.
11646 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11647                                               const AddrMode &AM, Type *Ty,
11648                                               unsigned AS) const {
11649   // PPC does not allow r+i addressing modes for vectors!
11650   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11651     return false;
11652
11653   // PPC allows a sign-extended 16-bit immediate field.
11654   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11655     return false;
11656
11657   // No global is ever allowed as a base.
11658   if (AM.BaseGV)
11659     return false;
11660
11661   // PPC only support r+r,
11662   switch (AM.Scale) {
11663   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11664     break;
11665   case 1:
11666     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11667       return false;
11668     // Otherwise we have r+r or r+i.
11669     break;
11670   case 2:
11671     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11672       return false;
11673     // Allow 2*r as r+r.
11674     break;
11675   default:
11676     // No other scales are supported.
11677     return false;
11678   }
11679
11680   return true;
11681 }
11682
11683 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11684                                            SelectionDAG &DAG) const {
11685   MachineFunction &MF = DAG.getMachineFunction();
11686   MachineFrameInfo &MFI = MF.getFrameInfo();
11687   MFI.setReturnAddressIsTaken(true);
11688
11689   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11690     return SDValue();
11691
11692   SDLoc dl(Op);
11693   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11694
11695   // Make sure the function does not optimize away the store of the RA to
11696   // the stack.
11697   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11698   FuncInfo->setLRStoreRequired();
11699   bool isPPC64 = Subtarget.isPPC64();
11700   auto PtrVT = getPointerTy(MF.getDataLayout());
11701
11702   if (Depth > 0) {
11703     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11704     SDValue Offset =
11705         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11706                         isPPC64 ? MVT::i64 : MVT::i32);
11707     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11708                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11709                        MachinePointerInfo());
11710   }
11711
11712   // Just load the return address off the stack.
11713   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11714   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11715                      MachinePointerInfo());
11716 }
11717
11718 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11719                                           SelectionDAG &DAG) const {
11720   SDLoc dl(Op);
11721   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11722
11723   MachineFunction &MF = DAG.getMachineFunction();
11724   MachineFrameInfo &MFI = MF.getFrameInfo();
11725   MFI.setFrameAddressIsTaken(true);
11726
11727   EVT PtrVT = getPointerTy(MF.getDataLayout());
11728   bool isPPC64 = PtrVT == MVT::i64;
11729
11730   // Naked functions never have a frame pointer, and so we use r1. For all
11731   // other functions, this decision must be delayed until during PEI.
11732   unsigned FrameReg;
11733   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11734     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11735   else
11736     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11737
11738   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11739                                          PtrVT);
11740   while (Depth--)
11741     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11742                             FrameAddr, MachinePointerInfo());
11743   return FrameAddr;
11744 }
11745
11746 // FIXME? Maybe this could be a TableGen attribute on some registers and
11747 // this table could be generated automatically from RegInfo.
11748 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11749                                               SelectionDAG &DAG) const {
11750   bool isPPC64 = Subtarget.isPPC64();
11751   bool isDarwinABI = Subtarget.isDarwinABI();
11752
11753   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11754       (!isPPC64 && VT != MVT::i32))
11755     report_fatal_error("Invalid register global variable type");
11756
11757   bool is64Bit = isPPC64 && VT == MVT::i64;
11758   unsigned Reg = StringSwitch<unsigned>(RegName)
11759                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11760                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11761                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11762                                   (is64Bit ? PPC::X13 : PPC::R13))
11763                    .Default(0);
11764
11765   if (Reg)
11766     return Reg;
11767   report_fatal_error("Invalid register name global variable");
11768 }
11769
11770 bool
11771 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11772   // The PowerPC target isn't yet aware of offsets.
11773   return false;
11774 }
11775
11776 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11777                                            const CallInst &I,
11778                                            unsigned Intrinsic) const {
11779
11780   switch (Intrinsic) {
11781   case Intrinsic::ppc_qpx_qvlfd:
11782   case Intrinsic::ppc_qpx_qvlfs:
11783   case Intrinsic::ppc_qpx_qvlfcd:
11784   case Intrinsic::ppc_qpx_qvlfcs:
11785   case Intrinsic::ppc_qpx_qvlfiwa:
11786   case Intrinsic::ppc_qpx_qvlfiwz:
11787   case Intrinsic::ppc_altivec_lvx:
11788   case Intrinsic::ppc_altivec_lvxl:
11789   case Intrinsic::ppc_altivec_lvebx:
11790   case Intrinsic::ppc_altivec_lvehx:
11791   case Intrinsic::ppc_altivec_lvewx:
11792   case Intrinsic::ppc_vsx_lxvd2x:
11793   case Intrinsic::ppc_vsx_lxvw4x: {
11794     EVT VT;
11795     switch (Intrinsic) {
11796     case Intrinsic::ppc_altivec_lvebx:
11797       VT = MVT::i8;
11798       break;
11799     case Intrinsic::ppc_altivec_lvehx:
11800       VT = MVT::i16;
11801       break;
11802     case Intrinsic::ppc_altivec_lvewx:
11803       VT = MVT::i32;
11804       break;
11805     case Intrinsic::ppc_vsx_lxvd2x:
11806       VT = MVT::v2f64;
11807       break;
11808     case Intrinsic::ppc_qpx_qvlfd:
11809       VT = MVT::v4f64;
11810       break;
11811     case Intrinsic::ppc_qpx_qvlfs:
11812       VT = MVT::v4f32;
11813       break;
11814     case Intrinsic::ppc_qpx_qvlfcd:
11815       VT = MVT::v2f64;
11816       break;
11817     case Intrinsic::ppc_qpx_qvlfcs:
11818       VT = MVT::v2f32;
11819       break;
11820     default:
11821       VT = MVT::v4i32;
11822       break;
11823     }
11824
11825     Info.opc = ISD::INTRINSIC_W_CHAIN;
11826     Info.memVT = VT;
11827     Info.ptrVal = I.getArgOperand(0);
11828     Info.offset = -VT.getStoreSize()+1;
11829     Info.size = 2*VT.getStoreSize()-1;
11830     Info.align = 1;
11831     Info.vol = false;
11832     Info.readMem = true;
11833     Info.writeMem = false;
11834     return true;
11835   }
11836   case Intrinsic::ppc_qpx_qvlfda:
11837   case Intrinsic::ppc_qpx_qvlfsa:
11838   case Intrinsic::ppc_qpx_qvlfcda:
11839   case Intrinsic::ppc_qpx_qvlfcsa:
11840   case Intrinsic::ppc_qpx_qvlfiwaa:
11841   case Intrinsic::ppc_qpx_qvlfiwza: {
11842     EVT VT;
11843     switch (Intrinsic) {
11844     case Intrinsic::ppc_qpx_qvlfda:
11845       VT = MVT::v4f64;
11846       break;
11847     case Intrinsic::ppc_qpx_qvlfsa:
11848       VT = MVT::v4f32;
11849       break;
11850     case Intrinsic::ppc_qpx_qvlfcda:
11851       VT = MVT::v2f64;
11852       break;
11853     case Intrinsic::ppc_qpx_qvlfcsa:
11854       VT = MVT::v2f32;
11855       break;
11856     default:
11857       VT = MVT::v4i32;
11858       break;
11859     }
11860
11861     Info.opc = ISD::INTRINSIC_W_CHAIN;
11862     Info.memVT = VT;
11863     Info.ptrVal = I.getArgOperand(0);
11864     Info.offset = 0;
11865     Info.size = VT.getStoreSize();
11866     Info.align = 1;
11867     Info.vol = false;
11868     Info.readMem = true;
11869     Info.writeMem = false;
11870     return true;
11871   }
11872   case Intrinsic::ppc_qpx_qvstfd:
11873   case Intrinsic::ppc_qpx_qvstfs:
11874   case Intrinsic::ppc_qpx_qvstfcd:
11875   case Intrinsic::ppc_qpx_qvstfcs:
11876   case Intrinsic::ppc_qpx_qvstfiw:
11877   case Intrinsic::ppc_altivec_stvx:
11878   case Intrinsic::ppc_altivec_stvxl:
11879   case Intrinsic::ppc_altivec_stvebx:
11880   case Intrinsic::ppc_altivec_stvehx:
11881   case Intrinsic::ppc_altivec_stvewx:
11882   case Intrinsic::ppc_vsx_stxvd2x:
11883   case Intrinsic::ppc_vsx_stxvw4x: {
11884     EVT VT;
11885     switch (Intrinsic) {
11886     case Intrinsic::ppc_altivec_stvebx:
11887       VT = MVT::i8;
11888       break;
11889     case Intrinsic::ppc_altivec_stvehx:
11890       VT = MVT::i16;
11891       break;
11892     case Intrinsic::ppc_altivec_stvewx:
11893       VT = MVT::i32;
11894       break;
11895     case Intrinsic::ppc_vsx_stxvd2x:
11896       VT = MVT::v2f64;
11897       break;
11898     case Intrinsic::ppc_qpx_qvstfd:
11899       VT = MVT::v4f64;
11900       break;
11901     case Intrinsic::ppc_qpx_qvstfs:
11902       VT = MVT::v4f32;
11903       break;
11904     case Intrinsic::ppc_qpx_qvstfcd:
11905       VT = MVT::v2f64;
11906       break;
11907     case Intrinsic::ppc_qpx_qvstfcs:
11908       VT = MVT::v2f32;
11909       break;
11910     default:
11911       VT = MVT::v4i32;
11912       break;
11913     }
11914
11915     Info.opc = ISD::INTRINSIC_VOID;
11916     Info.memVT = VT;
11917     Info.ptrVal = I.getArgOperand(1);
11918     Info.offset = -VT.getStoreSize()+1;
11919     Info.size = 2*VT.getStoreSize()-1;
11920     Info.align = 1;
11921     Info.vol = false;
11922     Info.readMem = false;
11923     Info.writeMem = true;
11924     return true;
11925   }
11926   case Intrinsic::ppc_qpx_qvstfda:
11927   case Intrinsic::ppc_qpx_qvstfsa:
11928   case Intrinsic::ppc_qpx_qvstfcda:
11929   case Intrinsic::ppc_qpx_qvstfcsa:
11930   case Intrinsic::ppc_qpx_qvstfiwa: {
11931     EVT VT;
11932     switch (Intrinsic) {
11933     case Intrinsic::ppc_qpx_qvstfda:
11934       VT = MVT::v4f64;
11935       break;
11936     case Intrinsic::ppc_qpx_qvstfsa:
11937       VT = MVT::v4f32;
11938       break;
11939     case Intrinsic::ppc_qpx_qvstfcda:
11940       VT = MVT::v2f64;
11941       break;
11942     case Intrinsic::ppc_qpx_qvstfcsa:
11943       VT = MVT::v2f32;
11944       break;
11945     default:
11946       VT = MVT::v4i32;
11947       break;
11948     }
11949
11950     Info.opc = ISD::INTRINSIC_VOID;
11951     Info.memVT = VT;
11952     Info.ptrVal = I.getArgOperand(1);
11953     Info.offset = 0;
11954     Info.size = VT.getStoreSize();
11955     Info.align = 1;
11956     Info.vol = false;
11957     Info.readMem = false;
11958     Info.writeMem = true;
11959     return true;
11960   }
11961   default:
11962     break;
11963   }
11964
11965   return false;
11966 }
11967
11968 /// getOptimalMemOpType - Returns the target specific optimal type for load
11969 /// and store operations as a result of memset, memcpy, and memmove
11970 /// lowering. If DstAlign is zero that means it's safe to destination
11971 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11972 /// means there isn't a need to check it against alignment requirement,
11973 /// probably because the source does not need to be loaded. If 'IsMemset' is
11974 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11975 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11976 /// source is constant so it does not need to be loaded.
11977 /// It returns EVT::Other if the type should be determined using generic
11978 /// target-independent logic.
11979 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11980                                            unsigned DstAlign, unsigned SrcAlign,
11981                                            bool IsMemset, bool ZeroMemset,
11982                                            bool MemcpyStrSrc,
11983                                            MachineFunction &MF) const {
11984   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11985     const Function *F = MF.getFunction();
11986     // When expanding a memset, require at least two QPX instructions to cover
11987     // the cost of loading the value to be stored from the constant pool.
11988     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11989        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11990         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11991       return MVT::v4f64;
11992     }
11993
11994     // We should use Altivec/VSX loads and stores when available. For unaligned
11995     // addresses, unaligned VSX loads are only fast starting with the P8.
11996     if (Subtarget.hasAltivec() && Size >= 16 &&
11997         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11998          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11999       return MVT::v4i32;
12000   }
12001
12002   if (Subtarget.isPPC64()) {
12003     return MVT::i64;
12004   }
12005
12006   return MVT::i32;
12007 }
12008
12009 /// \brief Returns true if it is beneficial to convert a load of a constant
12010 /// to just the constant itself.
12011 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12012                                                           Type *Ty) const {
12013   assert(Ty->isIntegerTy());
12014
12015   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12016   return !(BitSize == 0 || BitSize > 64);
12017 }
12018
12019 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12020   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12021     return false;
12022   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12023   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12024   return NumBits1 == 64 && NumBits2 == 32;
12025 }
12026
12027 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12028   if (!VT1.isInteger() || !VT2.isInteger())
12029     return false;
12030   unsigned NumBits1 = VT1.getSizeInBits();
12031   unsigned NumBits2 = VT2.getSizeInBits();
12032   return NumBits1 == 64 && NumBits2 == 32;
12033 }
12034
12035 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12036   // Generally speaking, zexts are not free, but they are free when they can be
12037   // folded with other operations.
12038   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12039     EVT MemVT = LD->getMemoryVT();
12040     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12041          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12042         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12043          LD->getExtensionType() == ISD::ZEXTLOAD))
12044       return true;
12045   }
12046
12047   // FIXME: Add other cases...
12048   //  - 32-bit shifts with a zext to i64
12049   //  - zext after ctlz, bswap, etc.
12050   //  - zext after and by a constant mask
12051
12052   return TargetLowering::isZExtFree(Val, VT2);
12053 }
12054
12055 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12056   assert(VT.isFloatingPoint());
12057   return true;
12058 }
12059
12060 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12061   return isInt<16>(Imm) || isUInt<16>(Imm);
12062 }
12063
12064 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12065   return isInt<16>(Imm) || isUInt<16>(Imm);
12066 }
12067
12068 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12069                                                        unsigned,
12070                                                        unsigned,
12071                                                        bool *Fast) const {
12072   if (DisablePPCUnaligned)
12073     return false;
12074
12075   // PowerPC supports unaligned memory access for simple non-vector types.
12076   // Although accessing unaligned addresses is not as efficient as accessing
12077   // aligned addresses, it is generally more efficient than manual expansion,
12078   // and generally only traps for software emulation when crossing page
12079   // boundaries.
12080
12081   if (!VT.isSimple())
12082     return false;
12083
12084   if (VT.getSimpleVT().isVector()) {
12085     if (Subtarget.hasVSX()) {
12086       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12087           VT != MVT::v4f32 && VT != MVT::v4i32)
12088         return false;
12089     } else {
12090       return false;
12091     }
12092   }
12093
12094   if (VT == MVT::ppcf128)
12095     return false;
12096
12097   if (Fast)
12098     *Fast = true;
12099
12100   return true;
12101 }
12102
12103 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12104   VT = VT.getScalarType();
12105
12106   if (!VT.isSimple())
12107     return false;
12108
12109   switch (VT.getSimpleVT().SimpleTy) {
12110   case MVT::f32:
12111   case MVT::f64:
12112     return true;
12113   default:
12114     break;
12115   }
12116
12117   return false;
12118 }
12119
12120 const MCPhysReg *
12121 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12122   // LR is a callee-save register, but we must treat it as clobbered by any call
12123   // site. Hence we include LR in the scratch registers, which are in turn added
12124   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12125   // to CTR, which is used by any indirect call.
12126   static const MCPhysReg ScratchRegs[] = {
12127     PPC::X12, PPC::LR8, PPC::CTR8, 0
12128   };
12129
12130   return ScratchRegs;
12131 }
12132
12133 unsigned PPCTargetLowering::getExceptionPointerRegister(
12134     const Constant *PersonalityFn) const {
12135   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12136 }
12137
12138 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12139     const Constant *PersonalityFn) const {
12140   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12141 }
12142
12143 bool
12144 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12145                      EVT VT , unsigned DefinedValues) const {
12146   if (VT == MVT::v2i64)
12147     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12148
12149   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12150     return true;
12151
12152   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12153 }
12154
12155 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12156   if (DisableILPPref || Subtarget.enableMachineScheduler())
12157     return TargetLowering::getSchedulingPreference(N);
12158
12159   return Sched::ILP;
12160 }
12161
12162 // Create a fast isel object.
12163 FastISel *
12164 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12165                                   const TargetLibraryInfo *LibInfo) const {
12166   return PPC::createFastISel(FuncInfo, LibInfo);
12167 }
12168
12169 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12170   if (Subtarget.isDarwinABI()) return;
12171   if (!Subtarget.isPPC64()) return;
12172
12173   // Update IsSplitCSR in PPCFunctionInfo
12174   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12175   PFI->setIsSplitCSR(true);
12176 }
12177
12178 void PPCTargetLowering::insertCopiesSplitCSR(
12179   MachineBasicBlock *Entry,
12180   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12181   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12182   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12183   if (!IStart)
12184     return;
12185
12186   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12187   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12188   MachineBasicBlock::iterator MBBI = Entry->begin();
12189   for (const MCPhysReg *I = IStart; *I; ++I) {
12190     const TargetRegisterClass *RC = nullptr;
12191     if (PPC::G8RCRegClass.contains(*I))
12192       RC = &PPC::G8RCRegClass;
12193     else if (PPC::F8RCRegClass.contains(*I))
12194       RC = &PPC::F8RCRegClass;
12195     else if (PPC::CRRCRegClass.contains(*I))
12196       RC = &PPC::CRRCRegClass;
12197     else if (PPC::VRRCRegClass.contains(*I))
12198       RC = &PPC::VRRCRegClass;
12199     else
12200       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12201
12202     unsigned NewVR = MRI->createVirtualRegister(RC);
12203     // Create copy from CSR to a virtual register.
12204     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12205     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12206     // nounwind. If we want to generalize this later, we may need to emit
12207     // CFI pseudo-instructions.
12208     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12209              Attribute::NoUnwind) &&
12210            "Function should be nounwind in insertCopiesSplitCSR!");
12211     Entry->addLiveIn(*I);
12212     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12213       .addReg(*I);
12214
12215     // Insert the copy-back instructions right before the terminator
12216     for (auto *Exit : Exits)
12217       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12218               TII->get(TargetOpcode::COPY), *I)
12219         .addReg(NewVR);
12220   }
12221 }
12222
12223 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12224 bool PPCTargetLowering::useLoadStackGuardNode() const {
12225   if (!Subtarget.isTargetLinux())
12226     return TargetLowering::useLoadStackGuardNode();
12227   return true;
12228 }
12229
12230 // Override to disable global variable loading on Linux.
12231 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12232   if (!Subtarget.isTargetLinux())
12233     return TargetLowering::insertSSPDeclarations(M);
12234 }