Introduce new @llvm.get.dynamic.area.offset.i{32, 64} intrinsics.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
42
43 using namespace llvm;
44
45 // FIXME: Remove this once soft-float is supported.
46 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
47 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
48
49 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
50 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
51
52 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
53 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
54
55 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
56 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
57
58 // FIXME: Remove this once the bug has been fixed!
59 extern cl::opt<bool> ANDIGlueBug;
60
61 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
62                                      const PPCSubtarget &STI)
63     : TargetLowering(TM), Subtarget(STI) {
64   // Use _setjmp/_longjmp instead of setjmp/longjmp.
65   setUseUnderscoreSetJmp(true);
66   setUseUnderscoreLongJmp(true);
67
68   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
69   // arguments are at least 4/8 bytes aligned.
70   bool isPPC64 = Subtarget.isPPC64();
71   setMinStackArgumentAlignment(isPPC64 ? 8:4);
72
73   // Set up the register classes.
74   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
75   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
76   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
77
78   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
79   for (MVT VT : MVT::integer_valuetypes()) {
80     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
81     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
82   }
83
84   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
85
86   // PowerPC has pre-inc load and store's.
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
100   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
101
102   if (Subtarget.useCRBits()) {
103     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
104
105     if (isPPC64 || Subtarget.hasFPCVT()) {
106       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
107       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
108                          isPPC64 ? MVT::i64 : MVT::i32);
109       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
110       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
111                         isPPC64 ? MVT::i64 : MVT::i32);
112     } else {
113       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
114       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
115     }
116
117     // PowerPC does not support direct load / store of condition registers
118     setOperationAction(ISD::LOAD, MVT::i1, Custom);
119     setOperationAction(ISD::STORE, MVT::i1, Custom);
120
121     // FIXME: Remove this once the ANDI glue bug is fixed:
122     if (ANDIGlueBug)
123       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
124
125     for (MVT VT : MVT::integer_valuetypes()) {
126       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
127       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
128       setTruncStoreAction(VT, MVT::i1, Expand);
129     }
130
131     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
132   }
133
134   // This is used in the ppcf128->int sequence.  Note it has different semantics
135   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
136   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
137
138   // We do not currently implement these libm ops for PowerPC.
139   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
140   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
141   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
142   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
143   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
144   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
145
146   // PowerPC has no SREM/UREM instructions
147   setOperationAction(ISD::SREM, MVT::i32, Expand);
148   setOperationAction(ISD::UREM, MVT::i32, Expand);
149   setOperationAction(ISD::SREM, MVT::i64, Expand);
150   setOperationAction(ISD::UREM, MVT::i64, Expand);
151
152   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
153   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
155   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
157   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
159   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
160   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
161
162   // We don't support sin/cos/sqrt/fmod/pow
163   setOperationAction(ISD::FSIN , MVT::f64, Expand);
164   setOperationAction(ISD::FCOS , MVT::f64, Expand);
165   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
166   setOperationAction(ISD::FREM , MVT::f64, Expand);
167   setOperationAction(ISD::FPOW , MVT::f64, Expand);
168   setOperationAction(ISD::FMA  , MVT::f64, Legal);
169   setOperationAction(ISD::FSIN , MVT::f32, Expand);
170   setOperationAction(ISD::FCOS , MVT::f32, Expand);
171   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
172   setOperationAction(ISD::FREM , MVT::f32, Expand);
173   setOperationAction(ISD::FPOW , MVT::f32, Expand);
174   setOperationAction(ISD::FMA  , MVT::f32, Legal);
175
176   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
177
178   // If we're enabling GP optimizations, use hardware square root
179   if (!Subtarget.hasFSQRT() &&
180       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
181         Subtarget.hasFRE()))
182     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
183
184   if (!Subtarget.hasFSQRT() &&
185       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
186         Subtarget.hasFRES()))
187     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
188
189   if (Subtarget.hasFCPSGN()) {
190     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
191     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
192   } else {
193     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
195   }
196
197   if (Subtarget.hasFPRND()) {
198     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
199     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
200     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
201     setOperationAction(ISD::FROUND, MVT::f64, Legal);
202
203     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
204     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
205     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
206     setOperationAction(ISD::FROUND, MVT::f32, Legal);
207   }
208
209   // PowerPC does not have BSWAP, CTPOP or CTTZ
210   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
212   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
214   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
216   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
217   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218
219   if (Subtarget.hasPOPCNTD()) {
220     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
221     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
222   } else {
223     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
224     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
225   }
226
227   // PowerPC does not have ROTR
228   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
229   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
230
231   if (!Subtarget.useCRBits()) {
232     // PowerPC does not have Select
233     setOperationAction(ISD::SELECT, MVT::i32, Expand);
234     setOperationAction(ISD::SELECT, MVT::i64, Expand);
235     setOperationAction(ISD::SELECT, MVT::f32, Expand);
236     setOperationAction(ISD::SELECT, MVT::f64, Expand);
237   }
238
239   // PowerPC wants to turn select_cc of FP into fsel when possible.
240   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242
243   // PowerPC wants to optimize integer setcc a bit
244   if (!Subtarget.useCRBits())
245     setOperationAction(ISD::SETCC, MVT::i32, Custom);
246
247   // PowerPC does not have BRCOND which requires SetCC
248   if (!Subtarget.useCRBits())
249     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
250
251   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
252
253   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
254   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255
256   // PowerPC does not have [U|S]INT_TO_FP
257   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
258   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
259
260   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
262   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
263   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
264
265   // We cannot sextinreg(i1).  Expand to shifts.
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
267
268   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
269   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
270   // support continuation, user-level threading, and etc.. As a result, no
271   // other SjLj exception interfaces are implemented and please don't build
272   // your own exception handling based on them.
273   // LLVM/Clang supports zero-cost DWARF exception handling.
274   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
275   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
276
277   // We want to legalize GlobalAddress and ConstantPool nodes into the
278   // appropriate instructions to materialize the address.
279   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
280   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
281   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
282   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
283   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
284   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
285   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
287   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
288   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
289
290   // TRAP is legal.
291   setOperationAction(ISD::TRAP, MVT::Other, Legal);
292
293   // TRAMPOLINE is custom lowered.
294   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
295   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
296
297   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
298   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
299
300   if (Subtarget.isSVR4ABI()) {
301     if (isPPC64) {
302       // VAARG always uses double-word chunks, so promote anything smaller.
303       setOperationAction(ISD::VAARG, MVT::i1, Promote);
304       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
305       setOperationAction(ISD::VAARG, MVT::i8, Promote);
306       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
307       setOperationAction(ISD::VAARG, MVT::i16, Promote);
308       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
309       setOperationAction(ISD::VAARG, MVT::i32, Promote);
310       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
311       setOperationAction(ISD::VAARG, MVT::Other, Expand);
312     } else {
313       // VAARG is custom lowered with the 32-bit SVR4 ABI.
314       setOperationAction(ISD::VAARG, MVT::Other, Custom);
315       setOperationAction(ISD::VAARG, MVT::i64, Custom);
316     }
317   } else
318     setOperationAction(ISD::VAARG, MVT::Other, Expand);
319
320   if (Subtarget.isSVR4ABI() && !isPPC64)
321     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
322     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
323   else
324     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
325
326   // Use the default implementation.
327   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
328   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
329   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
331   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
332   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
333   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
334
335   // We want to custom lower some of our intrinsics.
336   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
337
338   // To handle counter-based loop conditions.
339   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
340
341   // Comparisons that require checking two conditions.
342   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
343   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
344   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
345   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
346   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
347   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
348   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
349   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
350   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
351   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
352   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
353   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
354
355   if (Subtarget.has64BitSupport()) {
356     // They also have instructions for converting between i64 and fp.
357     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
358     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
359     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
360     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
361     // This is just the low 32 bits of a (signed) fp->i64 conversion.
362     // We cannot do this with Promote because i64 is not a legal type.
363     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
364
365     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
366       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
367   } else {
368     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
369     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
370   }
371
372   // With the instructions enabled under FPCVT, we can do everything.
373   if (Subtarget.hasFPCVT()) {
374     if (Subtarget.has64BitSupport()) {
375       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
376       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
377       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
378       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
379     }
380
381     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
383     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
384     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
385   }
386
387   if (Subtarget.use64BitRegs()) {
388     // 64-bit PowerPC implementations can support i64 types directly
389     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
390     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
391     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
392     // 64-bit PowerPC wants to expand i128 shifts itself.
393     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
394     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
395     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
396   } else {
397     // 32-bit PowerPC wants to expand i64 shifts itself.
398     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
399     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
400     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
401   }
402
403   if (Subtarget.hasAltivec()) {
404     // First set operation action for all vector types to expand. Then we
405     // will selectively turn on ones that can be effectively codegen'd.
406     for (MVT VT : MVT::vector_valuetypes()) {
407       // add/sub are legal for all supported vector VT's.
408       setOperationAction(ISD::ADD, VT, Legal);
409       setOperationAction(ISD::SUB, VT, Legal);
410
411       // Vector instructions introduced in P8
412       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
413         setOperationAction(ISD::CTPOP, VT, Legal);
414         setOperationAction(ISD::CTLZ, VT, Legal);
415       }
416       else {
417         setOperationAction(ISD::CTPOP, VT, Expand);
418         setOperationAction(ISD::CTLZ, VT, Expand);
419       }
420
421       // We promote all shuffles to v16i8.
422       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
423       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
424
425       // We promote all non-typed operations to v4i32.
426       setOperationAction(ISD::AND   , VT, Promote);
427       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
428       setOperationAction(ISD::OR    , VT, Promote);
429       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
430       setOperationAction(ISD::XOR   , VT, Promote);
431       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
432       setOperationAction(ISD::LOAD  , VT, Promote);
433       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
434       setOperationAction(ISD::SELECT, VT, Promote);
435       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
436       setOperationAction(ISD::SELECT_CC, VT, Promote);
437       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
438       setOperationAction(ISD::STORE, VT, Promote);
439       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
440
441       // No other operations are legal.
442       setOperationAction(ISD::MUL , VT, Expand);
443       setOperationAction(ISD::SDIV, VT, Expand);
444       setOperationAction(ISD::SREM, VT, Expand);
445       setOperationAction(ISD::UDIV, VT, Expand);
446       setOperationAction(ISD::UREM, VT, Expand);
447       setOperationAction(ISD::FDIV, VT, Expand);
448       setOperationAction(ISD::FREM, VT, Expand);
449       setOperationAction(ISD::FNEG, VT, Expand);
450       setOperationAction(ISD::FSQRT, VT, Expand);
451       setOperationAction(ISD::FLOG, VT, Expand);
452       setOperationAction(ISD::FLOG10, VT, Expand);
453       setOperationAction(ISD::FLOG2, VT, Expand);
454       setOperationAction(ISD::FEXP, VT, Expand);
455       setOperationAction(ISD::FEXP2, VT, Expand);
456       setOperationAction(ISD::FSIN, VT, Expand);
457       setOperationAction(ISD::FCOS, VT, Expand);
458       setOperationAction(ISD::FABS, VT, Expand);
459       setOperationAction(ISD::FPOWI, VT, Expand);
460       setOperationAction(ISD::FFLOOR, VT, Expand);
461       setOperationAction(ISD::FCEIL,  VT, Expand);
462       setOperationAction(ISD::FTRUNC, VT, Expand);
463       setOperationAction(ISD::FRINT,  VT, Expand);
464       setOperationAction(ISD::FNEARBYINT, VT, Expand);
465       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
466       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
467       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
468       setOperationAction(ISD::MULHU, VT, Expand);
469       setOperationAction(ISD::MULHS, VT, Expand);
470       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
471       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
472       setOperationAction(ISD::UDIVREM, VT, Expand);
473       setOperationAction(ISD::SDIVREM, VT, Expand);
474       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
475       setOperationAction(ISD::FPOW, VT, Expand);
476       setOperationAction(ISD::BSWAP, VT, Expand);
477       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
478       setOperationAction(ISD::CTTZ, VT, Expand);
479       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
480       setOperationAction(ISD::VSELECT, VT, Expand);
481       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
482
483       for (MVT InnerVT : MVT::vector_valuetypes()) {
484         setTruncStoreAction(VT, InnerVT, Expand);
485         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
486         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
487         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
488       }
489     }
490
491     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
492     // with merges, splats, etc.
493     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
494
495     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
496     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
497     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
498     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
499     setOperationAction(ISD::SELECT, MVT::v4i32,
500                        Subtarget.useCRBits() ? Legal : Expand);
501     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
502     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
503     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
504     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
505     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
506     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
507     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
508     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
509     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
510
511     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
512     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
513     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
514     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
515
516     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
517     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
518
519     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
520       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
521       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
522     }
523
524     if (Subtarget.hasP8Altivec())
525       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
526     else
527       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
528
529     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
530     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
531
532     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
533     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
534
535     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
536     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
537     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
538     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
539
540     // Altivec does not contain unordered floating-point compare instructions
541     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
542     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
543     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
544     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
545
546     if (Subtarget.hasVSX()) {
547       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
548       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
549       if (Subtarget.hasP8Vector()) {
550         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
551         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
552       }
553       if (Subtarget.hasDirectMove()) {
554         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
555         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
556         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
557         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
558         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
559         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
560         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
561         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
562       }
563       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
564
565       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
566       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
567       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
568       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
569       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
570
571       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
572
573       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
574       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
575
576       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
577       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
578
579       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
580       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
581       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
582       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
583       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
584
585       // Share the Altivec comparison restrictions.
586       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
587       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
588       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
589       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
590
591       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
592       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
593
594       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
595
596       if (Subtarget.hasP8Vector())
597         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
598
599       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
600
601       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
602       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
603       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
604
605       if (Subtarget.hasP8Altivec()) {
606         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
607         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
608         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
609
610         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
611       }
612       else {
613         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
614         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
615         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
616
617         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
618
619         // VSX v2i64 only supports non-arithmetic operations.
620         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
621         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
622       }
623
624       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
625       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
626       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
627       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
628
629       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
630
631       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
632       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
633       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
634       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
635
636       // Vector operation legalization checks the result type of
637       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
638       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
639       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
640       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
641       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
642
643       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
644     }
645
646     if (Subtarget.hasP8Altivec()) {
647       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
648       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
649     }
650   }
651
652   if (Subtarget.hasQPX()) {
653     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
654     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
655     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
656     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
657
658     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
659     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
660
661     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
662     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
663
664     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
665     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
666
667     if (!Subtarget.useCRBits())
668       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
669     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
670
671     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
672     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
673     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
674     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
675     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
676     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
677     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
678
679     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
680     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
681
682     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
683     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
684     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
685
686     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
687     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
688     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
689     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
690     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
691     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
692     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
693     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
694     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
695     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
696     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
697
698     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
699     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
700
701     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
702     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
703
704     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
705
706     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
707     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
708     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
709     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
710
711     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
712     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
713
714     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
715     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
716
717     if (!Subtarget.useCRBits())
718       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
719     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
720
721     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
722     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
723     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
724     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
725     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
726     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
727     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
728
729     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
730     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
731
732     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
733     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
734     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
735     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
736     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
737     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
738     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
739     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
740     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
741     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
742     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
743
744     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
745     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
746
747     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
748     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
749
750     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
751
752     setOperationAction(ISD::AND , MVT::v4i1, Legal);
753     setOperationAction(ISD::OR , MVT::v4i1, Legal);
754     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
755
756     if (!Subtarget.useCRBits())
757       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
758     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
759
760     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
761     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
762
763     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
764     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
765     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
766     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
767     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
768     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
769     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
770
771     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
772     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
773
774     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
775
776     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
777     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
778     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
779     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
780
781     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
782     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
783     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
784     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
785
786     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
787     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
788
789     // These need to set FE_INEXACT, and so cannot be vectorized here.
790     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
791     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
792
793     if (TM.Options.UnsafeFPMath) {
794       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
795       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
796
797       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
798       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
799     } else {
800       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
801       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
802
803       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
804       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
805     }
806   }
807
808   if (Subtarget.has64BitSupport())
809     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
810
811   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
812
813   if (!isPPC64) {
814     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
815     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
816   }
817
818   setBooleanContents(ZeroOrOneBooleanContent);
819
820   if (Subtarget.hasAltivec()) {
821     // Altivec instructions set fields to all zeros or all ones.
822     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
823   }
824
825   if (!isPPC64) {
826     // These libcalls are not available in 32-bit.
827     setLibcallName(RTLIB::SHL_I128, nullptr);
828     setLibcallName(RTLIB::SRL_I128, nullptr);
829     setLibcallName(RTLIB::SRA_I128, nullptr);
830   }
831
832   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
833
834   // We have target-specific dag combine patterns for the following nodes:
835   setTargetDAGCombine(ISD::SINT_TO_FP);
836   if (Subtarget.hasFPCVT())
837     setTargetDAGCombine(ISD::UINT_TO_FP);
838   setTargetDAGCombine(ISD::LOAD);
839   setTargetDAGCombine(ISD::STORE);
840   setTargetDAGCombine(ISD::BR_CC);
841   if (Subtarget.useCRBits())
842     setTargetDAGCombine(ISD::BRCOND);
843   setTargetDAGCombine(ISD::BSWAP);
844   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
845   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
846   setTargetDAGCombine(ISD::INTRINSIC_VOID);
847
848   setTargetDAGCombine(ISD::SIGN_EXTEND);
849   setTargetDAGCombine(ISD::ZERO_EXTEND);
850   setTargetDAGCombine(ISD::ANY_EXTEND);
851
852   if (Subtarget.useCRBits()) {
853     setTargetDAGCombine(ISD::TRUNCATE);
854     setTargetDAGCombine(ISD::SETCC);
855     setTargetDAGCombine(ISD::SELECT_CC);
856   }
857
858   // Use reciprocal estimates.
859   if (TM.Options.UnsafeFPMath) {
860     setTargetDAGCombine(ISD::FDIV);
861     setTargetDAGCombine(ISD::FSQRT);
862   }
863
864   // Darwin long double math library functions have $LDBL128 appended.
865   if (Subtarget.isDarwin()) {
866     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
867     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
868     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
869     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
870     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
871     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
872     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
873     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
874     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
875     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
876   }
877
878   // With 32 condition bits, we don't need to sink (and duplicate) compares
879   // aggressively in CodeGenPrep.
880   if (Subtarget.useCRBits()) {
881     setHasMultipleConditionRegisters();
882     setJumpIsExpensive();
883   }
884
885   setMinFunctionAlignment(2);
886   if (Subtarget.isDarwin())
887     setPrefFunctionAlignment(4);
888
889   switch (Subtarget.getDarwinDirective()) {
890   default: break;
891   case PPC::DIR_970:
892   case PPC::DIR_A2:
893   case PPC::DIR_E500mc:
894   case PPC::DIR_E5500:
895   case PPC::DIR_PWR4:
896   case PPC::DIR_PWR5:
897   case PPC::DIR_PWR5X:
898   case PPC::DIR_PWR6:
899   case PPC::DIR_PWR6X:
900   case PPC::DIR_PWR7:
901   case PPC::DIR_PWR8:
902     setPrefFunctionAlignment(4);
903     setPrefLoopAlignment(4);
904     break;
905   }
906
907   setInsertFencesForAtomic(true);
908
909   if (Subtarget.enableMachineScheduler())
910     setSchedulingPreference(Sched::Source);
911   else
912     setSchedulingPreference(Sched::Hybrid);
913
914   computeRegisterProperties(STI.getRegisterInfo());
915
916   // The Freescale cores do better with aggressive inlining of memcpy and
917   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
918   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
919       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
920     MaxStoresPerMemset = 32;
921     MaxStoresPerMemsetOptSize = 16;
922     MaxStoresPerMemcpy = 32;
923     MaxStoresPerMemcpyOptSize = 8;
924     MaxStoresPerMemmove = 32;
925     MaxStoresPerMemmoveOptSize = 8;
926   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
927     // The A2 also benefits from (very) aggressive inlining of memcpy and
928     // friends. The overhead of a the function call, even when warm, can be
929     // over one hundred cycles.
930     MaxStoresPerMemset = 128;
931     MaxStoresPerMemcpy = 128;
932     MaxStoresPerMemmove = 128;
933   }
934 }
935
936 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
937 /// the desired ByVal argument alignment.
938 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
939                              unsigned MaxMaxAlign) {
940   if (MaxAlign == MaxMaxAlign)
941     return;
942   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
943     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
944       MaxAlign = 32;
945     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
946       MaxAlign = 16;
947   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
948     unsigned EltAlign = 0;
949     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
950     if (EltAlign > MaxAlign)
951       MaxAlign = EltAlign;
952   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
953     for (auto *EltTy : STy->elements()) {
954       unsigned EltAlign = 0;
955       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
956       if (EltAlign > MaxAlign)
957         MaxAlign = EltAlign;
958       if (MaxAlign == MaxMaxAlign)
959         break;
960     }
961   }
962 }
963
964 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
965 /// function arguments in the caller parameter area.
966 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
967                                                   const DataLayout &DL) const {
968   // Darwin passes everything on 4 byte boundary.
969   if (Subtarget.isDarwin())
970     return 4;
971
972   // 16byte and wider vectors are passed on 16byte boundary.
973   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
974   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
975   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
976     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
977   return Align;
978 }
979
980 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
981   switch ((PPCISD::NodeType)Opcode) {
982   case PPCISD::FIRST_NUMBER:    break;
983   case PPCISD::FSEL:            return "PPCISD::FSEL";
984   case PPCISD::FCFID:           return "PPCISD::FCFID";
985   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
986   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
987   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
988   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
989   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
990   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
991   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
992   case PPCISD::FRE:             return "PPCISD::FRE";
993   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
994   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
995   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
996   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
997   case PPCISD::VPERM:           return "PPCISD::VPERM";
998   case PPCISD::CMPB:            return "PPCISD::CMPB";
999   case PPCISD::Hi:              return "PPCISD::Hi";
1000   case PPCISD::Lo:              return "PPCISD::Lo";
1001   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1002   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1003   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1004   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1005   case PPCISD::SRL:             return "PPCISD::SRL";
1006   case PPCISD::SRA:             return "PPCISD::SRA";
1007   case PPCISD::SHL:             return "PPCISD::SHL";
1008   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1009   case PPCISD::CALL:            return "PPCISD::CALL";
1010   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1011   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1012   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1013   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1014   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1015   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1016   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1017   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1018   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1019   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1020   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1021   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1022   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1023   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1024   case PPCISD::VCMP:            return "PPCISD::VCMP";
1025   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1026   case PPCISD::LBRX:            return "PPCISD::LBRX";
1027   case PPCISD::STBRX:           return "PPCISD::STBRX";
1028   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1029   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1030   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1031   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1032   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1033   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1034   case PPCISD::BDZ:             return "PPCISD::BDZ";
1035   case PPCISD::MFFS:            return "PPCISD::MFFS";
1036   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1037   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1038   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1039   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1040   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1041   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1042   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1043   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1044   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1045   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1046   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1047   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1048   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1049   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1050   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1051   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1052   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1053   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1054   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1055   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1056   case PPCISD::SC:              return "PPCISD::SC";
1057   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1058   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1059   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1060   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1061   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1062   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1063   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1064   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1065   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1066   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1067   }
1068   return nullptr;
1069 }
1070
1071 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1072                                           EVT VT) const {
1073   if (!VT.isVector())
1074     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1075
1076   if (Subtarget.hasQPX())
1077     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1078
1079   return VT.changeVectorElementTypeToInteger();
1080 }
1081
1082 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1083   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1084   return true;
1085 }
1086
1087 //===----------------------------------------------------------------------===//
1088 // Node matching predicates, for use by the tblgen matching code.
1089 //===----------------------------------------------------------------------===//
1090
1091 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1092 static bool isFloatingPointZero(SDValue Op) {
1093   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1094     return CFP->getValueAPF().isZero();
1095   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1096     // Maybe this has already been legalized into the constant pool?
1097     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1098       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1099         return CFP->getValueAPF().isZero();
1100   }
1101   return false;
1102 }
1103
1104 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1105 /// true if Op is undef or if it matches the specified value.
1106 static bool isConstantOrUndef(int Op, int Val) {
1107   return Op < 0 || Op == Val;
1108 }
1109
1110 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1111 /// VPKUHUM instruction.
1112 /// The ShuffleKind distinguishes between big-endian operations with
1113 /// two different inputs (0), either-endian operations with two identical
1114 /// inputs (1), and little-endian operations with two different inputs (2).
1115 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1116 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1117                                SelectionDAG &DAG) {
1118   bool IsLE = DAG.getDataLayout().isLittleEndian();
1119   if (ShuffleKind == 0) {
1120     if (IsLE)
1121       return false;
1122     for (unsigned i = 0; i != 16; ++i)
1123       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1124         return false;
1125   } else if (ShuffleKind == 2) {
1126     if (!IsLE)
1127       return false;
1128     for (unsigned i = 0; i != 16; ++i)
1129       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1130         return false;
1131   } else if (ShuffleKind == 1) {
1132     unsigned j = IsLE ? 0 : 1;
1133     for (unsigned i = 0; i != 8; ++i)
1134       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1135           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1136         return false;
1137   }
1138   return true;
1139 }
1140
1141 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1142 /// VPKUWUM instruction.
1143 /// The ShuffleKind distinguishes between big-endian operations with
1144 /// two different inputs (0), either-endian operations with two identical
1145 /// inputs (1), and little-endian operations with two different inputs (2).
1146 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1147 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1148                                SelectionDAG &DAG) {
1149   bool IsLE = DAG.getDataLayout().isLittleEndian();
1150   if (ShuffleKind == 0) {
1151     if (IsLE)
1152       return false;
1153     for (unsigned i = 0; i != 16; i += 2)
1154       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1155           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1156         return false;
1157   } else if (ShuffleKind == 2) {
1158     if (!IsLE)
1159       return false;
1160     for (unsigned i = 0; i != 16; i += 2)
1161       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1162           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1163         return false;
1164   } else if (ShuffleKind == 1) {
1165     unsigned j = IsLE ? 0 : 2;
1166     for (unsigned i = 0; i != 8; i += 2)
1167       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1168           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1169           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1170           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1171         return false;
1172   }
1173   return true;
1174 }
1175
1176 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1177 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1178 /// current subtarget.
1179 ///
1180 /// The ShuffleKind distinguishes between big-endian operations with
1181 /// two different inputs (0), either-endian operations with two identical
1182 /// inputs (1), and little-endian operations with two different inputs (2).
1183 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1184 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1185                                SelectionDAG &DAG) {
1186   const PPCSubtarget& Subtarget =
1187     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1188   if (!Subtarget.hasP8Vector())
1189     return false;
1190
1191   bool IsLE = DAG.getDataLayout().isLittleEndian();
1192   if (ShuffleKind == 0) {
1193     if (IsLE)
1194       return false;
1195     for (unsigned i = 0; i != 16; i += 4)
1196       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1197           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1198           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1199           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1200         return false;
1201   } else if (ShuffleKind == 2) {
1202     if (!IsLE)
1203       return false;
1204     for (unsigned i = 0; i != 16; i += 4)
1205       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1206           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1207           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1208           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1209         return false;
1210   } else if (ShuffleKind == 1) {
1211     unsigned j = IsLE ? 0 : 4;
1212     for (unsigned i = 0; i != 8; i += 4)
1213       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1214           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1215           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1216           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1217           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1218           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1219           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1220           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1221         return false;
1222   }
1223   return true;
1224 }
1225
1226 /// isVMerge - Common function, used to match vmrg* shuffles.
1227 ///
1228 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1229                      unsigned LHSStart, unsigned RHSStart) {
1230   if (N->getValueType(0) != MVT::v16i8)
1231     return false;
1232   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1233          "Unsupported merge size!");
1234
1235   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1236     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1237       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1238                              LHSStart+j+i*UnitSize) ||
1239           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1240                              RHSStart+j+i*UnitSize))
1241         return false;
1242     }
1243   return true;
1244 }
1245
1246 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1247 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1248 /// The ShuffleKind distinguishes between big-endian merges with two
1249 /// different inputs (0), either-endian merges with two identical inputs (1),
1250 /// and little-endian merges with two different inputs (2).  For the latter,
1251 /// the input operands are swapped (see PPCInstrAltivec.td).
1252 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1253                              unsigned ShuffleKind, SelectionDAG &DAG) {
1254   if (DAG.getDataLayout().isLittleEndian()) {
1255     if (ShuffleKind == 1) // unary
1256       return isVMerge(N, UnitSize, 0, 0);
1257     else if (ShuffleKind == 2) // swapped
1258       return isVMerge(N, UnitSize, 0, 16);
1259     else
1260       return false;
1261   } else {
1262     if (ShuffleKind == 1) // unary
1263       return isVMerge(N, UnitSize, 8, 8);
1264     else if (ShuffleKind == 0) // normal
1265       return isVMerge(N, UnitSize, 8, 24);
1266     else
1267       return false;
1268   }
1269 }
1270
1271 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1272 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1273 /// The ShuffleKind distinguishes between big-endian merges with two
1274 /// different inputs (0), either-endian merges with two identical inputs (1),
1275 /// and little-endian merges with two different inputs (2).  For the latter,
1276 /// the input operands are swapped (see PPCInstrAltivec.td).
1277 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1278                              unsigned ShuffleKind, SelectionDAG &DAG) {
1279   if (DAG.getDataLayout().isLittleEndian()) {
1280     if (ShuffleKind == 1) // unary
1281       return isVMerge(N, UnitSize, 8, 8);
1282     else if (ShuffleKind == 2) // swapped
1283       return isVMerge(N, UnitSize, 8, 24);
1284     else
1285       return false;
1286   } else {
1287     if (ShuffleKind == 1) // unary
1288       return isVMerge(N, UnitSize, 0, 0);
1289     else if (ShuffleKind == 0) // normal
1290       return isVMerge(N, UnitSize, 0, 16);
1291     else
1292       return false;
1293   }
1294 }
1295
1296 /**
1297  * \brief Common function used to match vmrgew and vmrgow shuffles
1298  *
1299  * The indexOffset determines whether to look for even or odd words in
1300  * the shuffle mask. This is based on the of the endianness of the target
1301  * machine.
1302  *   - Little Endian:
1303  *     - Use offset of 0 to check for odd elements
1304  *     - Use offset of 4 to check for even elements
1305  *   - Big Endian:
1306  *     - Use offset of 0 to check for even elements
1307  *     - Use offset of 4 to check for odd elements
1308  * A detailed description of the vector element ordering for little endian and
1309  * big endian can be found at
1310  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1311  * Targeting your applications - what little endian and big endian IBM XL C/C++
1312  * compiler differences mean to you
1313  *
1314  * The mask to the shuffle vector instruction specifies the indices of the
1315  * elements from the two input vectors to place in the result. The elements are
1316  * numbered in array-access order, starting with the first vector. These vectors
1317  * are always of type v16i8, thus each vector will contain 16 elements of size
1318  * 8. More info on the shuffle vector can be found in the
1319  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1320  * Language Reference.
1321  *
1322  * The RHSStartValue indicates whether the same input vectors are used (unary)
1323  * or two different input vectors are used, based on the following:
1324  *   - If the instruction uses the same vector for both inputs, the range of the
1325  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1326  *     be 0.
1327  *   - If the instruction has two different vectors then the range of the
1328  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1329  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1330  *     to 31 specify elements in the second vector).
1331  *
1332  * \param[in] N The shuffle vector SD Node to analyze
1333  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1334  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1335  * vector to the shuffle_vector instruction
1336  * \return true iff this shuffle vector represents an even or odd word merge
1337  */
1338 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1339                      unsigned RHSStartValue) {
1340   if (N->getValueType(0) != MVT::v16i8)
1341     return false;
1342
1343   for (unsigned i = 0; i < 2; ++i)
1344     for (unsigned j = 0; j < 4; ++j)
1345       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1346                              i*RHSStartValue+j+IndexOffset) ||
1347           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1348                              i*RHSStartValue+j+IndexOffset+8))
1349         return false;
1350   return true;
1351 }
1352
1353 /**
1354  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1355  * vmrgow instructions.
1356  *
1357  * \param[in] N The shuffle vector SD Node to analyze
1358  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1359  * \param[in] ShuffleKind Identify the type of merge:
1360  *   - 0 = big-endian merge with two different inputs;
1361  *   - 1 = either-endian merge with two identical inputs;
1362  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1363  *     little-endian merges).
1364  * \param[in] DAG The current SelectionDAG
1365  * \return true iff this shuffle mask
1366  */
1367 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1368                               unsigned ShuffleKind, SelectionDAG &DAG) {
1369   if (DAG.getDataLayout().isLittleEndian()) {
1370     unsigned indexOffset = CheckEven ? 4 : 0;
1371     if (ShuffleKind == 1) // Unary
1372       return isVMerge(N, indexOffset, 0);
1373     else if (ShuffleKind == 2) // swapped
1374       return isVMerge(N, indexOffset, 16);
1375     else
1376       return false;
1377   }
1378   else {
1379     unsigned indexOffset = CheckEven ? 0 : 4;
1380     if (ShuffleKind == 1) // Unary
1381       return isVMerge(N, indexOffset, 0);
1382     else if (ShuffleKind == 0) // Normal
1383       return isVMerge(N, indexOffset, 16);
1384     else
1385       return false;
1386   }
1387   return false;
1388 }
1389
1390 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1391 /// amount, otherwise return -1.
1392 /// The ShuffleKind distinguishes between big-endian operations with two
1393 /// different inputs (0), either-endian operations with two identical inputs
1394 /// (1), and little-endian operations with two different inputs (2).  For the
1395 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1396 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1397                              SelectionDAG &DAG) {
1398   if (N->getValueType(0) != MVT::v16i8)
1399     return -1;
1400
1401   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1402
1403   // Find the first non-undef value in the shuffle mask.
1404   unsigned i;
1405   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1406     /*search*/;
1407
1408   if (i == 16) return -1;  // all undef.
1409
1410   // Otherwise, check to see if the rest of the elements are consecutively
1411   // numbered from this value.
1412   unsigned ShiftAmt = SVOp->getMaskElt(i);
1413   if (ShiftAmt < i) return -1;
1414
1415   ShiftAmt -= i;
1416   bool isLE = DAG.getDataLayout().isLittleEndian();
1417
1418   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1419     // Check the rest of the elements to see if they are consecutive.
1420     for (++i; i != 16; ++i)
1421       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1422         return -1;
1423   } else if (ShuffleKind == 1) {
1424     // Check the rest of the elements to see if they are consecutive.
1425     for (++i; i != 16; ++i)
1426       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1427         return -1;
1428   } else
1429     return -1;
1430
1431   if (isLE)
1432     ShiftAmt = 16 - ShiftAmt;
1433
1434   return ShiftAmt;
1435 }
1436
1437 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1438 /// specifies a splat of a single element that is suitable for input to
1439 /// VSPLTB/VSPLTH/VSPLTW.
1440 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1441   assert(N->getValueType(0) == MVT::v16i8 &&
1442          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1443
1444   // The consecutive indices need to specify an element, not part of two
1445   // different elements.  So abandon ship early if this isn't the case.
1446   if (N->getMaskElt(0) % EltSize != 0)
1447     return false;
1448
1449   // This is a splat operation if each element of the permute is the same, and
1450   // if the value doesn't reference the second vector.
1451   unsigned ElementBase = N->getMaskElt(0);
1452
1453   // FIXME: Handle UNDEF elements too!
1454   if (ElementBase >= 16)
1455     return false;
1456
1457   // Check that the indices are consecutive, in the case of a multi-byte element
1458   // splatted with a v16i8 mask.
1459   for (unsigned i = 1; i != EltSize; ++i)
1460     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1461       return false;
1462
1463   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1464     if (N->getMaskElt(i) < 0) continue;
1465     for (unsigned j = 0; j != EltSize; ++j)
1466       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1467         return false;
1468   }
1469   return true;
1470 }
1471
1472 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1473 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1474 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1475                                 SelectionDAG &DAG) {
1476   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1477   assert(isSplatShuffleMask(SVOp, EltSize));
1478   if (DAG.getDataLayout().isLittleEndian())
1479     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1480   else
1481     return SVOp->getMaskElt(0) / EltSize;
1482 }
1483
1484 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1485 /// by using a vspltis[bhw] instruction of the specified element size, return
1486 /// the constant being splatted.  The ByteSize field indicates the number of
1487 /// bytes of each element [124] -> [bhw].
1488 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1489   SDValue OpVal(nullptr, 0);
1490
1491   // If ByteSize of the splat is bigger than the element size of the
1492   // build_vector, then we have a case where we are checking for a splat where
1493   // multiple elements of the buildvector are folded together into a single
1494   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1495   unsigned EltSize = 16/N->getNumOperands();
1496   if (EltSize < ByteSize) {
1497     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1498     SDValue UniquedVals[4];
1499     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1500
1501     // See if all of the elements in the buildvector agree across.
1502     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1503       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1504       // If the element isn't a constant, bail fully out.
1505       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1506
1507
1508       if (!UniquedVals[i&(Multiple-1)].getNode())
1509         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1510       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1511         return SDValue();  // no match.
1512     }
1513
1514     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1515     // either constant or undef values that are identical for each chunk.  See
1516     // if these chunks can form into a larger vspltis*.
1517
1518     // Check to see if all of the leading entries are either 0 or -1.  If
1519     // neither, then this won't fit into the immediate field.
1520     bool LeadingZero = true;
1521     bool LeadingOnes = true;
1522     for (unsigned i = 0; i != Multiple-1; ++i) {
1523       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1524
1525       LeadingZero &= isNullConstant(UniquedVals[i]);
1526       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1527     }
1528     // Finally, check the least significant entry.
1529     if (LeadingZero) {
1530       if (!UniquedVals[Multiple-1].getNode())
1531         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1532       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1533       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1534         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1535     }
1536     if (LeadingOnes) {
1537       if (!UniquedVals[Multiple-1].getNode())
1538         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1539       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1540       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1541         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1542     }
1543
1544     return SDValue();
1545   }
1546
1547   // Check to see if this buildvec has a single non-undef value in its elements.
1548   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1549     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1550     if (!OpVal.getNode())
1551       OpVal = N->getOperand(i);
1552     else if (OpVal != N->getOperand(i))
1553       return SDValue();
1554   }
1555
1556   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1557
1558   unsigned ValSizeInBytes = EltSize;
1559   uint64_t Value = 0;
1560   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1561     Value = CN->getZExtValue();
1562   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1563     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1564     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1565   }
1566
1567   // If the splat value is larger than the element value, then we can never do
1568   // this splat.  The only case that we could fit the replicated bits into our
1569   // immediate field for would be zero, and we prefer to use vxor for it.
1570   if (ValSizeInBytes < ByteSize) return SDValue();
1571
1572   // If the element value is larger than the splat value, check if it consists
1573   // of a repeated bit pattern of size ByteSize.
1574   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1575     return SDValue();
1576
1577   // Properly sign extend the value.
1578   int MaskVal = SignExtend32(Value, ByteSize * 8);
1579
1580   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1581   if (MaskVal == 0) return SDValue();
1582
1583   // Finally, if this value fits in a 5 bit sext field, return it
1584   if (SignExtend32<5>(MaskVal) == MaskVal)
1585     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1586   return SDValue();
1587 }
1588
1589 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1590 /// amount, otherwise return -1.
1591 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1592   EVT VT = N->getValueType(0);
1593   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1594     return -1;
1595
1596   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1597
1598   // Find the first non-undef value in the shuffle mask.
1599   unsigned i;
1600   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1601     /*search*/;
1602
1603   if (i == 4) return -1;  // all undef.
1604
1605   // Otherwise, check to see if the rest of the elements are consecutively
1606   // numbered from this value.
1607   unsigned ShiftAmt = SVOp->getMaskElt(i);
1608   if (ShiftAmt < i) return -1;
1609   ShiftAmt -= i;
1610
1611   // Check the rest of the elements to see if they are consecutive.
1612   for (++i; i != 4; ++i)
1613     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1614       return -1;
1615
1616   return ShiftAmt;
1617 }
1618
1619 //===----------------------------------------------------------------------===//
1620 //  Addressing Mode Selection
1621 //===----------------------------------------------------------------------===//
1622
1623 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1624 /// or 64-bit immediate, and if the value can be accurately represented as a
1625 /// sign extension from a 16-bit value.  If so, this returns true and the
1626 /// immediate.
1627 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1628   if (!isa<ConstantSDNode>(N))
1629     return false;
1630
1631   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1632   if (N->getValueType(0) == MVT::i32)
1633     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1634   else
1635     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1636 }
1637 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1638   return isIntS16Immediate(Op.getNode(), Imm);
1639 }
1640
1641 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1642 /// can be represented as an indexed [r+r] operation.  Returns false if it
1643 /// can be more efficiently represented with [r+imm].
1644 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1645                                             SDValue &Index,
1646                                             SelectionDAG &DAG) const {
1647   short imm = 0;
1648   if (N.getOpcode() == ISD::ADD) {
1649     if (isIntS16Immediate(N.getOperand(1), imm))
1650       return false;    // r+i
1651     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1652       return false;    // r+i
1653
1654     Base = N.getOperand(0);
1655     Index = N.getOperand(1);
1656     return true;
1657   } else if (N.getOpcode() == ISD::OR) {
1658     if (isIntS16Immediate(N.getOperand(1), imm))
1659       return false;    // r+i can fold it if we can.
1660
1661     // If this is an or of disjoint bitfields, we can codegen this as an add
1662     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1663     // disjoint.
1664     APInt LHSKnownZero, LHSKnownOne;
1665     APInt RHSKnownZero, RHSKnownOne;
1666     DAG.computeKnownBits(N.getOperand(0),
1667                          LHSKnownZero, LHSKnownOne);
1668
1669     if (LHSKnownZero.getBoolValue()) {
1670       DAG.computeKnownBits(N.getOperand(1),
1671                            RHSKnownZero, RHSKnownOne);
1672       // If all of the bits are known zero on the LHS or RHS, the add won't
1673       // carry.
1674       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1675         Base = N.getOperand(0);
1676         Index = N.getOperand(1);
1677         return true;
1678       }
1679     }
1680   }
1681
1682   return false;
1683 }
1684
1685 // If we happen to be doing an i64 load or store into a stack slot that has
1686 // less than a 4-byte alignment, then the frame-index elimination may need to
1687 // use an indexed load or store instruction (because the offset may not be a
1688 // multiple of 4). The extra register needed to hold the offset comes from the
1689 // register scavenger, and it is possible that the scavenger will need to use
1690 // an emergency spill slot. As a result, we need to make sure that a spill slot
1691 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1692 // stack slot.
1693 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1694   // FIXME: This does not handle the LWA case.
1695   if (VT != MVT::i64)
1696     return;
1697
1698   // NOTE: We'll exclude negative FIs here, which come from argument
1699   // lowering, because there are no known test cases triggering this problem
1700   // using packed structures (or similar). We can remove this exclusion if
1701   // we find such a test case. The reason why this is so test-case driven is
1702   // because this entire 'fixup' is only to prevent crashes (from the
1703   // register scavenger) on not-really-valid inputs. For example, if we have:
1704   //   %a = alloca i1
1705   //   %b = bitcast i1* %a to i64*
1706   //   store i64* a, i64 b
1707   // then the store should really be marked as 'align 1', but is not. If it
1708   // were marked as 'align 1' then the indexed form would have been
1709   // instruction-selected initially, and the problem this 'fixup' is preventing
1710   // won't happen regardless.
1711   if (FrameIdx < 0)
1712     return;
1713
1714   MachineFunction &MF = DAG.getMachineFunction();
1715   MachineFrameInfo *MFI = MF.getFrameInfo();
1716
1717   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1718   if (Align >= 4)
1719     return;
1720
1721   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1722   FuncInfo->setHasNonRISpills();
1723 }
1724
1725 /// Returns true if the address N can be represented by a base register plus
1726 /// a signed 16-bit displacement [r+imm], and if it is not better
1727 /// represented as reg+reg.  If Aligned is true, only accept displacements
1728 /// suitable for STD and friends, i.e. multiples of 4.
1729 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1730                                             SDValue &Base,
1731                                             SelectionDAG &DAG,
1732                                             bool Aligned) const {
1733   // FIXME dl should come from parent load or store, not from address
1734   SDLoc dl(N);
1735   // If this can be more profitably realized as r+r, fail.
1736   if (SelectAddressRegReg(N, Disp, Base, DAG))
1737     return false;
1738
1739   if (N.getOpcode() == ISD::ADD) {
1740     short imm = 0;
1741     if (isIntS16Immediate(N.getOperand(1), imm) &&
1742         (!Aligned || (imm & 3) == 0)) {
1743       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1744       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1745         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1746         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1747       } else {
1748         Base = N.getOperand(0);
1749       }
1750       return true; // [r+i]
1751     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1752       // Match LOAD (ADD (X, Lo(G))).
1753       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1754              && "Cannot handle constant offsets yet!");
1755       Disp = N.getOperand(1).getOperand(0);  // The global address.
1756       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1757              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1758              Disp.getOpcode() == ISD::TargetConstantPool ||
1759              Disp.getOpcode() == ISD::TargetJumpTable);
1760       Base = N.getOperand(0);
1761       return true;  // [&g+r]
1762     }
1763   } else if (N.getOpcode() == ISD::OR) {
1764     short imm = 0;
1765     if (isIntS16Immediate(N.getOperand(1), imm) &&
1766         (!Aligned || (imm & 3) == 0)) {
1767       // If this is an or of disjoint bitfields, we can codegen this as an add
1768       // (for better address arithmetic) if the LHS and RHS of the OR are
1769       // provably disjoint.
1770       APInt LHSKnownZero, LHSKnownOne;
1771       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1772
1773       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1774         // If all of the bits are known zero on the LHS or RHS, the add won't
1775         // carry.
1776         if (FrameIndexSDNode *FI =
1777               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1778           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1779           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1780         } else {
1781           Base = N.getOperand(0);
1782         }
1783         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1784         return true;
1785       }
1786     }
1787   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1788     // Loading from a constant address.
1789
1790     // If this address fits entirely in a 16-bit sext immediate field, codegen
1791     // this as "d, 0"
1792     short Imm;
1793     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1794       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1795       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1796                              CN->getValueType(0));
1797       return true;
1798     }
1799
1800     // Handle 32-bit sext immediates with LIS + addr mode.
1801     if ((CN->getValueType(0) == MVT::i32 ||
1802          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1803         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1804       int Addr = (int)CN->getZExtValue();
1805
1806       // Otherwise, break this down into an LIS + disp.
1807       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1808
1809       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1810                                    MVT::i32);
1811       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1812       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1813       return true;
1814     }
1815   }
1816
1817   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
1818   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1819     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1820     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1821   } else
1822     Base = N;
1823   return true;      // [r+0]
1824 }
1825
1826 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1827 /// represented as an indexed [r+r] operation.
1828 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1829                                                 SDValue &Index,
1830                                                 SelectionDAG &DAG) const {
1831   // Check to see if we can easily represent this as an [r+r] address.  This
1832   // will fail if it thinks that the address is more profitably represented as
1833   // reg+imm, e.g. where imm = 0.
1834   if (SelectAddressRegReg(N, Base, Index, DAG))
1835     return true;
1836
1837   // If the operand is an addition, always emit this as [r+r], since this is
1838   // better (for code size, and execution, as the memop does the add for free)
1839   // than emitting an explicit add.
1840   if (N.getOpcode() == ISD::ADD) {
1841     Base = N.getOperand(0);
1842     Index = N.getOperand(1);
1843     return true;
1844   }
1845
1846   // Otherwise, do it the hard way, using R0 as the base register.
1847   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1848                          N.getValueType());
1849   Index = N;
1850   return true;
1851 }
1852
1853 /// getPreIndexedAddressParts - returns true by value, base pointer and
1854 /// offset pointer and addressing mode by reference if the node's address
1855 /// can be legally represented as pre-indexed load / store address.
1856 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1857                                                   SDValue &Offset,
1858                                                   ISD::MemIndexedMode &AM,
1859                                                   SelectionDAG &DAG) const {
1860   if (DisablePPCPreinc) return false;
1861
1862   bool isLoad = true;
1863   SDValue Ptr;
1864   EVT VT;
1865   unsigned Alignment;
1866   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1867     Ptr = LD->getBasePtr();
1868     VT = LD->getMemoryVT();
1869     Alignment = LD->getAlignment();
1870   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1871     Ptr = ST->getBasePtr();
1872     VT  = ST->getMemoryVT();
1873     Alignment = ST->getAlignment();
1874     isLoad = false;
1875   } else
1876     return false;
1877
1878   // PowerPC doesn't have preinc load/store instructions for vectors (except
1879   // for QPX, which does have preinc r+r forms).
1880   if (VT.isVector()) {
1881     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1882       return false;
1883     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1884       AM = ISD::PRE_INC;
1885       return true;
1886     }
1887   }
1888
1889   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1890
1891     // Common code will reject creating a pre-inc form if the base pointer
1892     // is a frame index, or if N is a store and the base pointer is either
1893     // the same as or a predecessor of the value being stored.  Check for
1894     // those situations here, and try with swapped Base/Offset instead.
1895     bool Swap = false;
1896
1897     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1898       Swap = true;
1899     else if (!isLoad) {
1900       SDValue Val = cast<StoreSDNode>(N)->getValue();
1901       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1902         Swap = true;
1903     }
1904
1905     if (Swap)
1906       std::swap(Base, Offset);
1907
1908     AM = ISD::PRE_INC;
1909     return true;
1910   }
1911
1912   // LDU/STU can only handle immediates that are a multiple of 4.
1913   if (VT != MVT::i64) {
1914     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1915       return false;
1916   } else {
1917     // LDU/STU need an address with at least 4-byte alignment.
1918     if (Alignment < 4)
1919       return false;
1920
1921     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1922       return false;
1923   }
1924
1925   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1926     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1927     // sext i32 to i64 when addr mode is r+i.
1928     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1929         LD->getExtensionType() == ISD::SEXTLOAD &&
1930         isa<ConstantSDNode>(Offset))
1931       return false;
1932   }
1933
1934   AM = ISD::PRE_INC;
1935   return true;
1936 }
1937
1938 //===----------------------------------------------------------------------===//
1939 //  LowerOperation implementation
1940 //===----------------------------------------------------------------------===//
1941
1942 /// GetLabelAccessInfo - Return true if we should reference labels using a
1943 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1944 static bool GetLabelAccessInfo(const TargetMachine &TM,
1945                                const PPCSubtarget &Subtarget,
1946                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1947                                const GlobalValue *GV = nullptr) {
1948   HiOpFlags = PPCII::MO_HA;
1949   LoOpFlags = PPCII::MO_LO;
1950
1951   // Don't use the pic base if not in PIC relocation model.
1952   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1953
1954   if (isPIC) {
1955     HiOpFlags |= PPCII::MO_PIC_FLAG;
1956     LoOpFlags |= PPCII::MO_PIC_FLAG;
1957   }
1958
1959   // If this is a reference to a global value that requires a non-lazy-ptr, make
1960   // sure that instruction lowering adds it.
1961   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1962     HiOpFlags |= PPCII::MO_NLP_FLAG;
1963     LoOpFlags |= PPCII::MO_NLP_FLAG;
1964
1965     if (GV->hasHiddenVisibility()) {
1966       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1967       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1968     }
1969   }
1970
1971   return isPIC;
1972 }
1973
1974 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1975                              SelectionDAG &DAG) {
1976   SDLoc DL(HiPart);
1977   EVT PtrVT = HiPart.getValueType();
1978   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1979
1980   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1981   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1982
1983   // With PIC, the first instruction is actually "GR+hi(&G)".
1984   if (isPIC)
1985     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1986                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1987
1988   // Generate non-pic code that has direct accesses to the constant pool.
1989   // The address of the global is just (hi(&g)+lo(&g)).
1990   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1991 }
1992
1993 static void setUsesTOCBasePtr(MachineFunction &MF) {
1994   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1995   FuncInfo->setUsesTOCBasePtr();
1996 }
1997
1998 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1999   setUsesTOCBasePtr(DAG.getMachineFunction());
2000 }
2001
2002 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
2003                            SDValue GA) {
2004   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2005   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2006                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2007
2008   SDValue Ops[] = { GA, Reg };
2009   return DAG.getMemIntrinsicNode(
2010       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2011       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2012       false, 0);
2013 }
2014
2015 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2016                                              SelectionDAG &DAG) const {
2017   EVT PtrVT = Op.getValueType();
2018   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2019   const Constant *C = CP->getConstVal();
2020
2021   // 64-bit SVR4 ABI code is always position-independent.
2022   // The actual address of the GlobalValue is stored in the TOC.
2023   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2024     setUsesTOCBasePtr(DAG);
2025     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2026     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2027   }
2028
2029   unsigned MOHiFlag, MOLoFlag;
2030   bool isPIC =
2031       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2032
2033   if (isPIC && Subtarget.isSVR4ABI()) {
2034     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2035                                            PPCII::MO_PIC_FLAG);
2036     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2037   }
2038
2039   SDValue CPIHi =
2040     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2041   SDValue CPILo =
2042     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2043   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
2044 }
2045
2046 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2047   EVT PtrVT = Op.getValueType();
2048   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2049
2050   // 64-bit SVR4 ABI code is always position-independent.
2051   // The actual address of the GlobalValue is stored in the TOC.
2052   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2053     setUsesTOCBasePtr(DAG);
2054     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2055     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2056   }
2057
2058   unsigned MOHiFlag, MOLoFlag;
2059   bool isPIC =
2060       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2061
2062   if (isPIC && Subtarget.isSVR4ABI()) {
2063     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2064                                         PPCII::MO_PIC_FLAG);
2065     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2066   }
2067
2068   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2069   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2070   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
2071 }
2072
2073 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2074                                              SelectionDAG &DAG) const {
2075   EVT PtrVT = Op.getValueType();
2076   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2077   const BlockAddress *BA = BASDN->getBlockAddress();
2078
2079   // 64-bit SVR4 ABI code is always position-independent.
2080   // The actual BlockAddress is stored in the TOC.
2081   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2082     setUsesTOCBasePtr(DAG);
2083     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2084     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2085   }
2086
2087   unsigned MOHiFlag, MOLoFlag;
2088   bool isPIC =
2089       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
2090   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2091   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2092   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
2093 }
2094
2095 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2096                                               SelectionDAG &DAG) const {
2097
2098   // FIXME: TLS addresses currently use medium model code sequences,
2099   // which is the most useful form.  Eventually support for small and
2100   // large models could be added if users need it, at the cost of
2101   // additional complexity.
2102   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2103   if (DAG.getTarget().Options.EmulatedTLS)
2104     return LowerToTLSEmulatedModel(GA, DAG);
2105
2106   SDLoc dl(GA);
2107   const GlobalValue *GV = GA->getGlobal();
2108   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2109   bool is64bit = Subtarget.isPPC64();
2110   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2111   PICLevel::Level picLevel = M->getPICLevel();
2112
2113   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2114
2115   if (Model == TLSModel::LocalExec) {
2116     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2117                                                PPCII::MO_TPREL_HA);
2118     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2119                                                PPCII::MO_TPREL_LO);
2120     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2121                                      is64bit ? MVT::i64 : MVT::i32);
2122     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2123     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2124   }
2125
2126   if (Model == TLSModel::InitialExec) {
2127     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2128     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2129                                                 PPCII::MO_TLS);
2130     SDValue GOTPtr;
2131     if (is64bit) {
2132       setUsesTOCBasePtr(DAG);
2133       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2134       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2135                            PtrVT, GOTReg, TGA);
2136     } else
2137       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2138     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2139                                    PtrVT, TGA, GOTPtr);
2140     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2141   }
2142
2143   if (Model == TLSModel::GeneralDynamic) {
2144     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2145     SDValue GOTPtr;
2146     if (is64bit) {
2147       setUsesTOCBasePtr(DAG);
2148       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2149       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2150                                    GOTReg, TGA);
2151     } else {
2152       if (picLevel == PICLevel::Small)
2153         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2154       else
2155         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2156     }
2157     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2158                        GOTPtr, TGA, TGA);
2159   }
2160
2161   if (Model == TLSModel::LocalDynamic) {
2162     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2163     SDValue GOTPtr;
2164     if (is64bit) {
2165       setUsesTOCBasePtr(DAG);
2166       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2167       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2168                            GOTReg, TGA);
2169     } else {
2170       if (picLevel == PICLevel::Small)
2171         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2172       else
2173         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2174     }
2175     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2176                                   PtrVT, GOTPtr, TGA, TGA);
2177     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2178                                       PtrVT, TLSAddr, TGA);
2179     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2180   }
2181
2182   llvm_unreachable("Unknown TLS model!");
2183 }
2184
2185 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2186                                               SelectionDAG &DAG) const {
2187   EVT PtrVT = Op.getValueType();
2188   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2189   SDLoc DL(GSDN);
2190   const GlobalValue *GV = GSDN->getGlobal();
2191
2192   // 64-bit SVR4 ABI code is always position-independent.
2193   // The actual address of the GlobalValue is stored in the TOC.
2194   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2195     setUsesTOCBasePtr(DAG);
2196     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2197     return getTOCEntry(DAG, DL, true, GA);
2198   }
2199
2200   unsigned MOHiFlag, MOLoFlag;
2201   bool isPIC =
2202       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2203
2204   if (isPIC && Subtarget.isSVR4ABI()) {
2205     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2206                                             GSDN->getOffset(),
2207                                             PPCII::MO_PIC_FLAG);
2208     return getTOCEntry(DAG, DL, false, GA);
2209   }
2210
2211   SDValue GAHi =
2212     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2213   SDValue GALo =
2214     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2215
2216   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2217
2218   // If the global reference is actually to a non-lazy-pointer, we have to do an
2219   // extra load to get the address of the global.
2220   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2221     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2222                       false, false, false, 0);
2223   return Ptr;
2224 }
2225
2226 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2227   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2228   SDLoc dl(Op);
2229
2230   if (Op.getValueType() == MVT::v2i64) {
2231     // When the operands themselves are v2i64 values, we need to do something
2232     // special because VSX has no underlying comparison operations for these.
2233     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2234       // Equality can be handled by casting to the legal type for Altivec
2235       // comparisons, everything else needs to be expanded.
2236       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2237         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2238                  DAG.getSetCC(dl, MVT::v4i32,
2239                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2240                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2241                    CC));
2242       }
2243
2244       return SDValue();
2245     }
2246
2247     // We handle most of these in the usual way.
2248     return Op;
2249   }
2250
2251   // If we're comparing for equality to zero, expose the fact that this is
2252   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2253   // fold the new nodes.
2254   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2255     if (C->isNullValue() && CC == ISD::SETEQ) {
2256       EVT VT = Op.getOperand(0).getValueType();
2257       SDValue Zext = Op.getOperand(0);
2258       if (VT.bitsLT(MVT::i32)) {
2259         VT = MVT::i32;
2260         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2261       }
2262       unsigned Log2b = Log2_32(VT.getSizeInBits());
2263       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2264       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2265                                 DAG.getConstant(Log2b, dl, MVT::i32));
2266       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2267     }
2268     // Leave comparisons against 0 and -1 alone for now, since they're usually
2269     // optimized.  FIXME: revisit this when we can custom lower all setcc
2270     // optimizations.
2271     if (C->isAllOnesValue() || C->isNullValue())
2272       return SDValue();
2273   }
2274
2275   // If we have an integer seteq/setne, turn it into a compare against zero
2276   // by xor'ing the rhs with the lhs, which is faster than setting a
2277   // condition register, reading it back out, and masking the correct bit.  The
2278   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2279   // the result to other bit-twiddling opportunities.
2280   EVT LHSVT = Op.getOperand(0).getValueType();
2281   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2282     EVT VT = Op.getValueType();
2283     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2284                                 Op.getOperand(1));
2285     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2286   }
2287   return SDValue();
2288 }
2289
2290 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2291                                       const PPCSubtarget &Subtarget) const {
2292   SDNode *Node = Op.getNode();
2293   EVT VT = Node->getValueType(0);
2294   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2295   SDValue InChain = Node->getOperand(0);
2296   SDValue VAListPtr = Node->getOperand(1);
2297   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2298   SDLoc dl(Node);
2299
2300   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2301
2302   // gpr_index
2303   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2304                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2305                                     false, false, false, 0);
2306   InChain = GprIndex.getValue(1);
2307
2308   if (VT == MVT::i64) {
2309     // Check if GprIndex is even
2310     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2311                                  DAG.getConstant(1, dl, MVT::i32));
2312     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2313                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2314     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2315                                           DAG.getConstant(1, dl, MVT::i32));
2316     // Align GprIndex to be even if it isn't
2317     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2318                            GprIndex);
2319   }
2320
2321   // fpr index is 1 byte after gpr
2322   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2323                                DAG.getConstant(1, dl, MVT::i32));
2324
2325   // fpr
2326   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2327                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2328                                     false, false, false, 0);
2329   InChain = FprIndex.getValue(1);
2330
2331   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2332                                        DAG.getConstant(8, dl, MVT::i32));
2333
2334   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2335                                         DAG.getConstant(4, dl, MVT::i32));
2336
2337   // areas
2338   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2339                                      MachinePointerInfo(), false, false,
2340                                      false, 0);
2341   InChain = OverflowArea.getValue(1);
2342
2343   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2344                                     MachinePointerInfo(), false, false,
2345                                     false, 0);
2346   InChain = RegSaveArea.getValue(1);
2347
2348   // select overflow_area if index > 8
2349   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2350                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2351
2352   // adjustment constant gpr_index * 4/8
2353   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2354                                     VT.isInteger() ? GprIndex : FprIndex,
2355                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2356                                                     MVT::i32));
2357
2358   // OurReg = RegSaveArea + RegConstant
2359   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2360                                RegConstant);
2361
2362   // Floating types are 32 bytes into RegSaveArea
2363   if (VT.isFloatingPoint())
2364     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2365                          DAG.getConstant(32, dl, MVT::i32));
2366
2367   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2368   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2369                                    VT.isInteger() ? GprIndex : FprIndex,
2370                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2371                                                    MVT::i32));
2372
2373   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2374                               VT.isInteger() ? VAListPtr : FprPtr,
2375                               MachinePointerInfo(SV),
2376                               MVT::i8, false, false, 0);
2377
2378   // determine if we should load from reg_save_area or overflow_area
2379   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2380
2381   // increase overflow_area by 4/8 if gpr/fpr > 8
2382   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2383                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2384                                           dl, MVT::i32));
2385
2386   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2387                              OverflowAreaPlusN);
2388
2389   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2390                               OverflowAreaPtr,
2391                               MachinePointerInfo(),
2392                               MVT::i32, false, false, 0);
2393
2394   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2395                      false, false, false, 0);
2396 }
2397
2398 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2399                                        const PPCSubtarget &Subtarget) const {
2400   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2401
2402   // We have to copy the entire va_list struct:
2403   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2404   return DAG.getMemcpy(Op.getOperand(0), Op,
2405                        Op.getOperand(1), Op.getOperand(2),
2406                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2407                        false, MachinePointerInfo(), MachinePointerInfo());
2408 }
2409
2410 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2411                                                   SelectionDAG &DAG) const {
2412   return Op.getOperand(0);
2413 }
2414
2415 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2416                                                 SelectionDAG &DAG) const {
2417   SDValue Chain = Op.getOperand(0);
2418   SDValue Trmp = Op.getOperand(1); // trampoline
2419   SDValue FPtr = Op.getOperand(2); // nested function
2420   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2421   SDLoc dl(Op);
2422
2423   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2424   bool isPPC64 = (PtrVT == MVT::i64);
2425   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2426
2427   TargetLowering::ArgListTy Args;
2428   TargetLowering::ArgListEntry Entry;
2429
2430   Entry.Ty = IntPtrTy;
2431   Entry.Node = Trmp; Args.push_back(Entry);
2432
2433   // TrampSize == (isPPC64 ? 48 : 40);
2434   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2435                                isPPC64 ? MVT::i64 : MVT::i32);
2436   Args.push_back(Entry);
2437
2438   Entry.Node = FPtr; Args.push_back(Entry);
2439   Entry.Node = Nest; Args.push_back(Entry);
2440
2441   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2442   TargetLowering::CallLoweringInfo CLI(DAG);
2443   CLI.setDebugLoc(dl).setChain(Chain)
2444     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2445                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2446                std::move(Args), 0);
2447
2448   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2449   return CallResult.second;
2450 }
2451
2452 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2453                                         const PPCSubtarget &Subtarget) const {
2454   MachineFunction &MF = DAG.getMachineFunction();
2455   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2456
2457   SDLoc dl(Op);
2458
2459   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2460     // vastart just stores the address of the VarArgsFrameIndex slot into the
2461     // memory location argument.
2462     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2463     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2464     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2465     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2466                         MachinePointerInfo(SV),
2467                         false, false, 0);
2468   }
2469
2470   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2471   // We suppose the given va_list is already allocated.
2472   //
2473   // typedef struct {
2474   //  char gpr;     /* index into the array of 8 GPRs
2475   //                 * stored in the register save area
2476   //                 * gpr=0 corresponds to r3,
2477   //                 * gpr=1 to r4, etc.
2478   //                 */
2479   //  char fpr;     /* index into the array of 8 FPRs
2480   //                 * stored in the register save area
2481   //                 * fpr=0 corresponds to f1,
2482   //                 * fpr=1 to f2, etc.
2483   //                 */
2484   //  char *overflow_arg_area;
2485   //                /* location on stack that holds
2486   //                 * the next overflow argument
2487   //                 */
2488   //  char *reg_save_area;
2489   //               /* where r3:r10 and f1:f8 (if saved)
2490   //                * are stored
2491   //                */
2492   // } va_list[1];
2493
2494   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2495   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2496
2497   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2498
2499   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2500                                             PtrVT);
2501   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2502                                  PtrVT);
2503
2504   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2505   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2506
2507   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2508   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2509
2510   uint64_t FPROffset = 1;
2511   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2512
2513   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2514
2515   // Store first byte : number of int regs
2516   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2517                                          Op.getOperand(1),
2518                                          MachinePointerInfo(SV),
2519                                          MVT::i8, false, false, 0);
2520   uint64_t nextOffset = FPROffset;
2521   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2522                                   ConstFPROffset);
2523
2524   // Store second byte : number of float regs
2525   SDValue secondStore =
2526     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2527                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2528                       false, false, 0);
2529   nextOffset += StackOffset;
2530   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2531
2532   // Store second word : arguments given on stack
2533   SDValue thirdStore =
2534     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2535                  MachinePointerInfo(SV, nextOffset),
2536                  false, false, 0);
2537   nextOffset += FrameOffset;
2538   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2539
2540   // Store third word : arguments given in registers
2541   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2542                       MachinePointerInfo(SV, nextOffset),
2543                       false, false, 0);
2544
2545 }
2546
2547 #include "PPCGenCallingConv.inc"
2548
2549 // Function whose sole purpose is to kill compiler warnings
2550 // stemming from unused functions included from PPCGenCallingConv.inc.
2551 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2552   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2553 }
2554
2555 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2556                                       CCValAssign::LocInfo &LocInfo,
2557                                       ISD::ArgFlagsTy &ArgFlags,
2558                                       CCState &State) {
2559   return true;
2560 }
2561
2562 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2563                                              MVT &LocVT,
2564                                              CCValAssign::LocInfo &LocInfo,
2565                                              ISD::ArgFlagsTy &ArgFlags,
2566                                              CCState &State) {
2567   static const MCPhysReg ArgRegs[] = {
2568     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2569     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2570   };
2571   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2572
2573   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2574
2575   // Skip one register if the first unallocated register has an even register
2576   // number and there are still argument registers available which have not been
2577   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2578   // need to skip a register if RegNum is odd.
2579   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2580     State.AllocateReg(ArgRegs[RegNum]);
2581   }
2582
2583   // Always return false here, as this function only makes sure that the first
2584   // unallocated register has an odd register number and does not actually
2585   // allocate a register for the current argument.
2586   return false;
2587 }
2588
2589 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2590                                                MVT &LocVT,
2591                                                CCValAssign::LocInfo &LocInfo,
2592                                                ISD::ArgFlagsTy &ArgFlags,
2593                                                CCState &State) {
2594   static const MCPhysReg ArgRegs[] = {
2595     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2596     PPC::F8
2597   };
2598
2599   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2600
2601   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2602
2603   // If there is only one Floating-point register left we need to put both f64
2604   // values of a split ppc_fp128 value on the stack.
2605   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2606     State.AllocateReg(ArgRegs[RegNum]);
2607   }
2608
2609   // Always return false here, as this function only makes sure that the two f64
2610   // values a ppc_fp128 value is split into are both passed in registers or both
2611   // passed on the stack and does not actually allocate a register for the
2612   // current argument.
2613   return false;
2614 }
2615
2616 /// FPR - The set of FP registers that should be allocated for arguments,
2617 /// on Darwin.
2618 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2619                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2620                                 PPC::F11, PPC::F12, PPC::F13};
2621
2622 /// QFPR - The set of QPX registers that should be allocated for arguments.
2623 static const MCPhysReg QFPR[] = {
2624     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2625     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2626
2627 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2628 /// the stack.
2629 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2630                                        unsigned PtrByteSize) {
2631   unsigned ArgSize = ArgVT.getStoreSize();
2632   if (Flags.isByVal())
2633     ArgSize = Flags.getByValSize();
2634
2635   // Round up to multiples of the pointer size, except for array members,
2636   // which are always packed.
2637   if (!Flags.isInConsecutiveRegs())
2638     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2639
2640   return ArgSize;
2641 }
2642
2643 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2644 /// on the stack.
2645 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2646                                             ISD::ArgFlagsTy Flags,
2647                                             unsigned PtrByteSize) {
2648   unsigned Align = PtrByteSize;
2649
2650   // Altivec parameters are padded to a 16 byte boundary.
2651   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2652       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2653       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2654       ArgVT == MVT::v1i128)
2655     Align = 16;
2656   // QPX vector types stored in double-precision are padded to a 32 byte
2657   // boundary.
2658   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2659     Align = 32;
2660
2661   // ByVal parameters are aligned as requested.
2662   if (Flags.isByVal()) {
2663     unsigned BVAlign = Flags.getByValAlign();
2664     if (BVAlign > PtrByteSize) {
2665       if (BVAlign % PtrByteSize != 0)
2666           llvm_unreachable(
2667             "ByVal alignment is not a multiple of the pointer size");
2668
2669       Align = BVAlign;
2670     }
2671   }
2672
2673   // Array members are always packed to their original alignment.
2674   if (Flags.isInConsecutiveRegs()) {
2675     // If the array member was split into multiple registers, the first
2676     // needs to be aligned to the size of the full type.  (Except for
2677     // ppcf128, which is only aligned as its f64 components.)
2678     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2679       Align = OrigVT.getStoreSize();
2680     else
2681       Align = ArgVT.getStoreSize();
2682   }
2683
2684   return Align;
2685 }
2686
2687 /// CalculateStackSlotUsed - Return whether this argument will use its
2688 /// stack slot (instead of being passed in registers).  ArgOffset,
2689 /// AvailableFPRs, and AvailableVRs must hold the current argument
2690 /// position, and will be updated to account for this argument.
2691 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2692                                    ISD::ArgFlagsTy Flags,
2693                                    unsigned PtrByteSize,
2694                                    unsigned LinkageSize,
2695                                    unsigned ParamAreaSize,
2696                                    unsigned &ArgOffset,
2697                                    unsigned &AvailableFPRs,
2698                                    unsigned &AvailableVRs, bool HasQPX) {
2699   bool UseMemory = false;
2700
2701   // Respect alignment of argument on the stack.
2702   unsigned Align =
2703     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2704   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2705   // If there's no space left in the argument save area, we must
2706   // use memory (this check also catches zero-sized arguments).
2707   if (ArgOffset >= LinkageSize + ParamAreaSize)
2708     UseMemory = true;
2709
2710   // Allocate argument on the stack.
2711   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2712   if (Flags.isInConsecutiveRegsLast())
2713     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2714   // If we overran the argument save area, we must use memory
2715   // (this check catches arguments passed partially in memory)
2716   if (ArgOffset > LinkageSize + ParamAreaSize)
2717     UseMemory = true;
2718
2719   // However, if the argument is actually passed in an FPR or a VR,
2720   // we don't use memory after all.
2721   if (!Flags.isByVal()) {
2722     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2723         // QPX registers overlap with the scalar FP registers.
2724         (HasQPX && (ArgVT == MVT::v4f32 ||
2725                     ArgVT == MVT::v4f64 ||
2726                     ArgVT == MVT::v4i1)))
2727       if (AvailableFPRs > 0) {
2728         --AvailableFPRs;
2729         return false;
2730       }
2731     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2732         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2733         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2734         ArgVT == MVT::v1i128)
2735       if (AvailableVRs > 0) {
2736         --AvailableVRs;
2737         return false;
2738       }
2739   }
2740
2741   return UseMemory;
2742 }
2743
2744 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2745 /// ensure minimum alignment required for target.
2746 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2747                                      unsigned NumBytes) {
2748   unsigned TargetAlign = Lowering->getStackAlignment();
2749   unsigned AlignMask = TargetAlign - 1;
2750   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2751   return NumBytes;
2752 }
2753
2754 SDValue
2755 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2756                                         CallingConv::ID CallConv, bool isVarArg,
2757                                         const SmallVectorImpl<ISD::InputArg>
2758                                           &Ins,
2759                                         SDLoc dl, SelectionDAG &DAG,
2760                                         SmallVectorImpl<SDValue> &InVals)
2761                                           const {
2762   if (Subtarget.isSVR4ABI()) {
2763     if (Subtarget.isPPC64())
2764       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2765                                          dl, DAG, InVals);
2766     else
2767       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2768                                          dl, DAG, InVals);
2769   } else {
2770     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2771                                        dl, DAG, InVals);
2772   }
2773 }
2774
2775 SDValue
2776 PPCTargetLowering::LowerFormalArguments_32SVR4(
2777                                       SDValue Chain,
2778                                       CallingConv::ID CallConv, bool isVarArg,
2779                                       const SmallVectorImpl<ISD::InputArg>
2780                                         &Ins,
2781                                       SDLoc dl, SelectionDAG &DAG,
2782                                       SmallVectorImpl<SDValue> &InVals) const {
2783
2784   // 32-bit SVR4 ABI Stack Frame Layout:
2785   //              +-----------------------------------+
2786   //        +-->  |            Back chain             |
2787   //        |     +-----------------------------------+
2788   //        |     | Floating-point register save area |
2789   //        |     +-----------------------------------+
2790   //        |     |    General register save area     |
2791   //        |     +-----------------------------------+
2792   //        |     |          CR save word             |
2793   //        |     +-----------------------------------+
2794   //        |     |         VRSAVE save word          |
2795   //        |     +-----------------------------------+
2796   //        |     |         Alignment padding         |
2797   //        |     +-----------------------------------+
2798   //        |     |     Vector register save area     |
2799   //        |     +-----------------------------------+
2800   //        |     |       Local variable space        |
2801   //        |     +-----------------------------------+
2802   //        |     |        Parameter list area        |
2803   //        |     +-----------------------------------+
2804   //        |     |           LR save word            |
2805   //        |     +-----------------------------------+
2806   // SP-->  +---  |            Back chain             |
2807   //              +-----------------------------------+
2808   //
2809   // Specifications:
2810   //   System V Application Binary Interface PowerPC Processor Supplement
2811   //   AltiVec Technology Programming Interface Manual
2812
2813   MachineFunction &MF = DAG.getMachineFunction();
2814   MachineFrameInfo *MFI = MF.getFrameInfo();
2815   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2816
2817   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
2818   // Potential tail calls could cause overwriting of argument stack slots.
2819   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2820                        (CallConv == CallingConv::Fast));
2821   unsigned PtrByteSize = 4;
2822
2823   // Assign locations to all of the incoming arguments.
2824   SmallVector<CCValAssign, 16> ArgLocs;
2825   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2826                  *DAG.getContext());
2827
2828   // Reserve space for the linkage area on the stack.
2829   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2830   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2831
2832   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2833
2834   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2835     CCValAssign &VA = ArgLocs[i];
2836
2837     // Arguments stored in registers.
2838     if (VA.isRegLoc()) {
2839       const TargetRegisterClass *RC;
2840       EVT ValVT = VA.getValVT();
2841
2842       switch (ValVT.getSimpleVT().SimpleTy) {
2843         default:
2844           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2845         case MVT::i1:
2846         case MVT::i32:
2847           RC = &PPC::GPRCRegClass;
2848           break;
2849         case MVT::f32:
2850           if (Subtarget.hasP8Vector())
2851             RC = &PPC::VSSRCRegClass;
2852           else
2853             RC = &PPC::F4RCRegClass;
2854           break;
2855         case MVT::f64:
2856           if (Subtarget.hasVSX())
2857             RC = &PPC::VSFRCRegClass;
2858           else
2859             RC = &PPC::F8RCRegClass;
2860           break;
2861         case MVT::v16i8:
2862         case MVT::v8i16:
2863         case MVT::v4i32:
2864           RC = &PPC::VRRCRegClass;
2865           break;
2866         case MVT::v4f32:
2867           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2868           break;
2869         case MVT::v2f64:
2870         case MVT::v2i64:
2871           RC = &PPC::VSHRCRegClass;
2872           break;
2873         case MVT::v4f64:
2874           RC = &PPC::QFRCRegClass;
2875           break;
2876         case MVT::v4i1:
2877           RC = &PPC::QBRCRegClass;
2878           break;
2879       }
2880
2881       // Transform the arguments stored in physical registers into virtual ones.
2882       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2883       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2884                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2885
2886       if (ValVT == MVT::i1)
2887         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2888
2889       InVals.push_back(ArgValue);
2890     } else {
2891       // Argument stored in memory.
2892       assert(VA.isMemLoc());
2893
2894       unsigned ArgSize = VA.getLocVT().getStoreSize();
2895       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2896                                       isImmutable);
2897
2898       // Create load nodes to retrieve arguments from the stack.
2899       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2900       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2901                                    MachinePointerInfo(),
2902                                    false, false, false, 0));
2903     }
2904   }
2905
2906   // Assign locations to all of the incoming aggregate by value arguments.
2907   // Aggregates passed by value are stored in the local variable space of the
2908   // caller's stack frame, right above the parameter list area.
2909   SmallVector<CCValAssign, 16> ByValArgLocs;
2910   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2911                       ByValArgLocs, *DAG.getContext());
2912
2913   // Reserve stack space for the allocations in CCInfo.
2914   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2915
2916   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2917
2918   // Area that is at least reserved in the caller of this function.
2919   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2920   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2921
2922   // Set the size that is at least reserved in caller of this function.  Tail
2923   // call optimized function's reserved stack space needs to be aligned so that
2924   // taking the difference between two stack areas will result in an aligned
2925   // stack.
2926   MinReservedArea =
2927       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2928   FuncInfo->setMinReservedArea(MinReservedArea);
2929
2930   SmallVector<SDValue, 8> MemOps;
2931
2932   // If the function takes variable number of arguments, make a frame index for
2933   // the start of the first vararg value... for expansion of llvm.va_start.
2934   if (isVarArg) {
2935     static const MCPhysReg GPArgRegs[] = {
2936       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2937       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2938     };
2939     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2940
2941     static const MCPhysReg FPArgRegs[] = {
2942       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2943       PPC::F8
2944     };
2945     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2946     if (DisablePPCFloatInVariadic)
2947       NumFPArgRegs = 0;
2948
2949     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2950     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2951
2952     // Make room for NumGPArgRegs and NumFPArgRegs.
2953     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2954                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2955
2956     FuncInfo->setVarArgsStackOffset(
2957       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2958                              CCInfo.getNextStackOffset(), true));
2959
2960     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2961     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2962
2963     // The fixed integer arguments of a variadic function are stored to the
2964     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2965     // the result of va_next.
2966     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2967       // Get an existing live-in vreg, or add a new one.
2968       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2969       if (!VReg)
2970         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2971
2972       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2973       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2974                                    MachinePointerInfo(), false, false, 0);
2975       MemOps.push_back(Store);
2976       // Increment the address by four for the next argument to store
2977       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2978       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2979     }
2980
2981     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2982     // is set.
2983     // The double arguments are stored to the VarArgsFrameIndex
2984     // on the stack.
2985     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2986       // Get an existing live-in vreg, or add a new one.
2987       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2988       if (!VReg)
2989         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2990
2991       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2992       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2993                                    MachinePointerInfo(), false, false, 0);
2994       MemOps.push_back(Store);
2995       // Increment the address by eight for the next argument to store
2996       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2997                                          PtrVT);
2998       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2999     }
3000   }
3001
3002   if (!MemOps.empty())
3003     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3004
3005   return Chain;
3006 }
3007
3008 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3009 // value to MVT::i64 and then truncate to the correct register size.
3010 SDValue
3011 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
3012                                      SelectionDAG &DAG, SDValue ArgVal,
3013                                      SDLoc dl) const {
3014   if (Flags.isSExt())
3015     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3016                          DAG.getValueType(ObjectVT));
3017   else if (Flags.isZExt())
3018     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3019                          DAG.getValueType(ObjectVT));
3020
3021   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3022 }
3023
3024 SDValue
3025 PPCTargetLowering::LowerFormalArguments_64SVR4(
3026                                       SDValue Chain,
3027                                       CallingConv::ID CallConv, bool isVarArg,
3028                                       const SmallVectorImpl<ISD::InputArg>
3029                                         &Ins,
3030                                       SDLoc dl, SelectionDAG &DAG,
3031                                       SmallVectorImpl<SDValue> &InVals) const {
3032   // TODO: add description of PPC stack frame format, or at least some docs.
3033   //
3034   bool isELFv2ABI = Subtarget.isELFv2ABI();
3035   bool isLittleEndian = Subtarget.isLittleEndian();
3036   MachineFunction &MF = DAG.getMachineFunction();
3037   MachineFrameInfo *MFI = MF.getFrameInfo();
3038   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3039
3040   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3041          "fastcc not supported on varargs functions");
3042
3043   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3044   // Potential tail calls could cause overwriting of argument stack slots.
3045   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3046                        (CallConv == CallingConv::Fast));
3047   unsigned PtrByteSize = 8;
3048   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3049
3050   static const MCPhysReg GPR[] = {
3051     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3052     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3053   };
3054   static const MCPhysReg VR[] = {
3055     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3056     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3057   };
3058   static const MCPhysReg VSRH[] = {
3059     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
3060     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
3061   };
3062
3063   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3064   const unsigned Num_FPR_Regs = 13;
3065   const unsigned Num_VR_Regs  = array_lengthof(VR);
3066   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3067
3068   // Do a first pass over the arguments to determine whether the ABI
3069   // guarantees that our caller has allocated the parameter save area
3070   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3071   // in the ELFv2 ABI, it is true if this is a vararg function or if
3072   // any parameter is located in a stack slot.
3073
3074   bool HasParameterArea = !isELFv2ABI || isVarArg;
3075   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3076   unsigned NumBytes = LinkageSize;
3077   unsigned AvailableFPRs = Num_FPR_Regs;
3078   unsigned AvailableVRs = Num_VR_Regs;
3079   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3080     if (Ins[i].Flags.isNest())
3081       continue;
3082
3083     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3084                                PtrByteSize, LinkageSize, ParamAreaSize,
3085                                NumBytes, AvailableFPRs, AvailableVRs,
3086                                Subtarget.hasQPX()))
3087       HasParameterArea = true;
3088   }
3089
3090   // Add DAG nodes to load the arguments or copy them out of registers.  On
3091   // entry to a function on PPC, the arguments start after the linkage area,
3092   // although the first ones are often in registers.
3093
3094   unsigned ArgOffset = LinkageSize;
3095   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3096   unsigned &QFPR_idx = FPR_idx;
3097   SmallVector<SDValue, 8> MemOps;
3098   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3099   unsigned CurArgIdx = 0;
3100   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3101     SDValue ArgVal;
3102     bool needsLoad = false;
3103     EVT ObjectVT = Ins[ArgNo].VT;
3104     EVT OrigVT = Ins[ArgNo].ArgVT;
3105     unsigned ObjSize = ObjectVT.getStoreSize();
3106     unsigned ArgSize = ObjSize;
3107     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3108     if (Ins[ArgNo].isOrigArg()) {
3109       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3110       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3111     }
3112     // We re-align the argument offset for each argument, except when using the
3113     // fast calling convention, when we need to make sure we do that only when
3114     // we'll actually use a stack slot.
3115     unsigned CurArgOffset, Align;
3116     auto ComputeArgOffset = [&]() {
3117       /* Respect alignment of argument on the stack.  */
3118       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3119       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3120       CurArgOffset = ArgOffset;
3121     };
3122
3123     if (CallConv != CallingConv::Fast) {
3124       ComputeArgOffset();
3125
3126       /* Compute GPR index associated with argument offset.  */
3127       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3128       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3129     }
3130
3131     // FIXME the codegen can be much improved in some cases.
3132     // We do not have to keep everything in memory.
3133     if (Flags.isByVal()) {
3134       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3135
3136       if (CallConv == CallingConv::Fast)
3137         ComputeArgOffset();
3138
3139       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3140       ObjSize = Flags.getByValSize();
3141       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3142       // Empty aggregate parameters do not take up registers.  Examples:
3143       //   struct { } a;
3144       //   union  { } b;
3145       //   int c[0];
3146       // etc.  However, we have to provide a place-holder in InVals, so
3147       // pretend we have an 8-byte item at the current address for that
3148       // purpose.
3149       if (!ObjSize) {
3150         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3151         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3152         InVals.push_back(FIN);
3153         continue;
3154       }
3155
3156       // Create a stack object covering all stack doublewords occupied
3157       // by the argument.  If the argument is (fully or partially) on
3158       // the stack, or if the argument is fully in registers but the
3159       // caller has allocated the parameter save anyway, we can refer
3160       // directly to the caller's stack frame.  Otherwise, create a
3161       // local copy in our own frame.
3162       int FI;
3163       if (HasParameterArea ||
3164           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3165         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3166       else
3167         FI = MFI->CreateStackObject(ArgSize, Align, false);
3168       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3169
3170       // Handle aggregates smaller than 8 bytes.
3171       if (ObjSize < PtrByteSize) {
3172         // The value of the object is its address, which differs from the
3173         // address of the enclosing doubleword on big-endian systems.
3174         SDValue Arg = FIN;
3175         if (!isLittleEndian) {
3176           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3177           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3178         }
3179         InVals.push_back(Arg);
3180
3181         if (GPR_idx != Num_GPR_Regs) {
3182           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3183           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3184           SDValue Store;
3185
3186           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3187             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3188                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3189             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3190                                       MachinePointerInfo(&*FuncArg), ObjType,
3191                                       false, false, 0);
3192           } else {
3193             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3194             // store the whole register as-is to the parameter save area
3195             // slot.
3196             Store =
3197                 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3198                              MachinePointerInfo(&*FuncArg), false, false, 0);
3199           }
3200
3201           MemOps.push_back(Store);
3202         }
3203         // Whether we copied from a register or not, advance the offset
3204         // into the parameter save area by a full doubleword.
3205         ArgOffset += PtrByteSize;
3206         continue;
3207       }
3208
3209       // The value of the object is its address, which is the address of
3210       // its first stack doubleword.
3211       InVals.push_back(FIN);
3212
3213       // Store whatever pieces of the object are in registers to memory.
3214       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3215         if (GPR_idx == Num_GPR_Regs)
3216           break;
3217
3218         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3219         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3220         SDValue Addr = FIN;
3221         if (j) {
3222           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3223           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3224         }
3225         SDValue Store =
3226             DAG.getStore(Val.getValue(1), dl, Val, Addr,
3227                          MachinePointerInfo(&*FuncArg, j), false, false, 0);
3228         MemOps.push_back(Store);
3229         ++GPR_idx;
3230       }
3231       ArgOffset += ArgSize;
3232       continue;
3233     }
3234
3235     switch (ObjectVT.getSimpleVT().SimpleTy) {
3236     default: llvm_unreachable("Unhandled argument type!");
3237     case MVT::i1:
3238     case MVT::i32:
3239     case MVT::i64:
3240       if (Flags.isNest()) {
3241         // The 'nest' parameter, if any, is passed in R11.
3242         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3243         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3244
3245         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3246           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3247
3248         break;
3249       }
3250
3251       // These can be scalar arguments or elements of an integer array type
3252       // passed directly.  Clang may use those instead of "byval" aggregate
3253       // types to avoid forcing arguments to memory unnecessarily.
3254       if (GPR_idx != Num_GPR_Regs) {
3255         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3256         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3257
3258         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3259           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3260           // value to MVT::i64 and then truncate to the correct register size.
3261           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3262       } else {
3263         if (CallConv == CallingConv::Fast)
3264           ComputeArgOffset();
3265
3266         needsLoad = true;
3267         ArgSize = PtrByteSize;
3268       }
3269       if (CallConv != CallingConv::Fast || needsLoad)
3270         ArgOffset += 8;
3271       break;
3272
3273     case MVT::f32:
3274     case MVT::f64:
3275       // These can be scalar arguments or elements of a float array type
3276       // passed directly.  The latter are used to implement ELFv2 homogenous
3277       // float aggregates.
3278       if (FPR_idx != Num_FPR_Regs) {
3279         unsigned VReg;
3280
3281         if (ObjectVT == MVT::f32)
3282           VReg = MF.addLiveIn(FPR[FPR_idx],
3283                               Subtarget.hasP8Vector()
3284                                   ? &PPC::VSSRCRegClass
3285                                   : &PPC::F4RCRegClass);
3286         else
3287           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3288                                                 ? &PPC::VSFRCRegClass
3289                                                 : &PPC::F8RCRegClass);
3290
3291         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3292         ++FPR_idx;
3293       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3294         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3295         // once we support fp <-> gpr moves.
3296
3297         // This can only ever happen in the presence of f32 array types,
3298         // since otherwise we never run out of FPRs before running out
3299         // of GPRs.
3300         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3301         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3302
3303         if (ObjectVT == MVT::f32) {
3304           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3305             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3306                                  DAG.getConstant(32, dl, MVT::i32));
3307           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3308         }
3309
3310         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3311       } else {
3312         if (CallConv == CallingConv::Fast)
3313           ComputeArgOffset();
3314
3315         needsLoad = true;
3316       }
3317
3318       // When passing an array of floats, the array occupies consecutive
3319       // space in the argument area; only round up to the next doubleword
3320       // at the end of the array.  Otherwise, each float takes 8 bytes.
3321       if (CallConv != CallingConv::Fast || needsLoad) {
3322         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3323         ArgOffset += ArgSize;
3324         if (Flags.isInConsecutiveRegsLast())
3325           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3326       }
3327       break;
3328     case MVT::v4f32:
3329     case MVT::v4i32:
3330     case MVT::v8i16:
3331     case MVT::v16i8:
3332     case MVT::v2f64:
3333     case MVT::v2i64:
3334     case MVT::v1i128:
3335       if (!Subtarget.hasQPX()) {
3336       // These can be scalar arguments or elements of a vector array type
3337       // passed directly.  The latter are used to implement ELFv2 homogenous
3338       // vector aggregates.
3339       if (VR_idx != Num_VR_Regs) {
3340         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3341                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3342                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3343         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3344         ++VR_idx;
3345       } else {
3346         if (CallConv == CallingConv::Fast)
3347           ComputeArgOffset();
3348
3349         needsLoad = true;
3350       }
3351       if (CallConv != CallingConv::Fast || needsLoad)
3352         ArgOffset += 16;
3353       break;
3354       } // not QPX
3355
3356       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3357              "Invalid QPX parameter type");
3358       /* fall through */
3359
3360     case MVT::v4f64:
3361     case MVT::v4i1:
3362       // QPX vectors are treated like their scalar floating-point subregisters
3363       // (except that they're larger).
3364       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3365       if (QFPR_idx != Num_QFPR_Regs) {
3366         const TargetRegisterClass *RC;
3367         switch (ObjectVT.getSimpleVT().SimpleTy) {
3368         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3369         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3370         default:         RC = &PPC::QBRCRegClass; break;
3371         }
3372
3373         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3374         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3375         ++QFPR_idx;
3376       } else {
3377         if (CallConv == CallingConv::Fast)
3378           ComputeArgOffset();
3379         needsLoad = true;
3380       }
3381       if (CallConv != CallingConv::Fast || needsLoad)
3382         ArgOffset += Sz;
3383       break;
3384     }
3385
3386     // We need to load the argument to a virtual register if we determined
3387     // above that we ran out of physical registers of the appropriate type.
3388     if (needsLoad) {
3389       if (ObjSize < ArgSize && !isLittleEndian)
3390         CurArgOffset += ArgSize - ObjSize;
3391       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3392       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3393       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3394                            false, false, false, 0);
3395     }
3396
3397     InVals.push_back(ArgVal);
3398   }
3399
3400   // Area that is at least reserved in the caller of this function.
3401   unsigned MinReservedArea;
3402   if (HasParameterArea)
3403     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3404   else
3405     MinReservedArea = LinkageSize;
3406
3407   // Set the size that is at least reserved in caller of this function.  Tail
3408   // call optimized functions' reserved stack space needs to be aligned so that
3409   // taking the difference between two stack areas will result in an aligned
3410   // stack.
3411   MinReservedArea =
3412       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3413   FuncInfo->setMinReservedArea(MinReservedArea);
3414
3415   // If the function takes variable number of arguments, make a frame index for
3416   // the start of the first vararg value... for expansion of llvm.va_start.
3417   if (isVarArg) {
3418     int Depth = ArgOffset;
3419
3420     FuncInfo->setVarArgsFrameIndex(
3421       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3422     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3423
3424     // If this function is vararg, store any remaining integer argument regs
3425     // to their spots on the stack so that they may be loaded by deferencing the
3426     // result of va_next.
3427     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3428          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3429       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3430       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3431       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3432                                    MachinePointerInfo(), false, false, 0);
3433       MemOps.push_back(Store);
3434       // Increment the address by four for the next argument to store
3435       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3436       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3437     }
3438   }
3439
3440   if (!MemOps.empty())
3441     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3442
3443   return Chain;
3444 }
3445
3446 SDValue
3447 PPCTargetLowering::LowerFormalArguments_Darwin(
3448                                       SDValue Chain,
3449                                       CallingConv::ID CallConv, bool isVarArg,
3450                                       const SmallVectorImpl<ISD::InputArg>
3451                                         &Ins,
3452                                       SDLoc dl, SelectionDAG &DAG,
3453                                       SmallVectorImpl<SDValue> &InVals) const {
3454   // TODO: add description of PPC stack frame format, or at least some docs.
3455   //
3456   MachineFunction &MF = DAG.getMachineFunction();
3457   MachineFrameInfo *MFI = MF.getFrameInfo();
3458   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3459
3460   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
3461   bool isPPC64 = PtrVT == MVT::i64;
3462   // Potential tail calls could cause overwriting of argument stack slots.
3463   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3464                        (CallConv == CallingConv::Fast));
3465   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3466   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3467   unsigned ArgOffset = LinkageSize;
3468   // Area that is at least reserved in caller of this function.
3469   unsigned MinReservedArea = ArgOffset;
3470
3471   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3472     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3473     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3474   };
3475   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3476     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3477     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3478   };
3479   static const MCPhysReg VR[] = {
3480     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3481     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3482   };
3483
3484   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3485   const unsigned Num_FPR_Regs = 13;
3486   const unsigned Num_VR_Regs  = array_lengthof( VR);
3487
3488   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3489
3490   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3491
3492   // In 32-bit non-varargs functions, the stack space for vectors is after the
3493   // stack space for non-vectors.  We do not use this space unless we have
3494   // too many vectors to fit in registers, something that only occurs in
3495   // constructed examples:), but we have to walk the arglist to figure
3496   // that out...for the pathological case, compute VecArgOffset as the
3497   // start of the vector parameter area.  Computing VecArgOffset is the
3498   // entire point of the following loop.
3499   unsigned VecArgOffset = ArgOffset;
3500   if (!isVarArg && !isPPC64) {
3501     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3502          ++ArgNo) {
3503       EVT ObjectVT = Ins[ArgNo].VT;
3504       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3505
3506       if (Flags.isByVal()) {
3507         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3508         unsigned ObjSize = Flags.getByValSize();
3509         unsigned ArgSize =
3510                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3511         VecArgOffset += ArgSize;
3512         continue;
3513       }
3514
3515       switch(ObjectVT.getSimpleVT().SimpleTy) {
3516       default: llvm_unreachable("Unhandled argument type!");
3517       case MVT::i1:
3518       case MVT::i32:
3519       case MVT::f32:
3520         VecArgOffset += 4;
3521         break;
3522       case MVT::i64:  // PPC64
3523       case MVT::f64:
3524         // FIXME: We are guaranteed to be !isPPC64 at this point.
3525         // Does MVT::i64 apply?
3526         VecArgOffset += 8;
3527         break;
3528       case MVT::v4f32:
3529       case MVT::v4i32:
3530       case MVT::v8i16:
3531       case MVT::v16i8:
3532         // Nothing to do, we're only looking at Nonvector args here.
3533         break;
3534       }
3535     }
3536   }
3537   // We've found where the vector parameter area in memory is.  Skip the
3538   // first 12 parameters; these don't use that memory.
3539   VecArgOffset = ((VecArgOffset+15)/16)*16;
3540   VecArgOffset += 12*16;
3541
3542   // Add DAG nodes to load the arguments or copy them out of registers.  On
3543   // entry to a function on PPC, the arguments start after the linkage area,
3544   // although the first ones are often in registers.
3545
3546   SmallVector<SDValue, 8> MemOps;
3547   unsigned nAltivecParamsAtEnd = 0;
3548   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3549   unsigned CurArgIdx = 0;
3550   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3551     SDValue ArgVal;
3552     bool needsLoad = false;
3553     EVT ObjectVT = Ins[ArgNo].VT;
3554     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3555     unsigned ArgSize = ObjSize;
3556     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3557     if (Ins[ArgNo].isOrigArg()) {
3558       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3559       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3560     }
3561     unsigned CurArgOffset = ArgOffset;
3562
3563     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3564     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3565         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3566       if (isVarArg || isPPC64) {
3567         MinReservedArea = ((MinReservedArea+15)/16)*16;
3568         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3569                                                   Flags,
3570                                                   PtrByteSize);
3571       } else  nAltivecParamsAtEnd++;
3572     } else
3573       // Calculate min reserved area.
3574       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3575                                                 Flags,
3576                                                 PtrByteSize);
3577
3578     // FIXME the codegen can be much improved in some cases.
3579     // We do not have to keep everything in memory.
3580     if (Flags.isByVal()) {
3581       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3582
3583       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3584       ObjSize = Flags.getByValSize();
3585       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3586       // Objects of size 1 and 2 are right justified, everything else is
3587       // left justified.  This means the memory address is adjusted forwards.
3588       if (ObjSize==1 || ObjSize==2) {
3589         CurArgOffset = CurArgOffset + (4 - ObjSize);
3590       }
3591       // The value of the object is its address.
3592       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3593       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3594       InVals.push_back(FIN);
3595       if (ObjSize==1 || ObjSize==2) {
3596         if (GPR_idx != Num_GPR_Regs) {
3597           unsigned VReg;
3598           if (isPPC64)
3599             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3600           else
3601             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3602           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3603           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3604           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3605                                             MachinePointerInfo(&*FuncArg),
3606                                             ObjType, false, false, 0);
3607           MemOps.push_back(Store);
3608           ++GPR_idx;
3609         }
3610
3611         ArgOffset += PtrByteSize;
3612
3613         continue;
3614       }
3615       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3616         // Store whatever pieces of the object are in registers
3617         // to memory.  ArgOffset will be the address of the beginning
3618         // of the object.
3619         if (GPR_idx != Num_GPR_Regs) {
3620           unsigned VReg;
3621           if (isPPC64)
3622             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3623           else
3624             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3625           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3626           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3627           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3628           SDValue Store =
3629               DAG.getStore(Val.getValue(1), dl, Val, FIN,
3630                            MachinePointerInfo(&*FuncArg, j), false, false, 0);
3631           MemOps.push_back(Store);
3632           ++GPR_idx;
3633           ArgOffset += PtrByteSize;
3634         } else {
3635           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3636           break;
3637         }
3638       }
3639       continue;
3640     }
3641
3642     switch (ObjectVT.getSimpleVT().SimpleTy) {
3643     default: llvm_unreachable("Unhandled argument type!");
3644     case MVT::i1:
3645     case MVT::i32:
3646       if (!isPPC64) {
3647         if (GPR_idx != Num_GPR_Regs) {
3648           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3649           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3650
3651           if (ObjectVT == MVT::i1)
3652             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3653
3654           ++GPR_idx;
3655         } else {
3656           needsLoad = true;
3657           ArgSize = PtrByteSize;
3658         }
3659         // All int arguments reserve stack space in the Darwin ABI.
3660         ArgOffset += PtrByteSize;
3661         break;
3662       }
3663       // FALLTHROUGH
3664     case MVT::i64:  // PPC64
3665       if (GPR_idx != Num_GPR_Regs) {
3666         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3667         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3668
3669         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3670           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3671           // value to MVT::i64 and then truncate to the correct register size.
3672           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3673
3674         ++GPR_idx;
3675       } else {
3676         needsLoad = true;
3677         ArgSize = PtrByteSize;
3678       }
3679       // All int arguments reserve stack space in the Darwin ABI.
3680       ArgOffset += 8;
3681       break;
3682
3683     case MVT::f32:
3684     case MVT::f64:
3685       // Every 4 bytes of argument space consumes one of the GPRs available for
3686       // argument passing.
3687       if (GPR_idx != Num_GPR_Regs) {
3688         ++GPR_idx;
3689         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3690           ++GPR_idx;
3691       }
3692       if (FPR_idx != Num_FPR_Regs) {
3693         unsigned VReg;
3694
3695         if (ObjectVT == MVT::f32)
3696           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3697         else
3698           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3699
3700         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3701         ++FPR_idx;
3702       } else {
3703         needsLoad = true;
3704       }
3705
3706       // All FP arguments reserve stack space in the Darwin ABI.
3707       ArgOffset += isPPC64 ? 8 : ObjSize;
3708       break;
3709     case MVT::v4f32:
3710     case MVT::v4i32:
3711     case MVT::v8i16:
3712     case MVT::v16i8:
3713       // Note that vector arguments in registers don't reserve stack space,
3714       // except in varargs functions.
3715       if (VR_idx != Num_VR_Regs) {
3716         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3717         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3718         if (isVarArg) {
3719           while ((ArgOffset % 16) != 0) {
3720             ArgOffset += PtrByteSize;
3721             if (GPR_idx != Num_GPR_Regs)
3722               GPR_idx++;
3723           }
3724           ArgOffset += 16;
3725           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3726         }
3727         ++VR_idx;
3728       } else {
3729         if (!isVarArg && !isPPC64) {
3730           // Vectors go after all the nonvectors.
3731           CurArgOffset = VecArgOffset;
3732           VecArgOffset += 16;
3733         } else {
3734           // Vectors are aligned.
3735           ArgOffset = ((ArgOffset+15)/16)*16;
3736           CurArgOffset = ArgOffset;
3737           ArgOffset += 16;
3738         }
3739         needsLoad = true;
3740       }
3741       break;
3742     }
3743
3744     // We need to load the argument to a virtual register if we determined above
3745     // that we ran out of physical registers of the appropriate type.
3746     if (needsLoad) {
3747       int FI = MFI->CreateFixedObject(ObjSize,
3748                                       CurArgOffset + (ArgSize - ObjSize),
3749                                       isImmutable);
3750       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3751       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3752                            false, false, false, 0);
3753     }
3754
3755     InVals.push_back(ArgVal);
3756   }
3757
3758   // Allow for Altivec parameters at the end, if needed.
3759   if (nAltivecParamsAtEnd) {
3760     MinReservedArea = ((MinReservedArea+15)/16)*16;
3761     MinReservedArea += 16*nAltivecParamsAtEnd;
3762   }
3763
3764   // Area that is at least reserved in the caller of this function.
3765   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3766
3767   // Set the size that is at least reserved in caller of this function.  Tail
3768   // call optimized functions' reserved stack space needs to be aligned so that
3769   // taking the difference between two stack areas will result in an aligned
3770   // stack.
3771   MinReservedArea =
3772       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3773   FuncInfo->setMinReservedArea(MinReservedArea);
3774
3775   // If the function takes variable number of arguments, make a frame index for
3776   // the start of the first vararg value... for expansion of llvm.va_start.
3777   if (isVarArg) {
3778     int Depth = ArgOffset;
3779
3780     FuncInfo->setVarArgsFrameIndex(
3781       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3782                              Depth, true));
3783     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3784
3785     // If this function is vararg, store any remaining integer argument regs
3786     // to their spots on the stack so that they may be loaded by deferencing the
3787     // result of va_next.
3788     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3789       unsigned VReg;
3790
3791       if (isPPC64)
3792         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3793       else
3794         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3795
3796       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3797       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3798                                    MachinePointerInfo(), false, false, 0);
3799       MemOps.push_back(Store);
3800       // Increment the address by four for the next argument to store
3801       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3802       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3803     }
3804   }
3805
3806   if (!MemOps.empty())
3807     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3808
3809   return Chain;
3810 }
3811
3812 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3813 /// adjusted to accommodate the arguments for the tailcall.
3814 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3815                                    unsigned ParamSize) {
3816
3817   if (!isTailCall) return 0;
3818
3819   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3820   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3821   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3822   // Remember only if the new adjustement is bigger.
3823   if (SPDiff < FI->getTailCallSPDelta())
3824     FI->setTailCallSPDelta(SPDiff);
3825
3826   return SPDiff;
3827 }
3828
3829 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3830 /// for tail call optimization. Targets which want to do tail call
3831 /// optimization should implement this function.
3832 bool
3833 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3834                                                      CallingConv::ID CalleeCC,
3835                                                      bool isVarArg,
3836                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3837                                                      SelectionDAG& DAG) const {
3838   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3839     return false;
3840
3841   // Variable argument functions are not supported.
3842   if (isVarArg)
3843     return false;
3844
3845   MachineFunction &MF = DAG.getMachineFunction();
3846   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3847   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3848     // Functions containing by val parameters are not supported.
3849     for (unsigned i = 0; i != Ins.size(); i++) {
3850        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3851        if (Flags.isByVal()) return false;
3852     }
3853
3854     // Non-PIC/GOT tail calls are supported.
3855     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3856       return true;
3857
3858     // At the moment we can only do local tail calls (in same module, hidden
3859     // or protected) if we are generating PIC.
3860     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3861       return G->getGlobal()->hasHiddenVisibility()
3862           || G->getGlobal()->hasProtectedVisibility();
3863   }
3864
3865   return false;
3866 }
3867
3868 /// isCallCompatibleAddress - Return the immediate to use if the specified
3869 /// 32-bit value is representable in the immediate field of a BxA instruction.
3870 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3871   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3872   if (!C) return nullptr;
3873
3874   int Addr = C->getZExtValue();
3875   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3876       SignExtend32<26>(Addr) != Addr)
3877     return nullptr;  // Top 6 bits have to be sext of immediate.
3878
3879   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3880                          DAG.getTargetLoweringInfo().getPointerTy(
3881                              DAG.getDataLayout())).getNode();
3882 }
3883
3884 namespace {
3885
3886 struct TailCallArgumentInfo {
3887   SDValue Arg;
3888   SDValue FrameIdxOp;
3889   int       FrameIdx;
3890
3891   TailCallArgumentInfo() : FrameIdx(0) {}
3892 };
3893 }
3894
3895 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3896 static void
3897 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3898                                            SDValue Chain,
3899                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3900                    SmallVectorImpl<SDValue> &MemOpChains,
3901                    SDLoc dl) {
3902   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3903     SDValue Arg = TailCallArgs[i].Arg;
3904     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3905     int FI = TailCallArgs[i].FrameIdx;
3906     // Store relative to framepointer.
3907     MemOpChains.push_back(DAG.getStore(
3908         Chain, dl, Arg, FIN,
3909         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
3910         false, 0));
3911   }
3912 }
3913
3914 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3915 /// the appropriate stack slot for the tail call optimized function call.
3916 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3917                                                MachineFunction &MF,
3918                                                SDValue Chain,
3919                                                SDValue OldRetAddr,
3920                                                SDValue OldFP,
3921                                                int SPDiff,
3922                                                bool isPPC64,
3923                                                bool isDarwinABI,
3924                                                SDLoc dl) {
3925   if (SPDiff) {
3926     // Calculate the new stack slot for the return address.
3927     int SlotSize = isPPC64 ? 8 : 4;
3928     const PPCFrameLowering *FL =
3929         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3930     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3931     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3932                                                           NewRetAddrLoc, true);
3933     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3934     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3935     Chain = DAG.getStore(
3936         Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3937         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewRetAddr),
3938         false, false, 0);
3939
3940     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3941     // slot as the FP is never overwritten.
3942     if (isDarwinABI) {
3943       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3944       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3945                                                           true);
3946       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3947       Chain = DAG.getStore(
3948           Chain, dl, OldFP, NewFramePtrIdx,
3949           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewFPIdx),
3950           false, false, 0);
3951     }
3952   }
3953   return Chain;
3954 }
3955
3956 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3957 /// the position of the argument.
3958 static void
3959 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3960                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3961                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3962   int Offset = ArgOffset + SPDiff;
3963   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3964   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3965   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3966   SDValue FIN = DAG.getFrameIndex(FI, VT);
3967   TailCallArgumentInfo Info;
3968   Info.Arg = Arg;
3969   Info.FrameIdxOp = FIN;
3970   Info.FrameIdx = FI;
3971   TailCallArguments.push_back(Info);
3972 }
3973
3974 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3975 /// stack slot. Returns the chain as result and the loaded frame pointers in
3976 /// LROpOut/FPOpout. Used when tail calling.
3977 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3978                                                         int SPDiff,
3979                                                         SDValue Chain,
3980                                                         SDValue &LROpOut,
3981                                                         SDValue &FPOpOut,
3982                                                         bool isDarwinABI,
3983                                                         SDLoc dl) const {
3984   if (SPDiff) {
3985     // Load the LR and FP stack slot for later adjusting.
3986     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3987     LROpOut = getReturnAddrFrameIndex(DAG);
3988     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3989                           false, false, false, 0);
3990     Chain = SDValue(LROpOut.getNode(), 1);
3991
3992     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3993     // slot as the FP is never overwritten.
3994     if (isDarwinABI) {
3995       FPOpOut = getFramePointerFrameIndex(DAG);
3996       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3997                             false, false, false, 0);
3998       Chain = SDValue(FPOpOut.getNode(), 1);
3999     }
4000   }
4001   return Chain;
4002 }
4003
4004 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4005 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4006 /// specified by the specific parameter attribute. The copy will be passed as
4007 /// a byval function parameter.
4008 /// Sometimes what we are copying is the end of a larger object, the part that
4009 /// does not fit in registers.
4010 static SDValue
4011 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
4012                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
4013                           SDLoc dl) {
4014   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4015   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4016                        false, false, false, MachinePointerInfo(),
4017                        MachinePointerInfo());
4018 }
4019
4020 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4021 /// tail calls.
4022 static void
4023 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
4024                  SDValue Arg, SDValue PtrOff, int SPDiff,
4025                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
4026                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4027                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
4028                  SDLoc dl) {
4029   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4030   if (!isTailCall) {
4031     if (isVector) {
4032       SDValue StackPtr;
4033       if (isPPC64)
4034         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4035       else
4036         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4037       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4038                            DAG.getConstant(ArgOffset, dl, PtrVT));
4039     }
4040     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4041                                        MachinePointerInfo(), false, false, 0));
4042   // Calculate and remember argument location.
4043   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4044                                   TailCallArguments);
4045 }
4046
4047 static
4048 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4049                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
4050                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
4051                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4052   MachineFunction &MF = DAG.getMachineFunction();
4053
4054   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4055   // might overwrite each other in case of tail call optimization.
4056   SmallVector<SDValue, 8> MemOpChains2;
4057   // Do not flag preceding copytoreg stuff together with the following stuff.
4058   InFlag = SDValue();
4059   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4060                                     MemOpChains2, dl);
4061   if (!MemOpChains2.empty())
4062     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4063
4064   // Store the return address to the appropriate stack slot.
4065   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
4066                                         isPPC64, isDarwinABI, dl);
4067
4068   // Emit callseq_end just before tailcall node.
4069   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4070                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4071   InFlag = Chain.getValue(1);
4072 }
4073
4074 // Is this global address that of a function that can be called by name? (as
4075 // opposed to something that must hold a descriptor for an indirect call).
4076 static bool isFunctionGlobalAddress(SDValue Callee) {
4077   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4078     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4079         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4080       return false;
4081
4082     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
4083   }
4084
4085   return false;
4086 }
4087
4088 static
4089 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
4090                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
4091                      bool isTailCall, bool IsPatchPoint, bool hasNest,
4092                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
4093                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4094                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4095
4096   bool isPPC64 = Subtarget.isPPC64();
4097   bool isSVR4ABI = Subtarget.isSVR4ABI();
4098   bool isELFv2ABI = Subtarget.isELFv2ABI();
4099
4100   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4101   NodeTys.push_back(MVT::Other);   // Returns a chain
4102   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4103
4104   unsigned CallOpc = PPCISD::CALL;
4105
4106   bool needIndirectCall = true;
4107   if (!isSVR4ABI || !isPPC64)
4108     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4109       // If this is an absolute destination address, use the munged value.
4110       Callee = SDValue(Dest, 0);
4111       needIndirectCall = false;
4112     }
4113
4114   if (isFunctionGlobalAddress(Callee)) {
4115     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4116     // A call to a TLS address is actually an indirect call to a
4117     // thread-specific pointer.
4118     unsigned OpFlags = 0;
4119     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4120          (Subtarget.getTargetTriple().isMacOSX() &&
4121           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
4122          !G->getGlobal()->isStrongDefinitionForLinker()) ||
4123         (Subtarget.isTargetELF() && !isPPC64 &&
4124          !G->getGlobal()->hasLocalLinkage() &&
4125          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4126       // PC-relative references to external symbols should go through $stub,
4127       // unless we're building with the leopard linker or later, which
4128       // automatically synthesizes these stubs.
4129       OpFlags = PPCII::MO_PLT_OR_STUB;
4130     }
4131
4132     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4133     // every direct call is) turn it into a TargetGlobalAddress /
4134     // TargetExternalSymbol node so that legalize doesn't hack it.
4135     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4136                                         Callee.getValueType(), 0, OpFlags);
4137     needIndirectCall = false;
4138   }
4139
4140   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4141     unsigned char OpFlags = 0;
4142
4143     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4144          (Subtarget.getTargetTriple().isMacOSX() &&
4145           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4146         (Subtarget.isTargetELF() && !isPPC64 &&
4147          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4148       // PC-relative references to external symbols should go through $stub,
4149       // unless we're building with the leopard linker or later, which
4150       // automatically synthesizes these stubs.
4151       OpFlags = PPCII::MO_PLT_OR_STUB;
4152     }
4153
4154     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4155                                          OpFlags);
4156     needIndirectCall = false;
4157   }
4158
4159   if (IsPatchPoint) {
4160     // We'll form an invalid direct call when lowering a patchpoint; the full
4161     // sequence for an indirect call is complicated, and many of the
4162     // instructions introduced might have side effects (and, thus, can't be
4163     // removed later). The call itself will be removed as soon as the
4164     // argument/return lowering is complete, so the fact that it has the wrong
4165     // kind of operands should not really matter.
4166     needIndirectCall = false;
4167   }
4168
4169   if (needIndirectCall) {
4170     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4171     // to do the call, we can't use PPCISD::CALL.
4172     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4173
4174     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4175       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4176       // entry point, but to the function descriptor (the function entry point
4177       // address is part of the function descriptor though).
4178       // The function descriptor is a three doubleword structure with the
4179       // following fields: function entry point, TOC base address and
4180       // environment pointer.
4181       // Thus for a call through a function pointer, the following actions need
4182       // to be performed:
4183       //   1. Save the TOC of the caller in the TOC save area of its stack
4184       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4185       //   2. Load the address of the function entry point from the function
4186       //      descriptor.
4187       //   3. Load the TOC of the callee from the function descriptor into r2.
4188       //   4. Load the environment pointer from the function descriptor into
4189       //      r11.
4190       //   5. Branch to the function entry point address.
4191       //   6. On return of the callee, the TOC of the caller needs to be
4192       //      restored (this is done in FinishCall()).
4193       //
4194       // The loads are scheduled at the beginning of the call sequence, and the
4195       // register copies are flagged together to ensure that no other
4196       // operations can be scheduled in between. E.g. without flagging the
4197       // copies together, a TOC access in the caller could be scheduled between
4198       // the assignment of the callee TOC and the branch to the callee, which
4199       // results in the TOC access going through the TOC of the callee instead
4200       // of going through the TOC of the caller, which leads to incorrect code.
4201
4202       // Load the address of the function entry point from the function
4203       // descriptor.
4204       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4205       if (LDChain.getValueType() == MVT::Glue)
4206         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4207
4208       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4209
4210       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4211       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4212                                         false, false, LoadsInv, 8);
4213
4214       // Load environment pointer into r11.
4215       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4216       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4217       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4218                                        MPI.getWithOffset(16), false, false,
4219                                        LoadsInv, 8);
4220
4221       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4222       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4223       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4224                                    MPI.getWithOffset(8), false, false,
4225                                    LoadsInv, 8);
4226
4227       setUsesTOCBasePtr(DAG);
4228       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4229                                         InFlag);
4230       Chain = TOCVal.getValue(0);
4231       InFlag = TOCVal.getValue(1);
4232
4233       // If the function call has an explicit 'nest' parameter, it takes the
4234       // place of the environment pointer.
4235       if (!hasNest) {
4236         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4237                                           InFlag);
4238
4239         Chain = EnvVal.getValue(0);
4240         InFlag = EnvVal.getValue(1);
4241       }
4242
4243       MTCTROps[0] = Chain;
4244       MTCTROps[1] = LoadFuncPtr;
4245       MTCTROps[2] = InFlag;
4246     }
4247
4248     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4249                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4250     InFlag = Chain.getValue(1);
4251
4252     NodeTys.clear();
4253     NodeTys.push_back(MVT::Other);
4254     NodeTys.push_back(MVT::Glue);
4255     Ops.push_back(Chain);
4256     CallOpc = PPCISD::BCTRL;
4257     Callee.setNode(nullptr);
4258     // Add use of X11 (holding environment pointer)
4259     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4260       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4261     // Add CTR register as callee so a bctr can be emitted later.
4262     if (isTailCall)
4263       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4264   }
4265
4266   // If this is a direct call, pass the chain and the callee.
4267   if (Callee.getNode()) {
4268     Ops.push_back(Chain);
4269     Ops.push_back(Callee);
4270   }
4271   // If this is a tail call add stack pointer delta.
4272   if (isTailCall)
4273     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4274
4275   // Add argument registers to the end of the list so that they are known live
4276   // into the call.
4277   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4278     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4279                                   RegsToPass[i].second.getValueType()));
4280
4281   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4282   // into the call.
4283   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4284     setUsesTOCBasePtr(DAG);
4285     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4286   }
4287
4288   return CallOpc;
4289 }
4290
4291 static
4292 bool isLocalCall(const SDValue &Callee)
4293 {
4294   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4295     return G->getGlobal()->isStrongDefinitionForLinker();
4296   return false;
4297 }
4298
4299 SDValue
4300 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4301                                    CallingConv::ID CallConv, bool isVarArg,
4302                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4303                                    SDLoc dl, SelectionDAG &DAG,
4304                                    SmallVectorImpl<SDValue> &InVals) const {
4305
4306   SmallVector<CCValAssign, 16> RVLocs;
4307   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4308                     *DAG.getContext());
4309   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4310
4311   // Copy all of the result registers out of their specified physreg.
4312   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4313     CCValAssign &VA = RVLocs[i];
4314     assert(VA.isRegLoc() && "Can only return in registers!");
4315
4316     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4317                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4318     Chain = Val.getValue(1);
4319     InFlag = Val.getValue(2);
4320
4321     switch (VA.getLocInfo()) {
4322     default: llvm_unreachable("Unknown loc info!");
4323     case CCValAssign::Full: break;
4324     case CCValAssign::AExt:
4325       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4326       break;
4327     case CCValAssign::ZExt:
4328       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4329                         DAG.getValueType(VA.getValVT()));
4330       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4331       break;
4332     case CCValAssign::SExt:
4333       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4334                         DAG.getValueType(VA.getValVT()));
4335       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4336       break;
4337     }
4338
4339     InVals.push_back(Val);
4340   }
4341
4342   return Chain;
4343 }
4344
4345 SDValue
4346 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4347                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4348                               bool hasNest, SelectionDAG &DAG,
4349                               SmallVector<std::pair<unsigned, SDValue>, 8>
4350                                 &RegsToPass,
4351                               SDValue InFlag, SDValue Chain,
4352                               SDValue CallSeqStart, SDValue &Callee,
4353                               int SPDiff, unsigned NumBytes,
4354                               const SmallVectorImpl<ISD::InputArg> &Ins,
4355                               SmallVectorImpl<SDValue> &InVals,
4356                               ImmutableCallSite *CS) const {
4357
4358   std::vector<EVT> NodeTys;
4359   SmallVector<SDValue, 8> Ops;
4360   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4361                                  SPDiff, isTailCall, IsPatchPoint, hasNest,
4362                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4363
4364   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4365   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4366     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4367
4368   // When performing tail call optimization the callee pops its arguments off
4369   // the stack. Account for this here so these bytes can be pushed back on in
4370   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4371   int BytesCalleePops =
4372     (CallConv == CallingConv::Fast &&
4373      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4374
4375   // Add a register mask operand representing the call-preserved registers.
4376   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4377   const uint32_t *Mask =
4378       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4379   assert(Mask && "Missing call preserved mask for calling convention");
4380   Ops.push_back(DAG.getRegisterMask(Mask));
4381
4382   if (InFlag.getNode())
4383     Ops.push_back(InFlag);
4384
4385   // Emit tail call.
4386   if (isTailCall) {
4387     assert(((Callee.getOpcode() == ISD::Register &&
4388              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4389             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4390             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4391             isa<ConstantSDNode>(Callee)) &&
4392     "Expecting an global address, external symbol, absolute value or register");
4393
4394     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4395     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4396   }
4397
4398   // Add a NOP immediately after the branch instruction when using the 64-bit
4399   // SVR4 ABI. At link time, if caller and callee are in a different module and
4400   // thus have a different TOC, the call will be replaced with a call to a stub
4401   // function which saves the current TOC, loads the TOC of the callee and
4402   // branches to the callee. The NOP will be replaced with a load instruction
4403   // which restores the TOC of the caller from the TOC save slot of the current
4404   // stack frame. If caller and callee belong to the same module (and have the
4405   // same TOC), the NOP will remain unchanged.
4406
4407   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4408       !IsPatchPoint) {
4409     if (CallOpc == PPCISD::BCTRL) {
4410       // This is a call through a function pointer.
4411       // Restore the caller TOC from the save area into R2.
4412       // See PrepareCall() for more information about calls through function
4413       // pointers in the 64-bit SVR4 ABI.
4414       // We are using a target-specific load with r2 hard coded, because the
4415       // result of a target-independent load would never go directly into r2,
4416       // since r2 is a reserved register (which prevents the register allocator
4417       // from allocating it), resulting in an additional register being
4418       // allocated and an unnecessary move instruction being generated.
4419       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4420
4421       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4422       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4423       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4424       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4425       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4426
4427       // The address needs to go after the chain input but before the flag (or
4428       // any other variadic arguments).
4429       Ops.insert(std::next(Ops.begin()), AddTOC);
4430     } else if ((CallOpc == PPCISD::CALL) &&
4431                (!isLocalCall(Callee) ||
4432                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4433       // Otherwise insert NOP for non-local calls.
4434       CallOpc = PPCISD::CALL_NOP;
4435   }
4436
4437   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4438   InFlag = Chain.getValue(1);
4439
4440   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4441                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4442                              InFlag, dl);
4443   if (!Ins.empty())
4444     InFlag = Chain.getValue(1);
4445
4446   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4447                          Ins, dl, DAG, InVals);
4448 }
4449
4450 SDValue
4451 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4452                              SmallVectorImpl<SDValue> &InVals) const {
4453   SelectionDAG &DAG                     = CLI.DAG;
4454   SDLoc &dl                             = CLI.DL;
4455   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4456   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4457   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4458   SDValue Chain                         = CLI.Chain;
4459   SDValue Callee                        = CLI.Callee;
4460   bool &isTailCall                      = CLI.IsTailCall;
4461   CallingConv::ID CallConv              = CLI.CallConv;
4462   bool isVarArg                         = CLI.IsVarArg;
4463   bool IsPatchPoint                     = CLI.IsPatchPoint;
4464   ImmutableCallSite *CS                 = CLI.CS;
4465
4466   if (isTailCall)
4467     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4468                                                    Ins, DAG);
4469
4470   if (!isTailCall && CS && CS->isMustTailCall())
4471     report_fatal_error("failed to perform tail call elimination on a call "
4472                        "site marked musttail");
4473
4474   if (Subtarget.isSVR4ABI()) {
4475     if (Subtarget.isPPC64())
4476       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4477                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4478                               dl, DAG, InVals, CS);
4479     else
4480       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4481                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4482                               dl, DAG, InVals, CS);
4483   }
4484
4485   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4486                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4487                           dl, DAG, InVals, CS);
4488 }
4489
4490 SDValue
4491 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4492                                     CallingConv::ID CallConv, bool isVarArg,
4493                                     bool isTailCall, bool IsPatchPoint,
4494                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4495                                     const SmallVectorImpl<SDValue> &OutVals,
4496                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4497                                     SDLoc dl, SelectionDAG &DAG,
4498                                     SmallVectorImpl<SDValue> &InVals,
4499                                     ImmutableCallSite *CS) const {
4500   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4501   // of the 32-bit SVR4 ABI stack frame layout.
4502
4503   assert((CallConv == CallingConv::C ||
4504           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4505
4506   unsigned PtrByteSize = 4;
4507
4508   MachineFunction &MF = DAG.getMachineFunction();
4509
4510   // Mark this function as potentially containing a function that contains a
4511   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4512   // and restoring the callers stack pointer in this functions epilog. This is
4513   // done because by tail calling the called function might overwrite the value
4514   // in this function's (MF) stack pointer stack slot 0(SP).
4515   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4516       CallConv == CallingConv::Fast)
4517     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4518
4519   // Count how many bytes are to be pushed on the stack, including the linkage
4520   // area, parameter list area and the part of the local variable space which
4521   // contains copies of aggregates which are passed by value.
4522
4523   // Assign locations to all of the outgoing arguments.
4524   SmallVector<CCValAssign, 16> ArgLocs;
4525   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4526                  *DAG.getContext());
4527
4528   // Reserve space for the linkage area on the stack.
4529   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4530                        PtrByteSize);
4531
4532   if (isVarArg) {
4533     // Handle fixed and variable vector arguments differently.
4534     // Fixed vector arguments go into registers as long as registers are
4535     // available. Variable vector arguments always go into memory.
4536     unsigned NumArgs = Outs.size();
4537
4538     for (unsigned i = 0; i != NumArgs; ++i) {
4539       MVT ArgVT = Outs[i].VT;
4540       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4541       bool Result;
4542
4543       if (Outs[i].IsFixed) {
4544         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4545                                CCInfo);
4546       } else {
4547         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4548                                       ArgFlags, CCInfo);
4549       }
4550
4551       if (Result) {
4552 #ifndef NDEBUG
4553         errs() << "Call operand #" << i << " has unhandled type "
4554              << EVT(ArgVT).getEVTString() << "\n";
4555 #endif
4556         llvm_unreachable(nullptr);
4557       }
4558     }
4559   } else {
4560     // All arguments are treated the same.
4561     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4562   }
4563
4564   // Assign locations to all of the outgoing aggregate by value arguments.
4565   SmallVector<CCValAssign, 16> ByValArgLocs;
4566   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4567                       ByValArgLocs, *DAG.getContext());
4568
4569   // Reserve stack space for the allocations in CCInfo.
4570   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4571
4572   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4573
4574   // Size of the linkage area, parameter list area and the part of the local
4575   // space variable where copies of aggregates which are passed by value are
4576   // stored.
4577   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4578
4579   // Calculate by how many bytes the stack has to be adjusted in case of tail
4580   // call optimization.
4581   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4582
4583   // Adjust the stack pointer for the new arguments...
4584   // These operations are automatically eliminated by the prolog/epilog pass
4585   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4586                                dl);
4587   SDValue CallSeqStart = Chain;
4588
4589   // Load the return address and frame pointer so it can be moved somewhere else
4590   // later.
4591   SDValue LROp, FPOp;
4592   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4593                                        dl);
4594
4595   // Set up a copy of the stack pointer for use loading and storing any
4596   // arguments that may not fit in the registers available for argument
4597   // passing.
4598   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4599
4600   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4601   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4602   SmallVector<SDValue, 8> MemOpChains;
4603
4604   bool seenFloatArg = false;
4605   // Walk the register/memloc assignments, inserting copies/loads.
4606   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4607        i != e;
4608        ++i) {
4609     CCValAssign &VA = ArgLocs[i];
4610     SDValue Arg = OutVals[i];
4611     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4612
4613     if (Flags.isByVal()) {
4614       // Argument is an aggregate which is passed by value, thus we need to
4615       // create a copy of it in the local variable space of the current stack
4616       // frame (which is the stack frame of the caller) and pass the address of
4617       // this copy to the callee.
4618       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4619       CCValAssign &ByValVA = ByValArgLocs[j++];
4620       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4621
4622       // Memory reserved in the local variable space of the callers stack frame.
4623       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4624
4625       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4626       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4627                            StackPtr, PtrOff);
4628
4629       // Create a copy of the argument in the local area of the current
4630       // stack frame.
4631       SDValue MemcpyCall =
4632         CreateCopyOfByValArgument(Arg, PtrOff,
4633                                   CallSeqStart.getNode()->getOperand(0),
4634                                   Flags, DAG, dl);
4635
4636       // This must go outside the CALLSEQ_START..END.
4637       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4638                            CallSeqStart.getNode()->getOperand(1),
4639                            SDLoc(MemcpyCall));
4640       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4641                              NewCallSeqStart.getNode());
4642       Chain = CallSeqStart = NewCallSeqStart;
4643
4644       // Pass the address of the aggregate copy on the stack either in a
4645       // physical register or in the parameter list area of the current stack
4646       // frame to the callee.
4647       Arg = PtrOff;
4648     }
4649
4650     if (VA.isRegLoc()) {
4651       if (Arg.getValueType() == MVT::i1)
4652         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4653
4654       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4655       // Put argument in a physical register.
4656       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4657     } else {
4658       // Put argument in the parameter list area of the current stack frame.
4659       assert(VA.isMemLoc());
4660       unsigned LocMemOffset = VA.getLocMemOffset();
4661
4662       if (!isTailCall) {
4663         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4664         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4665                              StackPtr, PtrOff);
4666
4667         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4668                                            MachinePointerInfo(),
4669                                            false, false, 0));
4670       } else {
4671         // Calculate and remember argument location.
4672         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4673                                  TailCallArguments);
4674       }
4675     }
4676   }
4677
4678   if (!MemOpChains.empty())
4679     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4680
4681   // Build a sequence of copy-to-reg nodes chained together with token chain
4682   // and flag operands which copy the outgoing args into the appropriate regs.
4683   SDValue InFlag;
4684   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4685     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4686                              RegsToPass[i].second, InFlag);
4687     InFlag = Chain.getValue(1);
4688   }
4689
4690   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4691   // registers.
4692   if (isVarArg) {
4693     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4694     SDValue Ops[] = { Chain, InFlag };
4695
4696     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4697                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4698
4699     InFlag = Chain.getValue(1);
4700   }
4701
4702   if (isTailCall)
4703     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4704                     false, TailCallArguments);
4705
4706   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
4707                     /* unused except on PPC64 ELFv1 */ false, DAG,
4708                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4709                     NumBytes, Ins, InVals, CS);
4710 }
4711
4712 // Copy an argument into memory, being careful to do this outside the
4713 // call sequence for the call to which the argument belongs.
4714 SDValue
4715 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4716                                               SDValue CallSeqStart,
4717                                               ISD::ArgFlagsTy Flags,
4718                                               SelectionDAG &DAG,
4719                                               SDLoc dl) const {
4720   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4721                         CallSeqStart.getNode()->getOperand(0),
4722                         Flags, DAG, dl);
4723   // The MEMCPY must go outside the CALLSEQ_START..END.
4724   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4725                              CallSeqStart.getNode()->getOperand(1),
4726                              SDLoc(MemcpyCall));
4727   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4728                          NewCallSeqStart.getNode());
4729   return NewCallSeqStart;
4730 }
4731
4732 SDValue
4733 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4734                                     CallingConv::ID CallConv, bool isVarArg,
4735                                     bool isTailCall, bool IsPatchPoint,
4736                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4737                                     const SmallVectorImpl<SDValue> &OutVals,
4738                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4739                                     SDLoc dl, SelectionDAG &DAG,
4740                                     SmallVectorImpl<SDValue> &InVals,
4741                                     ImmutableCallSite *CS) const {
4742
4743   bool isELFv2ABI = Subtarget.isELFv2ABI();
4744   bool isLittleEndian = Subtarget.isLittleEndian();
4745   unsigned NumOps = Outs.size();
4746   bool hasNest = false;
4747
4748   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4749   unsigned PtrByteSize = 8;
4750
4751   MachineFunction &MF = DAG.getMachineFunction();
4752
4753   // Mark this function as potentially containing a function that contains a
4754   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4755   // and restoring the callers stack pointer in this functions epilog. This is
4756   // done because by tail calling the called function might overwrite the value
4757   // in this function's (MF) stack pointer stack slot 0(SP).
4758   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4759       CallConv == CallingConv::Fast)
4760     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4761
4762   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4763          "fastcc not supported on varargs functions");
4764
4765   // Count how many bytes are to be pushed on the stack, including the linkage
4766   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4767   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4768   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4769   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4770   unsigned NumBytes = LinkageSize;
4771   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4772   unsigned &QFPR_idx = FPR_idx;
4773
4774   static const MCPhysReg GPR[] = {
4775     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4776     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4777   };
4778   static const MCPhysReg VR[] = {
4779     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4780     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4781   };
4782   static const MCPhysReg VSRH[] = {
4783     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4784     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4785   };
4786
4787   const unsigned NumGPRs = array_lengthof(GPR);
4788   const unsigned NumFPRs = 13;
4789   const unsigned NumVRs  = array_lengthof(VR);
4790   const unsigned NumQFPRs = NumFPRs;
4791
4792   // When using the fast calling convention, we don't provide backing for
4793   // arguments that will be in registers.
4794   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4795
4796   // Add up all the space actually used.
4797   for (unsigned i = 0; i != NumOps; ++i) {
4798     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4799     EVT ArgVT = Outs[i].VT;
4800     EVT OrigVT = Outs[i].ArgVT;
4801
4802     if (Flags.isNest())
4803       continue;
4804
4805     if (CallConv == CallingConv::Fast) {
4806       if (Flags.isByVal())
4807         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4808       else
4809         switch (ArgVT.getSimpleVT().SimpleTy) {
4810         default: llvm_unreachable("Unexpected ValueType for argument!");
4811         case MVT::i1:
4812         case MVT::i32:
4813         case MVT::i64:
4814           if (++NumGPRsUsed <= NumGPRs)
4815             continue;
4816           break;
4817         case MVT::v4i32:
4818         case MVT::v8i16:
4819         case MVT::v16i8:
4820         case MVT::v2f64:
4821         case MVT::v2i64:
4822         case MVT::v1i128:
4823           if (++NumVRsUsed <= NumVRs)
4824             continue;
4825           break;
4826         case MVT::v4f32:
4827           // When using QPX, this is handled like a FP register, otherwise, it
4828           // is an Altivec register.
4829           if (Subtarget.hasQPX()) {
4830             if (++NumFPRsUsed <= NumFPRs)
4831               continue;
4832           } else {
4833             if (++NumVRsUsed <= NumVRs)
4834               continue;
4835           }
4836           break;
4837         case MVT::f32:
4838         case MVT::f64:
4839         case MVT::v4f64: // QPX
4840         case MVT::v4i1:  // QPX
4841           if (++NumFPRsUsed <= NumFPRs)
4842             continue;
4843           break;
4844         }
4845     }
4846
4847     /* Respect alignment of argument on the stack.  */
4848     unsigned Align =
4849       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4850     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4851
4852     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4853     if (Flags.isInConsecutiveRegsLast())
4854       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4855   }
4856
4857   unsigned NumBytesActuallyUsed = NumBytes;
4858
4859   // The prolog code of the callee may store up to 8 GPR argument registers to
4860   // the stack, allowing va_start to index over them in memory if its varargs.
4861   // Because we cannot tell if this is needed on the caller side, we have to
4862   // conservatively assume that it is needed.  As such, make sure we have at
4863   // least enough stack space for the caller to store the 8 GPRs.
4864   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4865   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4866
4867   // Tail call needs the stack to be aligned.
4868   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4869       CallConv == CallingConv::Fast)
4870     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4871
4872   // Calculate by how many bytes the stack has to be adjusted in case of tail
4873   // call optimization.
4874   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4875
4876   // To protect arguments on the stack from being clobbered in a tail call,
4877   // force all the loads to happen before doing any other lowering.
4878   if (isTailCall)
4879     Chain = DAG.getStackArgumentTokenFactor(Chain);
4880
4881   // Adjust the stack pointer for the new arguments...
4882   // These operations are automatically eliminated by the prolog/epilog pass
4883   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4884                                dl);
4885   SDValue CallSeqStart = Chain;
4886
4887   // Load the return address and frame pointer so it can be move somewhere else
4888   // later.
4889   SDValue LROp, FPOp;
4890   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4891                                        dl);
4892
4893   // Set up a copy of the stack pointer for use loading and storing any
4894   // arguments that may not fit in the registers available for argument
4895   // passing.
4896   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4897
4898   // Figure out which arguments are going to go in registers, and which in
4899   // memory.  Also, if this is a vararg function, floating point operations
4900   // must be stored to our stack, and loaded into integer regs as well, if
4901   // any integer regs are available for argument passing.
4902   unsigned ArgOffset = LinkageSize;
4903
4904   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4905   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4906
4907   SmallVector<SDValue, 8> MemOpChains;
4908   for (unsigned i = 0; i != NumOps; ++i) {
4909     SDValue Arg = OutVals[i];
4910     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4911     EVT ArgVT = Outs[i].VT;
4912     EVT OrigVT = Outs[i].ArgVT;
4913
4914     // PtrOff will be used to store the current argument to the stack if a
4915     // register cannot be found for it.
4916     SDValue PtrOff;
4917
4918     // We re-align the argument offset for each argument, except when using the
4919     // fast calling convention, when we need to make sure we do that only when
4920     // we'll actually use a stack slot.
4921     auto ComputePtrOff = [&]() {
4922       /* Respect alignment of argument on the stack.  */
4923       unsigned Align =
4924         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4925       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4926
4927       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4928
4929       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4930     };
4931
4932     if (CallConv != CallingConv::Fast) {
4933       ComputePtrOff();
4934
4935       /* Compute GPR index associated with argument offset.  */
4936       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4937       GPR_idx = std::min(GPR_idx, NumGPRs);
4938     }
4939
4940     // Promote integers to 64-bit values.
4941     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4942       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4943       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4944       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4945     }
4946
4947     // FIXME memcpy is used way more than necessary.  Correctness first.
4948     // Note: "by value" is code for passing a structure by value, not
4949     // basic types.
4950     if (Flags.isByVal()) {
4951       // Note: Size includes alignment padding, so
4952       //   struct x { short a; char b; }
4953       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4954       // These are the proper values we need for right-justifying the
4955       // aggregate in a parameter register.
4956       unsigned Size = Flags.getByValSize();
4957
4958       // An empty aggregate parameter takes up no storage and no
4959       // registers.
4960       if (Size == 0)
4961         continue;
4962
4963       if (CallConv == CallingConv::Fast)
4964         ComputePtrOff();
4965
4966       // All aggregates smaller than 8 bytes must be passed right-justified.
4967       if (Size==1 || Size==2 || Size==4) {
4968         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4969         if (GPR_idx != NumGPRs) {
4970           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4971                                         MachinePointerInfo(), VT,
4972                                         false, false, false, 0);
4973           MemOpChains.push_back(Load.getValue(1));
4974           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4975
4976           ArgOffset += PtrByteSize;
4977           continue;
4978         }
4979       }
4980
4981       if (GPR_idx == NumGPRs && Size < 8) {
4982         SDValue AddPtr = PtrOff;
4983         if (!isLittleEndian) {
4984           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4985                                           PtrOff.getValueType());
4986           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4987         }
4988         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4989                                                           CallSeqStart,
4990                                                           Flags, DAG, dl);
4991         ArgOffset += PtrByteSize;
4992         continue;
4993       }
4994       // Copy entire object into memory.  There are cases where gcc-generated
4995       // code assumes it is there, even if it could be put entirely into
4996       // registers.  (This is not what the doc says.)
4997
4998       // FIXME: The above statement is likely due to a misunderstanding of the
4999       // documents.  All arguments must be copied into the parameter area BY
5000       // THE CALLEE in the event that the callee takes the address of any
5001       // formal argument.  That has not yet been implemented.  However, it is
5002       // reasonable to use the stack area as a staging area for the register
5003       // load.
5004
5005       // Skip this for small aggregates, as we will use the same slot for a
5006       // right-justified copy, below.
5007       if (Size >= 8)
5008         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5009                                                           CallSeqStart,
5010                                                           Flags, DAG, dl);
5011
5012       // When a register is available, pass a small aggregate right-justified.
5013       if (Size < 8 && GPR_idx != NumGPRs) {
5014         // The easiest way to get this right-justified in a register
5015         // is to copy the structure into the rightmost portion of a
5016         // local variable slot, then load the whole slot into the
5017         // register.
5018         // FIXME: The memcpy seems to produce pretty awful code for
5019         // small aggregates, particularly for packed ones.
5020         // FIXME: It would be preferable to use the slot in the
5021         // parameter save area instead of a new local variable.
5022         SDValue AddPtr = PtrOff;
5023         if (!isLittleEndian) {
5024           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5025           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5026         }
5027         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5028                                                           CallSeqStart,
5029                                                           Flags, DAG, dl);
5030
5031         // Load the slot into the register.
5032         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
5033                                    MachinePointerInfo(),
5034                                    false, false, false, 0);
5035         MemOpChains.push_back(Load.getValue(1));
5036         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5037
5038         // Done with this argument.
5039         ArgOffset += PtrByteSize;
5040         continue;
5041       }
5042
5043       // For aggregates larger than PtrByteSize, copy the pieces of the
5044       // object that fit into registers from the parameter save area.
5045       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5046         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5047         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5048         if (GPR_idx != NumGPRs) {
5049           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5050                                      MachinePointerInfo(),
5051                                      false, false, false, 0);
5052           MemOpChains.push_back(Load.getValue(1));
5053           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5054           ArgOffset += PtrByteSize;
5055         } else {
5056           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5057           break;
5058         }
5059       }
5060       continue;
5061     }
5062
5063     switch (Arg.getSimpleValueType().SimpleTy) {
5064     default: llvm_unreachable("Unexpected ValueType for argument!");
5065     case MVT::i1:
5066     case MVT::i32:
5067     case MVT::i64:
5068       if (Flags.isNest()) {
5069         // The 'nest' parameter, if any, is passed in R11.
5070         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5071         hasNest = true;
5072         break;
5073       }
5074
5075       // These can be scalar arguments or elements of an integer array type
5076       // passed directly.  Clang may use those instead of "byval" aggregate
5077       // types to avoid forcing arguments to memory unnecessarily.
5078       if (GPR_idx != NumGPRs) {
5079         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5080       } else {
5081         if (CallConv == CallingConv::Fast)
5082           ComputePtrOff();
5083
5084         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5085                          true, isTailCall, false, MemOpChains,
5086                          TailCallArguments, dl);
5087         if (CallConv == CallingConv::Fast)
5088           ArgOffset += PtrByteSize;
5089       }
5090       if (CallConv != CallingConv::Fast)
5091         ArgOffset += PtrByteSize;
5092       break;
5093     case MVT::f32:
5094     case MVT::f64: {
5095       // These can be scalar arguments or elements of a float array type
5096       // passed directly.  The latter are used to implement ELFv2 homogenous
5097       // float aggregates.
5098
5099       // Named arguments go into FPRs first, and once they overflow, the
5100       // remaining arguments go into GPRs and then the parameter save area.
5101       // Unnamed arguments for vararg functions always go to GPRs and
5102       // then the parameter save area.  For now, put all arguments to vararg
5103       // routines always in both locations (FPR *and* GPR or stack slot).
5104       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5105       bool NeededLoad = false;
5106
5107       // First load the argument into the next available FPR.
5108       if (FPR_idx != NumFPRs)
5109         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5110
5111       // Next, load the argument into GPR or stack slot if needed.
5112       if (!NeedGPROrStack)
5113         ;
5114       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5115         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5116         // once we support fp <-> gpr moves.
5117
5118         // In the non-vararg case, this can only ever happen in the
5119         // presence of f32 array types, since otherwise we never run
5120         // out of FPRs before running out of GPRs.
5121         SDValue ArgVal;
5122
5123         // Double values are always passed in a single GPR.
5124         if (Arg.getValueType() != MVT::f32) {
5125           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5126
5127         // Non-array float values are extended and passed in a GPR.
5128         } else if (!Flags.isInConsecutiveRegs()) {
5129           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5130           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5131
5132         // If we have an array of floats, we collect every odd element
5133         // together with its predecessor into one GPR.
5134         } else if (ArgOffset % PtrByteSize != 0) {
5135           SDValue Lo, Hi;
5136           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5137           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5138           if (!isLittleEndian)
5139             std::swap(Lo, Hi);
5140           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5141
5142         // The final element, if even, goes into the first half of a GPR.
5143         } else if (Flags.isInConsecutiveRegsLast()) {
5144           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5145           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5146           if (!isLittleEndian)
5147             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5148                                  DAG.getConstant(32, dl, MVT::i32));
5149
5150         // Non-final even elements are skipped; they will be handled
5151         // together the with subsequent argument on the next go-around.
5152         } else
5153           ArgVal = SDValue();
5154
5155         if (ArgVal.getNode())
5156           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5157       } else {
5158         if (CallConv == CallingConv::Fast)
5159           ComputePtrOff();
5160
5161         // Single-precision floating-point values are mapped to the
5162         // second (rightmost) word of the stack doubleword.
5163         if (Arg.getValueType() == MVT::f32 &&
5164             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5165           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5166           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5167         }
5168
5169         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5170                          true, isTailCall, false, MemOpChains,
5171                          TailCallArguments, dl);
5172
5173         NeededLoad = true;
5174       }
5175       // When passing an array of floats, the array occupies consecutive
5176       // space in the argument area; only round up to the next doubleword
5177       // at the end of the array.  Otherwise, each float takes 8 bytes.
5178       if (CallConv != CallingConv::Fast || NeededLoad) {
5179         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5180                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5181         if (Flags.isInConsecutiveRegsLast())
5182           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5183       }
5184       break;
5185     }
5186     case MVT::v4f32:
5187     case MVT::v4i32:
5188     case MVT::v8i16:
5189     case MVT::v16i8:
5190     case MVT::v2f64:
5191     case MVT::v2i64:
5192     case MVT::v1i128:
5193       if (!Subtarget.hasQPX()) {
5194       // These can be scalar arguments or elements of a vector array type
5195       // passed directly.  The latter are used to implement ELFv2 homogenous
5196       // vector aggregates.
5197
5198       // For a varargs call, named arguments go into VRs or on the stack as
5199       // usual; unnamed arguments always go to the stack or the corresponding
5200       // GPRs when within range.  For now, we always put the value in both
5201       // locations (or even all three).
5202       if (isVarArg) {
5203         // We could elide this store in the case where the object fits
5204         // entirely in R registers.  Maybe later.
5205         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5206                                      MachinePointerInfo(), false, false, 0);
5207         MemOpChains.push_back(Store);
5208         if (VR_idx != NumVRs) {
5209           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5210                                      MachinePointerInfo(),
5211                                      false, false, false, 0);
5212           MemOpChains.push_back(Load.getValue(1));
5213
5214           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5215                            Arg.getSimpleValueType() == MVT::v2i64) ?
5216                           VSRH[VR_idx] : VR[VR_idx];
5217           ++VR_idx;
5218
5219           RegsToPass.push_back(std::make_pair(VReg, Load));
5220         }
5221         ArgOffset += 16;
5222         for (unsigned i=0; i<16; i+=PtrByteSize) {
5223           if (GPR_idx == NumGPRs)
5224             break;
5225           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5226                                    DAG.getConstant(i, dl, PtrVT));
5227           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5228                                      false, false, false, 0);
5229           MemOpChains.push_back(Load.getValue(1));
5230           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5231         }
5232         break;
5233       }
5234
5235       // Non-varargs Altivec params go into VRs or on the stack.
5236       if (VR_idx != NumVRs) {
5237         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5238                          Arg.getSimpleValueType() == MVT::v2i64) ?
5239                         VSRH[VR_idx] : VR[VR_idx];
5240         ++VR_idx;
5241
5242         RegsToPass.push_back(std::make_pair(VReg, Arg));
5243       } else {
5244         if (CallConv == CallingConv::Fast)
5245           ComputePtrOff();
5246
5247         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5248                          true, isTailCall, true, MemOpChains,
5249                          TailCallArguments, dl);
5250         if (CallConv == CallingConv::Fast)
5251           ArgOffset += 16;
5252       }
5253
5254       if (CallConv != CallingConv::Fast)
5255         ArgOffset += 16;
5256       break;
5257       } // not QPX
5258
5259       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5260              "Invalid QPX parameter type");
5261
5262       /* fall through */
5263     case MVT::v4f64:
5264     case MVT::v4i1: {
5265       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5266       if (isVarArg) {
5267         // We could elide this store in the case where the object fits
5268         // entirely in R registers.  Maybe later.
5269         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5270                                      MachinePointerInfo(), false, false, 0);
5271         MemOpChains.push_back(Store);
5272         if (QFPR_idx != NumQFPRs) {
5273           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5274                                      Store, PtrOff, MachinePointerInfo(),
5275                                      false, false, false, 0);
5276           MemOpChains.push_back(Load.getValue(1));
5277           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5278         }
5279         ArgOffset += (IsF32 ? 16 : 32);
5280         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5281           if (GPR_idx == NumGPRs)
5282             break;
5283           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5284                                    DAG.getConstant(i, dl, PtrVT));
5285           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5286                                      false, false, false, 0);
5287           MemOpChains.push_back(Load.getValue(1));
5288           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5289         }
5290         break;
5291       }
5292
5293       // Non-varargs QPX params go into registers or on the stack.
5294       if (QFPR_idx != NumQFPRs) {
5295         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5296       } else {
5297         if (CallConv == CallingConv::Fast)
5298           ComputePtrOff();
5299
5300         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5301                          true, isTailCall, true, MemOpChains,
5302                          TailCallArguments, dl);
5303         if (CallConv == CallingConv::Fast)
5304           ArgOffset += (IsF32 ? 16 : 32);
5305       }
5306
5307       if (CallConv != CallingConv::Fast)
5308         ArgOffset += (IsF32 ? 16 : 32);
5309       break;
5310       }
5311     }
5312   }
5313
5314   assert(NumBytesActuallyUsed == ArgOffset);
5315   (void)NumBytesActuallyUsed;
5316
5317   if (!MemOpChains.empty())
5318     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5319
5320   // Check if this is an indirect call (MTCTR/BCTRL).
5321   // See PrepareCall() for more information about calls through function
5322   // pointers in the 64-bit SVR4 ABI.
5323   if (!isTailCall && !IsPatchPoint &&
5324       !isFunctionGlobalAddress(Callee) &&
5325       !isa<ExternalSymbolSDNode>(Callee)) {
5326     // Load r2 into a virtual register and store it to the TOC save area.
5327     setUsesTOCBasePtr(DAG);
5328     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5329     // TOC save area offset.
5330     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5331     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5332     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5333     Chain = DAG.getStore(
5334         Val.getValue(1), dl, Val, AddPtr,
5335         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset),
5336         false, false, 0);
5337     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5338     // This does not mean the MTCTR instruction must use R12; it's easier
5339     // to model this as an extra parameter, so do that.
5340     if (isELFv2ABI && !IsPatchPoint)
5341       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5342   }
5343
5344   // Build a sequence of copy-to-reg nodes chained together with token chain
5345   // and flag operands which copy the outgoing args into the appropriate regs.
5346   SDValue InFlag;
5347   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5348     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5349                              RegsToPass[i].second, InFlag);
5350     InFlag = Chain.getValue(1);
5351   }
5352
5353   if (isTailCall)
5354     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5355                     FPOp, true, TailCallArguments);
5356
5357   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, hasNest,
5358                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5359                     SPDiff, NumBytes, Ins, InVals, CS);
5360 }
5361
5362 SDValue
5363 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5364                                     CallingConv::ID CallConv, bool isVarArg,
5365                                     bool isTailCall, bool IsPatchPoint,
5366                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5367                                     const SmallVectorImpl<SDValue> &OutVals,
5368                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5369                                     SDLoc dl, SelectionDAG &DAG,
5370                                     SmallVectorImpl<SDValue> &InVals,
5371                                     ImmutableCallSite *CS) const {
5372
5373   unsigned NumOps = Outs.size();
5374
5375   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5376   bool isPPC64 = PtrVT == MVT::i64;
5377   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5378
5379   MachineFunction &MF = DAG.getMachineFunction();
5380
5381   // Mark this function as potentially containing a function that contains a
5382   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5383   // and restoring the callers stack pointer in this functions epilog. This is
5384   // done because by tail calling the called function might overwrite the value
5385   // in this function's (MF) stack pointer stack slot 0(SP).
5386   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5387       CallConv == CallingConv::Fast)
5388     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5389
5390   // Count how many bytes are to be pushed on the stack, including the linkage
5391   // area, and parameter passing area.  We start with 24/48 bytes, which is
5392   // prereserved space for [SP][CR][LR][3 x unused].
5393   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5394   unsigned NumBytes = LinkageSize;
5395
5396   // Add up all the space actually used.
5397   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5398   // they all go in registers, but we must reserve stack space for them for
5399   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5400   // assigned stack space in order, with padding so Altivec parameters are
5401   // 16-byte aligned.
5402   unsigned nAltivecParamsAtEnd = 0;
5403   for (unsigned i = 0; i != NumOps; ++i) {
5404     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5405     EVT ArgVT = Outs[i].VT;
5406     // Varargs Altivec parameters are padded to a 16 byte boundary.
5407     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5408         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5409         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5410       if (!isVarArg && !isPPC64) {
5411         // Non-varargs Altivec parameters go after all the non-Altivec
5412         // parameters; handle those later so we know how much padding we need.
5413         nAltivecParamsAtEnd++;
5414         continue;
5415       }
5416       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5417       NumBytes = ((NumBytes+15)/16)*16;
5418     }
5419     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5420   }
5421
5422   // Allow for Altivec parameters at the end, if needed.
5423   if (nAltivecParamsAtEnd) {
5424     NumBytes = ((NumBytes+15)/16)*16;
5425     NumBytes += 16*nAltivecParamsAtEnd;
5426   }
5427
5428   // The prolog code of the callee may store up to 8 GPR argument registers to
5429   // the stack, allowing va_start to index over them in memory if its varargs.
5430   // Because we cannot tell if this is needed on the caller side, we have to
5431   // conservatively assume that it is needed.  As such, make sure we have at
5432   // least enough stack space for the caller to store the 8 GPRs.
5433   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5434
5435   // Tail call needs the stack to be aligned.
5436   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5437       CallConv == CallingConv::Fast)
5438     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5439
5440   // Calculate by how many bytes the stack has to be adjusted in case of tail
5441   // call optimization.
5442   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5443
5444   // To protect arguments on the stack from being clobbered in a tail call,
5445   // force all the loads to happen before doing any other lowering.
5446   if (isTailCall)
5447     Chain = DAG.getStackArgumentTokenFactor(Chain);
5448
5449   // Adjust the stack pointer for the new arguments...
5450   // These operations are automatically eliminated by the prolog/epilog pass
5451   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5452                                dl);
5453   SDValue CallSeqStart = Chain;
5454
5455   // Load the return address and frame pointer so it can be move somewhere else
5456   // later.
5457   SDValue LROp, FPOp;
5458   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5459                                        dl);
5460
5461   // Set up a copy of the stack pointer for use loading and storing any
5462   // arguments that may not fit in the registers available for argument
5463   // passing.
5464   SDValue StackPtr;
5465   if (isPPC64)
5466     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5467   else
5468     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5469
5470   // Figure out which arguments are going to go in registers, and which in
5471   // memory.  Also, if this is a vararg function, floating point operations
5472   // must be stored to our stack, and loaded into integer regs as well, if
5473   // any integer regs are available for argument passing.
5474   unsigned ArgOffset = LinkageSize;
5475   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5476
5477   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5478     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5479     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5480   };
5481   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5482     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5483     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5484   };
5485   static const MCPhysReg VR[] = {
5486     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5487     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5488   };
5489   const unsigned NumGPRs = array_lengthof(GPR_32);
5490   const unsigned NumFPRs = 13;
5491   const unsigned NumVRs  = array_lengthof(VR);
5492
5493   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5494
5495   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5496   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5497
5498   SmallVector<SDValue, 8> MemOpChains;
5499   for (unsigned i = 0; i != NumOps; ++i) {
5500     SDValue Arg = OutVals[i];
5501     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5502
5503     // PtrOff will be used to store the current argument to the stack if a
5504     // register cannot be found for it.
5505     SDValue PtrOff;
5506
5507     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5508
5509     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5510
5511     // On PPC64, promote integers to 64-bit values.
5512     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5513       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5514       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5515       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5516     }
5517
5518     // FIXME memcpy is used way more than necessary.  Correctness first.
5519     // Note: "by value" is code for passing a structure by value, not
5520     // basic types.
5521     if (Flags.isByVal()) {
5522       unsigned Size = Flags.getByValSize();
5523       // Very small objects are passed right-justified.  Everything else is
5524       // passed left-justified.
5525       if (Size==1 || Size==2) {
5526         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5527         if (GPR_idx != NumGPRs) {
5528           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5529                                         MachinePointerInfo(), VT,
5530                                         false, false, false, 0);
5531           MemOpChains.push_back(Load.getValue(1));
5532           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5533
5534           ArgOffset += PtrByteSize;
5535         } else {
5536           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5537                                           PtrOff.getValueType());
5538           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5539           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5540                                                             CallSeqStart,
5541                                                             Flags, DAG, dl);
5542           ArgOffset += PtrByteSize;
5543         }
5544         continue;
5545       }
5546       // Copy entire object into memory.  There are cases where gcc-generated
5547       // code assumes it is there, even if it could be put entirely into
5548       // registers.  (This is not what the doc says.)
5549       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5550                                                         CallSeqStart,
5551                                                         Flags, DAG, dl);
5552
5553       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5554       // copy the pieces of the object that fit into registers from the
5555       // parameter save area.
5556       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5557         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5558         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5559         if (GPR_idx != NumGPRs) {
5560           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5561                                      MachinePointerInfo(),
5562                                      false, false, false, 0);
5563           MemOpChains.push_back(Load.getValue(1));
5564           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5565           ArgOffset += PtrByteSize;
5566         } else {
5567           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5568           break;
5569         }
5570       }
5571       continue;
5572     }
5573
5574     switch (Arg.getSimpleValueType().SimpleTy) {
5575     default: llvm_unreachable("Unexpected ValueType for argument!");
5576     case MVT::i1:
5577     case MVT::i32:
5578     case MVT::i64:
5579       if (GPR_idx != NumGPRs) {
5580         if (Arg.getValueType() == MVT::i1)
5581           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5582
5583         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5584       } else {
5585         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5586                          isPPC64, isTailCall, false, MemOpChains,
5587                          TailCallArguments, dl);
5588       }
5589       ArgOffset += PtrByteSize;
5590       break;
5591     case MVT::f32:
5592     case MVT::f64:
5593       if (FPR_idx != NumFPRs) {
5594         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5595
5596         if (isVarArg) {
5597           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5598                                        MachinePointerInfo(), false, false, 0);
5599           MemOpChains.push_back(Store);
5600
5601           // Float varargs are always shadowed in available integer registers
5602           if (GPR_idx != NumGPRs) {
5603             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5604                                        MachinePointerInfo(), false, false,
5605                                        false, 0);
5606             MemOpChains.push_back(Load.getValue(1));
5607             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5608           }
5609           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5610             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5611             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5612             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5613                                        MachinePointerInfo(),
5614                                        false, false, false, 0);
5615             MemOpChains.push_back(Load.getValue(1));
5616             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5617           }
5618         } else {
5619           // If we have any FPRs remaining, we may also have GPRs remaining.
5620           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5621           // GPRs.
5622           if (GPR_idx != NumGPRs)
5623             ++GPR_idx;
5624           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5625               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5626             ++GPR_idx;
5627         }
5628       } else
5629         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5630                          isPPC64, isTailCall, false, MemOpChains,
5631                          TailCallArguments, dl);
5632       if (isPPC64)
5633         ArgOffset += 8;
5634       else
5635         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5636       break;
5637     case MVT::v4f32:
5638     case MVT::v4i32:
5639     case MVT::v8i16:
5640     case MVT::v16i8:
5641       if (isVarArg) {
5642         // These go aligned on the stack, or in the corresponding R registers
5643         // when within range.  The Darwin PPC ABI doc claims they also go in
5644         // V registers; in fact gcc does this only for arguments that are
5645         // prototyped, not for those that match the ...  We do it for all
5646         // arguments, seems to work.
5647         while (ArgOffset % 16 !=0) {
5648           ArgOffset += PtrByteSize;
5649           if (GPR_idx != NumGPRs)
5650             GPR_idx++;
5651         }
5652         // We could elide this store in the case where the object fits
5653         // entirely in R registers.  Maybe later.
5654         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5655                              DAG.getConstant(ArgOffset, dl, PtrVT));
5656         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5657                                      MachinePointerInfo(), false, false, 0);
5658         MemOpChains.push_back(Store);
5659         if (VR_idx != NumVRs) {
5660           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5661                                      MachinePointerInfo(),
5662                                      false, false, false, 0);
5663           MemOpChains.push_back(Load.getValue(1));
5664           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5665         }
5666         ArgOffset += 16;
5667         for (unsigned i=0; i<16; i+=PtrByteSize) {
5668           if (GPR_idx == NumGPRs)
5669             break;
5670           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5671                                    DAG.getConstant(i, dl, PtrVT));
5672           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5673                                      false, false, false, 0);
5674           MemOpChains.push_back(Load.getValue(1));
5675           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5676         }
5677         break;
5678       }
5679
5680       // Non-varargs Altivec params generally go in registers, but have
5681       // stack space allocated at the end.
5682       if (VR_idx != NumVRs) {
5683         // Doesn't have GPR space allocated.
5684         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5685       } else if (nAltivecParamsAtEnd==0) {
5686         // We are emitting Altivec params in order.
5687         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5688                          isPPC64, isTailCall, true, MemOpChains,
5689                          TailCallArguments, dl);
5690         ArgOffset += 16;
5691       }
5692       break;
5693     }
5694   }
5695   // If all Altivec parameters fit in registers, as they usually do,
5696   // they get stack space following the non-Altivec parameters.  We
5697   // don't track this here because nobody below needs it.
5698   // If there are more Altivec parameters than fit in registers emit
5699   // the stores here.
5700   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5701     unsigned j = 0;
5702     // Offset is aligned; skip 1st 12 params which go in V registers.
5703     ArgOffset = ((ArgOffset+15)/16)*16;
5704     ArgOffset += 12*16;
5705     for (unsigned i = 0; i != NumOps; ++i) {
5706       SDValue Arg = OutVals[i];
5707       EVT ArgType = Outs[i].VT;
5708       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5709           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5710         if (++j > NumVRs) {
5711           SDValue PtrOff;
5712           // We are emitting Altivec params in order.
5713           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5714                            isPPC64, isTailCall, true, MemOpChains,
5715                            TailCallArguments, dl);
5716           ArgOffset += 16;
5717         }
5718       }
5719     }
5720   }
5721
5722   if (!MemOpChains.empty())
5723     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5724
5725   // On Darwin, R12 must contain the address of an indirect callee.  This does
5726   // not mean the MTCTR instruction must use R12; it's easier to model this as
5727   // an extra parameter, so do that.
5728   if (!isTailCall &&
5729       !isFunctionGlobalAddress(Callee) &&
5730       !isa<ExternalSymbolSDNode>(Callee) &&
5731       !isBLACompatibleAddress(Callee, DAG))
5732     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5733                                                    PPC::R12), Callee));
5734
5735   // Build a sequence of copy-to-reg nodes chained together with token chain
5736   // and flag operands which copy the outgoing args into the appropriate regs.
5737   SDValue InFlag;
5738   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5739     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5740                              RegsToPass[i].second, InFlag);
5741     InFlag = Chain.getValue(1);
5742   }
5743
5744   if (isTailCall)
5745     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5746                     FPOp, true, TailCallArguments);
5747
5748   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint,
5749                     /* unused except on PPC64 ELFv1 */ false, DAG,
5750                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5751                     NumBytes, Ins, InVals, CS);
5752 }
5753
5754 bool
5755 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5756                                   MachineFunction &MF, bool isVarArg,
5757                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5758                                   LLVMContext &Context) const {
5759   SmallVector<CCValAssign, 16> RVLocs;
5760   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5761   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5762 }
5763
5764 SDValue
5765 PPCTargetLowering::LowerReturn(SDValue Chain,
5766                                CallingConv::ID CallConv, bool isVarArg,
5767                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5768                                const SmallVectorImpl<SDValue> &OutVals,
5769                                SDLoc dl, SelectionDAG &DAG) const {
5770
5771   SmallVector<CCValAssign, 16> RVLocs;
5772   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5773                  *DAG.getContext());
5774   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5775
5776   SDValue Flag;
5777   SmallVector<SDValue, 4> RetOps(1, Chain);
5778
5779   // Copy the result values into the output registers.
5780   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5781     CCValAssign &VA = RVLocs[i];
5782     assert(VA.isRegLoc() && "Can only return in registers!");
5783
5784     SDValue Arg = OutVals[i];
5785
5786     switch (VA.getLocInfo()) {
5787     default: llvm_unreachable("Unknown loc info!");
5788     case CCValAssign::Full: break;
5789     case CCValAssign::AExt:
5790       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5791       break;
5792     case CCValAssign::ZExt:
5793       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5794       break;
5795     case CCValAssign::SExt:
5796       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5797       break;
5798     }
5799
5800     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5801     Flag = Chain.getValue(1);
5802     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5803   }
5804
5805   RetOps[0] = Chain;  // Update chain.
5806
5807   // Add the flag if we have it.
5808   if (Flag.getNode())
5809     RetOps.push_back(Flag);
5810
5811   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5812 }
5813
5814 SDValue PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(
5815     SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const {
5816   SDLoc dl(Op);
5817
5818   // Get the corect type for integers.
5819   EVT IntVT = Op.getValueType();
5820
5821   // Get the inputs.
5822   SDValue Chain = Op.getOperand(0);
5823   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5824   // Build a DYNAREAOFFSET node.
5825   SDValue Ops[2] = {Chain, FPSIdx};
5826   SDVTList VTs = DAG.getVTList(IntVT);
5827   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
5828 }
5829
5830 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5831                                    const PPCSubtarget &Subtarget) const {
5832   // When we pop the dynamic allocation we need to restore the SP link.
5833   SDLoc dl(Op);
5834
5835   // Get the corect type for pointers.
5836   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5837
5838   // Construct the stack pointer operand.
5839   bool isPPC64 = Subtarget.isPPC64();
5840   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5841   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5842
5843   // Get the operands for the STACKRESTORE.
5844   SDValue Chain = Op.getOperand(0);
5845   SDValue SaveSP = Op.getOperand(1);
5846
5847   // Load the old link SP.
5848   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5849                                    MachinePointerInfo(),
5850                                    false, false, false, 0);
5851
5852   // Restore the stack pointer.
5853   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5854
5855   // Store the old link SP.
5856   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5857                       false, false, 0);
5858 }
5859
5860 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
5861   MachineFunction &MF = DAG.getMachineFunction();
5862   bool isPPC64 = Subtarget.isPPC64();
5863   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5864
5865   // Get current frame pointer save index.  The users of this index will be
5866   // primarily DYNALLOC instructions.
5867   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5868   int RASI = FI->getReturnAddrSaveIndex();
5869
5870   // If the frame pointer save index hasn't been defined yet.
5871   if (!RASI) {
5872     // Find out what the fix offset of the frame pointer save area.
5873     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5874     // Allocate the frame index for frame pointer save area.
5875     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5876     // Save the result.
5877     FI->setReturnAddrSaveIndex(RASI);
5878   }
5879   return DAG.getFrameIndex(RASI, PtrVT);
5880 }
5881
5882 SDValue
5883 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5884   MachineFunction &MF = DAG.getMachineFunction();
5885   bool isPPC64 = Subtarget.isPPC64();
5886   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
5887
5888   // Get current frame pointer save index.  The users of this index will be
5889   // primarily DYNALLOC instructions.
5890   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5891   int FPSI = FI->getFramePointerSaveIndex();
5892
5893   // If the frame pointer save index hasn't been defined yet.
5894   if (!FPSI) {
5895     // Find out what the fix offset of the frame pointer save area.
5896     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5897     // Allocate the frame index for frame pointer save area.
5898     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5899     // Save the result.
5900     FI->setFramePointerSaveIndex(FPSI);
5901   }
5902   return DAG.getFrameIndex(FPSI, PtrVT);
5903 }
5904
5905 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5906                                          SelectionDAG &DAG,
5907                                          const PPCSubtarget &Subtarget) const {
5908   // Get the inputs.
5909   SDValue Chain = Op.getOperand(0);
5910   SDValue Size  = Op.getOperand(1);
5911   SDLoc dl(Op);
5912
5913   // Get the corect type for pointers.
5914   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5915   // Negate the size.
5916   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5917                                 DAG.getConstant(0, dl, PtrVT), Size);
5918   // Construct a node for the frame pointer save index.
5919   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5920   // Build a DYNALLOC node.
5921   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5922   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5923   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5924 }
5925
5926 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5927                                                SelectionDAG &DAG) const {
5928   SDLoc DL(Op);
5929   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5930                      DAG.getVTList(MVT::i32, MVT::Other),
5931                      Op.getOperand(0), Op.getOperand(1));
5932 }
5933
5934 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5935                                                 SelectionDAG &DAG) const {
5936   SDLoc DL(Op);
5937   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5938                      Op.getOperand(0), Op.getOperand(1));
5939 }
5940
5941 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5942   if (Op.getValueType().isVector())
5943     return LowerVectorLoad(Op, DAG);
5944
5945   assert(Op.getValueType() == MVT::i1 &&
5946          "Custom lowering only for i1 loads");
5947
5948   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5949
5950   SDLoc dl(Op);
5951   LoadSDNode *LD = cast<LoadSDNode>(Op);
5952
5953   SDValue Chain = LD->getChain();
5954   SDValue BasePtr = LD->getBasePtr();
5955   MachineMemOperand *MMO = LD->getMemOperand();
5956
5957   SDValue NewLD =
5958       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
5959                      BasePtr, MVT::i8, MMO);
5960   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5961
5962   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5963   return DAG.getMergeValues(Ops, dl);
5964 }
5965
5966 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5967   if (Op.getOperand(1).getValueType().isVector())
5968     return LowerVectorStore(Op, DAG);
5969
5970   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5971          "Custom lowering only for i1 stores");
5972
5973   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5974
5975   SDLoc dl(Op);
5976   StoreSDNode *ST = cast<StoreSDNode>(Op);
5977
5978   SDValue Chain = ST->getChain();
5979   SDValue BasePtr = ST->getBasePtr();
5980   SDValue Value = ST->getValue();
5981   MachineMemOperand *MMO = ST->getMemOperand();
5982
5983   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
5984                       Value);
5985   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5986 }
5987
5988 // FIXME: Remove this once the ANDI glue bug is fixed:
5989 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5990   assert(Op.getValueType() == MVT::i1 &&
5991          "Custom lowering only for i1 results");
5992
5993   SDLoc DL(Op);
5994   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5995                      Op.getOperand(0));
5996 }
5997
5998 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5999 /// possible.
6000 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6001   // Not FP? Not a fsel.
6002   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6003       !Op.getOperand(2).getValueType().isFloatingPoint())
6004     return Op;
6005
6006   // We might be able to do better than this under some circumstances, but in
6007   // general, fsel-based lowering of select is a finite-math-only optimization.
6008   // For more information, see section F.3 of the 2.06 ISA specification.
6009   if (!DAG.getTarget().Options.NoInfsFPMath ||
6010       !DAG.getTarget().Options.NoNaNsFPMath)
6011     return Op;
6012   // TODO: Propagate flags from the select rather than global settings.
6013   SDNodeFlags Flags;
6014   Flags.setNoInfs(true);
6015   Flags.setNoNaNs(true);
6016
6017   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6018
6019   EVT ResVT = Op.getValueType();
6020   EVT CmpVT = Op.getOperand(0).getValueType();
6021   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6022   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6023   SDLoc dl(Op);
6024
6025   // If the RHS of the comparison is a 0.0, we don't need to do the
6026   // subtraction at all.
6027   SDValue Sel1;
6028   if (isFloatingPointZero(RHS))
6029     switch (CC) {
6030     default: break;       // SETUO etc aren't handled by fsel.
6031     case ISD::SETNE:
6032       std::swap(TV, FV);
6033     case ISD::SETEQ:
6034       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6035         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6036       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6037       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6038         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6039       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6040                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6041     case ISD::SETULT:
6042     case ISD::SETLT:
6043       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6044     case ISD::SETOGE:
6045     case ISD::SETGE:
6046       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6047         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6048       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6049     case ISD::SETUGT:
6050     case ISD::SETGT:
6051       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6052     case ISD::SETOLE:
6053     case ISD::SETLE:
6054       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6055         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6056       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6057                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6058     }
6059
6060   SDValue Cmp;
6061   switch (CC) {
6062   default: break;       // SETUO etc aren't handled by fsel.
6063   case ISD::SETNE:
6064     std::swap(TV, FV);
6065   case ISD::SETEQ:
6066     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6067     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6068       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6069     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6070     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6071       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6072     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6073                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6074   case ISD::SETULT:
6075   case ISD::SETLT:
6076     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6077     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6078       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6079     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6080   case ISD::SETOGE:
6081   case ISD::SETGE:
6082     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags);
6083     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6084       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6085     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6086   case ISD::SETUGT:
6087   case ISD::SETGT:
6088     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6089     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6090       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6091     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6092   case ISD::SETOLE:
6093   case ISD::SETLE:
6094     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags);
6095     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6096       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6097     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6098   }
6099   return Op;
6100 }
6101
6102 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6103                                                SelectionDAG &DAG,
6104                                                SDLoc dl) const {
6105   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6106   SDValue Src = Op.getOperand(0);
6107   if (Src.getValueType() == MVT::f32)
6108     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6109
6110   SDValue Tmp;
6111   switch (Op.getSimpleValueType().SimpleTy) {
6112   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6113   case MVT::i32:
6114     Tmp = DAG.getNode(
6115         Op.getOpcode() == ISD::FP_TO_SINT
6116             ? PPCISD::FCTIWZ
6117             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6118         dl, MVT::f64, Src);
6119     break;
6120   case MVT::i64:
6121     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6122            "i64 FP_TO_UINT is supported only with FPCVT");
6123     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6124                                                         PPCISD::FCTIDUZ,
6125                       dl, MVT::f64, Src);
6126     break;
6127   }
6128
6129   // Convert the FP value to an int value through memory.
6130   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6131     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6132   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6133   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6134   MachinePointerInfo MPI =
6135       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6136
6137   // Emit a store to the stack slot.
6138   SDValue Chain;
6139   if (i32Stack) {
6140     MachineFunction &MF = DAG.getMachineFunction();
6141     MachineMemOperand *MMO =
6142       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6143     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6144     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6145               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6146   } else
6147     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
6148                          MPI, false, false, 0);
6149
6150   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6151   // add in a bias.
6152   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6153     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6154                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6155     MPI = MPI.getWithOffset(4);
6156   }
6157
6158   RLI.Chain = Chain;
6159   RLI.Ptr = FIPtr;
6160   RLI.MPI = MPI;
6161 }
6162
6163 /// \brief Custom lowers floating point to integer conversions to use
6164 /// the direct move instructions available in ISA 2.07 to avoid the
6165 /// need for load/store combinations.
6166 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6167                                                     SelectionDAG &DAG,
6168                                                     SDLoc dl) const {
6169   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6170   SDValue Src = Op.getOperand(0);
6171
6172   if (Src.getValueType() == MVT::f32)
6173     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6174
6175   SDValue Tmp;
6176   switch (Op.getSimpleValueType().SimpleTy) {
6177   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6178   case MVT::i32:
6179     Tmp = DAG.getNode(
6180         Op.getOpcode() == ISD::FP_TO_SINT
6181             ? PPCISD::FCTIWZ
6182             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6183         dl, MVT::f64, Src);
6184     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6185     break;
6186   case MVT::i64:
6187     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6188            "i64 FP_TO_UINT is supported only with FPCVT");
6189     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6190                                                         PPCISD::FCTIDUZ,
6191                       dl, MVT::f64, Src);
6192     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6193     break;
6194   }
6195   return Tmp;
6196 }
6197
6198 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6199                                           SDLoc dl) const {
6200   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6201     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6202
6203   ReuseLoadInfo RLI;
6204   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6205
6206   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6207                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6208                      RLI.Ranges);
6209 }
6210
6211 // We're trying to insert a regular store, S, and then a load, L. If the
6212 // incoming value, O, is a load, we might just be able to have our load use the
6213 // address used by O. However, we don't know if anything else will store to
6214 // that address before we can load from it. To prevent this situation, we need
6215 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6216 // the same chain operand as O, we create a token factor from the chain results
6217 // of O and L, and we replace all uses of O's chain result with that token
6218 // factor (see spliceIntoChain below for this last part).
6219 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6220                                             ReuseLoadInfo &RLI,
6221                                             SelectionDAG &DAG,
6222                                             ISD::LoadExtType ET) const {
6223   SDLoc dl(Op);
6224   if (ET == ISD::NON_EXTLOAD &&
6225       (Op.getOpcode() == ISD::FP_TO_UINT ||
6226        Op.getOpcode() == ISD::FP_TO_SINT) &&
6227       isOperationLegalOrCustom(Op.getOpcode(),
6228                                Op.getOperand(0).getValueType())) {
6229
6230     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6231     return true;
6232   }
6233
6234   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6235   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6236       LD->isNonTemporal())
6237     return false;
6238   if (LD->getMemoryVT() != MemVT)
6239     return false;
6240
6241   RLI.Ptr = LD->getBasePtr();
6242   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6243     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6244            "Non-pre-inc AM on PPC?");
6245     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6246                           LD->getOffset());
6247   }
6248
6249   RLI.Chain = LD->getChain();
6250   RLI.MPI = LD->getPointerInfo();
6251   RLI.IsInvariant = LD->isInvariant();
6252   RLI.Alignment = LD->getAlignment();
6253   RLI.AAInfo = LD->getAAInfo();
6254   RLI.Ranges = LD->getRanges();
6255
6256   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6257   return true;
6258 }
6259
6260 // Given the head of the old chain, ResChain, insert a token factor containing
6261 // it and NewResChain, and make users of ResChain now be users of that token
6262 // factor.
6263 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6264                                         SDValue NewResChain,
6265                                         SelectionDAG &DAG) const {
6266   if (!ResChain)
6267     return;
6268
6269   SDLoc dl(NewResChain);
6270
6271   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6272                            NewResChain, DAG.getUNDEF(MVT::Other));
6273   assert(TF.getNode() != NewResChain.getNode() &&
6274          "A new TF really is required here");
6275
6276   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6277   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6278 }
6279
6280 /// \brief Custom lowers integer to floating point conversions to use
6281 /// the direct move instructions available in ISA 2.07 to avoid the
6282 /// need for load/store combinations.
6283 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6284                                                     SelectionDAG &DAG,
6285                                                     SDLoc dl) const {
6286   assert((Op.getValueType() == MVT::f32 ||
6287           Op.getValueType() == MVT::f64) &&
6288          "Invalid floating point type as target of conversion");
6289   assert(Subtarget.hasFPCVT() &&
6290          "Int to FP conversions with direct moves require FPCVT");
6291   SDValue FP;
6292   SDValue Src = Op.getOperand(0);
6293   bool SinglePrec = Op.getValueType() == MVT::f32;
6294   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6295   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6296   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6297                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6298
6299   if (WordInt) {
6300     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6301                      dl, MVT::f64, Src);
6302     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6303   }
6304   else {
6305     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6306     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6307   }
6308
6309   return FP;
6310 }
6311
6312 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6313                                           SelectionDAG &DAG) const {
6314   SDLoc dl(Op);
6315
6316   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6317     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6318       return SDValue();
6319
6320     SDValue Value = Op.getOperand(0);
6321     // The values are now known to be -1 (false) or 1 (true). To convert this
6322     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6323     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6324     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6325
6326     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6327     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, FPHalfs, FPHalfs,
6328                           FPHalfs, FPHalfs);
6329
6330     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6331
6332     if (Op.getValueType() != MVT::v4f64)
6333       Value = DAG.getNode(ISD::FP_ROUND, dl,
6334                           Op.getValueType(), Value,
6335                           DAG.getIntPtrConstant(1, dl));
6336     return Value;
6337   }
6338
6339   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6340   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6341     return SDValue();
6342
6343   if (Op.getOperand(0).getValueType() == MVT::i1)
6344     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6345                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6346                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6347
6348   // If we have direct moves, we can do all the conversion, skip the store/load
6349   // however, without FPCVT we can't do most conversions.
6350   if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6351     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6352
6353   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6354          "UINT_TO_FP is supported only with FPCVT");
6355
6356   // If we have FCFIDS, then use it when converting to single-precision.
6357   // Otherwise, convert to double-precision and then round.
6358   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6359                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6360                                                             : PPCISD::FCFIDS)
6361                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6362                                                             : PPCISD::FCFID);
6363   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6364                   ? MVT::f32
6365                   : MVT::f64;
6366
6367   if (Op.getOperand(0).getValueType() == MVT::i64) {
6368     SDValue SINT = Op.getOperand(0);
6369     // When converting to single-precision, we actually need to convert
6370     // to double-precision first and then round to single-precision.
6371     // To avoid double-rounding effects during that operation, we have
6372     // to prepare the input operand.  Bits that might be truncated when
6373     // converting to double-precision are replaced by a bit that won't
6374     // be lost at this stage, but is below the single-precision rounding
6375     // position.
6376     //
6377     // However, if -enable-unsafe-fp-math is in effect, accept double
6378     // rounding to avoid the extra overhead.
6379     if (Op.getValueType() == MVT::f32 &&
6380         !Subtarget.hasFPCVT() &&
6381         !DAG.getTarget().Options.UnsafeFPMath) {
6382
6383       // Twiddle input to make sure the low 11 bits are zero.  (If this
6384       // is the case, we are guaranteed the value will fit into the 53 bit
6385       // mantissa of an IEEE double-precision value without rounding.)
6386       // If any of those low 11 bits were not zero originally, make sure
6387       // bit 12 (value 2048) is set instead, so that the final rounding
6388       // to single-precision gets the correct result.
6389       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6390                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6391       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6392                           Round, DAG.getConstant(2047, dl, MVT::i64));
6393       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6394       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6395                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6396
6397       // However, we cannot use that value unconditionally: if the magnitude
6398       // of the input value is small, the bit-twiddling we did above might
6399       // end up visibly changing the output.  Fortunately, in that case, we
6400       // don't need to twiddle bits since the original input will convert
6401       // exactly to double-precision floating-point already.  Therefore,
6402       // construct a conditional to use the original value if the top 11
6403       // bits are all sign-bit copies, and use the rounded value computed
6404       // above otherwise.
6405       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6406                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6407       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6408                          Cond, DAG.getConstant(1, dl, MVT::i64));
6409       Cond = DAG.getSetCC(dl, MVT::i32,
6410                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6411
6412       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6413     }
6414
6415     ReuseLoadInfo RLI;
6416     SDValue Bits;
6417
6418     MachineFunction &MF = DAG.getMachineFunction();
6419     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6420       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6421                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6422                          RLI.Ranges);
6423       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6424     } else if (Subtarget.hasLFIWAX() &&
6425                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6426       MachineMemOperand *MMO =
6427         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6428                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6429       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6430       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6431                                      DAG.getVTList(MVT::f64, MVT::Other),
6432                                      Ops, MVT::i32, MMO);
6433       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6434     } else if (Subtarget.hasFPCVT() &&
6435                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6436       MachineMemOperand *MMO =
6437         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6438                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6439       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6440       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6441                                      DAG.getVTList(MVT::f64, MVT::Other),
6442                                      Ops, MVT::i32, MMO);
6443       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6444     } else if (((Subtarget.hasLFIWAX() &&
6445                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6446                 (Subtarget.hasFPCVT() &&
6447                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6448                SINT.getOperand(0).getValueType() == MVT::i32) {
6449       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6450       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
6451
6452       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6453       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6454
6455       SDValue Store = DAG.getStore(
6456           DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6457           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6458           false, false, 0);
6459
6460       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6461              "Expected an i32 store");
6462
6463       RLI.Ptr = FIdx;
6464       RLI.Chain = Store;
6465       RLI.MPI =
6466           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6467       RLI.Alignment = 4;
6468
6469       MachineMemOperand *MMO =
6470         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6471                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6472       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6473       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6474                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6475                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6476                                      Ops, MVT::i32, MMO);
6477     } else
6478       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6479
6480     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6481
6482     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6483       FP = DAG.getNode(ISD::FP_ROUND, dl,
6484                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6485     return FP;
6486   }
6487
6488   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6489          "Unhandled INT_TO_FP type in custom expander!");
6490   // Since we only generate this in 64-bit mode, we can take advantage of
6491   // 64-bit registers.  In particular, sign extend the input value into the
6492   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6493   // then lfd it and fcfid it.
6494   MachineFunction &MF = DAG.getMachineFunction();
6495   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6496   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6497
6498   SDValue Ld;
6499   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6500     ReuseLoadInfo RLI;
6501     bool ReusingLoad;
6502     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6503                                             DAG))) {
6504       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6505       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6506
6507       SDValue Store = DAG.getStore(
6508           DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6509           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6510           false, false, 0);
6511
6512       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6513              "Expected an i32 store");
6514
6515       RLI.Ptr = FIdx;
6516       RLI.Chain = Store;
6517       RLI.MPI =
6518           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6519       RLI.Alignment = 4;
6520     }
6521
6522     MachineMemOperand *MMO =
6523       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6524                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6525     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6526     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6527                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6528                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6529                                  Ops, MVT::i32, MMO);
6530     if (ReusingLoad)
6531       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6532   } else {
6533     assert(Subtarget.isPPC64() &&
6534            "i32->FP without LFIWAX supported only on PPC64");
6535
6536     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6537     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6538
6539     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6540                                 Op.getOperand(0));
6541
6542     // STD the extended value into the stack slot.
6543     SDValue Store = DAG.getStore(
6544         DAG.getEntryNode(), dl, Ext64, FIdx,
6545         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6546         false, false, 0);
6547
6548     // Load the value as a double.
6549     Ld = DAG.getLoad(
6550         MVT::f64, dl, Store, FIdx,
6551         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx),
6552         false, false, false, 0);
6553   }
6554
6555   // FCFID it and return it.
6556   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6557   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6558     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6559                      DAG.getIntPtrConstant(0, dl));
6560   return FP;
6561 }
6562
6563 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6564                                             SelectionDAG &DAG) const {
6565   SDLoc dl(Op);
6566   /*
6567    The rounding mode is in bits 30:31 of FPSR, and has the following
6568    settings:
6569      00 Round to nearest
6570      01 Round to 0
6571      10 Round to +inf
6572      11 Round to -inf
6573
6574   FLT_ROUNDS, on the other hand, expects the following:
6575     -1 Undefined
6576      0 Round to 0
6577      1 Round to nearest
6578      2 Round to +inf
6579      3 Round to -inf
6580
6581   To perform the conversion, we do:
6582     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6583   */
6584
6585   MachineFunction &MF = DAG.getMachineFunction();
6586   EVT VT = Op.getValueType();
6587   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
6588
6589   // Save FP Control Word to register
6590   EVT NodeTys[] = {
6591     MVT::f64,    // return register
6592     MVT::Glue    // unused in this context
6593   };
6594   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6595
6596   // Save FP register to stack slot
6597   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6598   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6599   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6600                                StackSlot, MachinePointerInfo(), false, false,0);
6601
6602   // Load FP Control Word from low 32 bits of stack slot.
6603   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6604   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6605   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6606                             false, false, false, 0);
6607
6608   // Transform as necessary
6609   SDValue CWD1 =
6610     DAG.getNode(ISD::AND, dl, MVT::i32,
6611                 CWD, DAG.getConstant(3, dl, MVT::i32));
6612   SDValue CWD2 =
6613     DAG.getNode(ISD::SRL, dl, MVT::i32,
6614                 DAG.getNode(ISD::AND, dl, MVT::i32,
6615                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6616                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6617                             DAG.getConstant(3, dl, MVT::i32)),
6618                 DAG.getConstant(1, dl, MVT::i32));
6619
6620   SDValue RetVal =
6621     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6622
6623   return DAG.getNode((VT.getSizeInBits() < 16 ?
6624                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6625 }
6626
6627 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6628   EVT VT = Op.getValueType();
6629   unsigned BitWidth = VT.getSizeInBits();
6630   SDLoc dl(Op);
6631   assert(Op.getNumOperands() == 3 &&
6632          VT == Op.getOperand(1).getValueType() &&
6633          "Unexpected SHL!");
6634
6635   // Expand into a bunch of logical ops.  Note that these ops
6636   // depend on the PPC behavior for oversized shift amounts.
6637   SDValue Lo = Op.getOperand(0);
6638   SDValue Hi = Op.getOperand(1);
6639   SDValue Amt = Op.getOperand(2);
6640   EVT AmtVT = Amt.getValueType();
6641
6642   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6643                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6644   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6645   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6646   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6647   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6648                              DAG.getConstant(-BitWidth, dl, AmtVT));
6649   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6650   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6651   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6652   SDValue OutOps[] = { OutLo, OutHi };
6653   return DAG.getMergeValues(OutOps, dl);
6654 }
6655
6656 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6657   EVT VT = Op.getValueType();
6658   SDLoc dl(Op);
6659   unsigned BitWidth = VT.getSizeInBits();
6660   assert(Op.getNumOperands() == 3 &&
6661          VT == Op.getOperand(1).getValueType() &&
6662          "Unexpected SRL!");
6663
6664   // Expand into a bunch of logical ops.  Note that these ops
6665   // depend on the PPC behavior for oversized shift amounts.
6666   SDValue Lo = Op.getOperand(0);
6667   SDValue Hi = Op.getOperand(1);
6668   SDValue Amt = Op.getOperand(2);
6669   EVT AmtVT = Amt.getValueType();
6670
6671   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6672                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6673   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6674   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6675   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6676   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6677                              DAG.getConstant(-BitWidth, dl, AmtVT));
6678   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6679   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6680   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6681   SDValue OutOps[] = { OutLo, OutHi };
6682   return DAG.getMergeValues(OutOps, dl);
6683 }
6684
6685 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6686   SDLoc dl(Op);
6687   EVT VT = Op.getValueType();
6688   unsigned BitWidth = VT.getSizeInBits();
6689   assert(Op.getNumOperands() == 3 &&
6690          VT == Op.getOperand(1).getValueType() &&
6691          "Unexpected SRA!");
6692
6693   // Expand into a bunch of logical ops, followed by a select_cc.
6694   SDValue Lo = Op.getOperand(0);
6695   SDValue Hi = Op.getOperand(1);
6696   SDValue Amt = Op.getOperand(2);
6697   EVT AmtVT = Amt.getValueType();
6698
6699   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6700                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6701   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6702   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6703   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6704   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6705                              DAG.getConstant(-BitWidth, dl, AmtVT));
6706   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6707   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6708   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6709                                   Tmp4, Tmp6, ISD::SETLE);
6710   SDValue OutOps[] = { OutLo, OutHi };
6711   return DAG.getMergeValues(OutOps, dl);
6712 }
6713
6714 //===----------------------------------------------------------------------===//
6715 // Vector related lowering.
6716 //
6717
6718 /// BuildSplatI - Build a canonical splati of Val with an element size of
6719 /// SplatSize.  Cast the result to VT.
6720 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6721                              SelectionDAG &DAG, SDLoc dl) {
6722   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6723
6724   static const MVT VTys[] = { // canonical VT to use for each size.
6725     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6726   };
6727
6728   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6729
6730   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6731   if (Val == -1)
6732     SplatSize = 1;
6733
6734   EVT CanonicalVT = VTys[SplatSize-1];
6735
6736   // Build a canonical splat for this value.
6737   SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6738   SmallVector<SDValue, 8> Ops;
6739   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6740   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6741   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6742 }
6743
6744 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6745 /// specified intrinsic ID.
6746 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6747                                 SelectionDAG &DAG, SDLoc dl,
6748                                 EVT DestVT = MVT::Other) {
6749   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6750   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6751                      DAG.getConstant(IID, dl, MVT::i32), Op);
6752 }
6753
6754 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6755 /// specified intrinsic ID.
6756 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6757                                 SelectionDAG &DAG, SDLoc dl,
6758                                 EVT DestVT = MVT::Other) {
6759   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6760   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6761                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6762 }
6763
6764 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6765 /// specified intrinsic ID.
6766 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6767                                 SDValue Op2, SelectionDAG &DAG,
6768                                 SDLoc dl, EVT DestVT = MVT::Other) {
6769   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6770   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6771                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6772 }
6773
6774 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6775 /// amount.  The result has the specified value type.
6776 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6777                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6778   // Force LHS/RHS to be the right type.
6779   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6780   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6781
6782   int Ops[16];
6783   for (unsigned i = 0; i != 16; ++i)
6784     Ops[i] = i + Amt;
6785   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6786   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6787 }
6788
6789 // If this is a case we can't handle, return null and let the default
6790 // expansion code take care of it.  If we CAN select this case, and if it
6791 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6792 // this case more efficiently than a constant pool load, lower it to the
6793 // sequence of ops that should be used.
6794 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6795                                              SelectionDAG &DAG) const {
6796   SDLoc dl(Op);
6797   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6798   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6799
6800   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6801     // We first build an i32 vector, load it into a QPX register,
6802     // then convert it to a floating-point vector and compare it
6803     // to a zero vector to get the boolean result.
6804     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6805     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6806     MachinePointerInfo PtrInfo =
6807         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6808     EVT PtrVT = getPointerTy(DAG.getDataLayout());
6809     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6810
6811     assert(BVN->getNumOperands() == 4 &&
6812       "BUILD_VECTOR for v4i1 does not have 4 operands");
6813
6814     bool IsConst = true;
6815     for (unsigned i = 0; i < 4; ++i) {
6816       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6817       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6818         IsConst = false;
6819         break;
6820       }
6821     }
6822
6823     if (IsConst) {
6824       Constant *One =
6825         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6826       Constant *NegOne =
6827         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6828
6829       SmallVector<Constant*, 4> CV(4, NegOne);
6830       for (unsigned i = 0; i < 4; ++i) {
6831         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6832           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6833         else if (isNullConstant(BVN->getOperand(i)))
6834           continue;
6835         else
6836           CV[i] = One;
6837       }
6838
6839       Constant *CP = ConstantVector::get(CV);
6840       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
6841                                           16 /* alignment */);
6842
6843       SmallVector<SDValue, 2> Ops;
6844       Ops.push_back(DAG.getEntryNode());
6845       Ops.push_back(CPIdx);
6846
6847       SmallVector<EVT, 2> ValueVTs;
6848       ValueVTs.push_back(MVT::v4i1);
6849       ValueVTs.push_back(MVT::Other); // chain
6850       SDVTList VTs = DAG.getVTList(ValueVTs);
6851
6852       return DAG.getMemIntrinsicNode(
6853           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
6854           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
6855     }
6856
6857     SmallVector<SDValue, 4> Stores;
6858     for (unsigned i = 0; i < 4; ++i) {
6859       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6860
6861       unsigned Offset = 4*i;
6862       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6863       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6864
6865       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6866       if (StoreSize > 4) {
6867         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6868                                            BVN->getOperand(i), Idx,
6869                                            PtrInfo.getWithOffset(Offset),
6870                                            MVT::i32, false, false, 0));
6871       } else {
6872         SDValue StoreValue = BVN->getOperand(i);
6873         if (StoreSize < 4)
6874           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6875
6876         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6877                                       StoreValue, Idx,
6878                                       PtrInfo.getWithOffset(Offset),
6879                                       false, false, 0));
6880       }
6881     }
6882
6883     SDValue StoreChain;
6884     if (!Stores.empty())
6885       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6886     else
6887       StoreChain = DAG.getEntryNode();
6888
6889     // Now load from v4i32 into the QPX register; this will extend it to
6890     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6891     // is typed as v4f64 because the QPX register integer states are not
6892     // explicitly represented.
6893
6894     SmallVector<SDValue, 2> Ops;
6895     Ops.push_back(StoreChain);
6896     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6897     Ops.push_back(FIdx);
6898
6899     SmallVector<EVT, 2> ValueVTs;
6900     ValueVTs.push_back(MVT::v4f64);
6901     ValueVTs.push_back(MVT::Other); // chain
6902     SDVTList VTs = DAG.getVTList(ValueVTs);
6903
6904     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6905       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6906     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6907       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6908       LoadedVect);
6909
6910     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6911     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6912                           FPZeros, FPZeros, FPZeros, FPZeros);
6913
6914     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6915   }
6916
6917   // All other QPX vectors are handled by generic code.
6918   if (Subtarget.hasQPX())
6919     return SDValue();
6920
6921   // Check if this is a splat of a constant value.
6922   APInt APSplatBits, APSplatUndef;
6923   unsigned SplatBitSize;
6924   bool HasAnyUndefs;
6925   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6926                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6927       SplatBitSize > 32)
6928     return SDValue();
6929
6930   unsigned SplatBits = APSplatBits.getZExtValue();
6931   unsigned SplatUndef = APSplatUndef.getZExtValue();
6932   unsigned SplatSize = SplatBitSize / 8;
6933
6934   // First, handle single instruction cases.
6935
6936   // All zeros?
6937   if (SplatBits == 0) {
6938     // Canonicalize all zero vectors to be v4i32.
6939     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6940       SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6941       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6942       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6943     }
6944     return Op;
6945   }
6946
6947   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6948   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6949                     (32-SplatBitSize));
6950   if (SextVal >= -16 && SextVal <= 15)
6951     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6952
6953   // Two instruction sequences.
6954
6955   // If this value is in the range [-32,30] and is even, use:
6956   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6957   // If this value is in the range [17,31] and is odd, use:
6958   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6959   // If this value is in the range [-31,-17] and is odd, use:
6960   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6961   // Note the last two are three-instruction sequences.
6962   if (SextVal >= -32 && SextVal <= 31) {
6963     // To avoid having these optimizations undone by constant folding,
6964     // we convert to a pseudo that will be expanded later into one of
6965     // the above forms.
6966     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6967     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6968               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6969     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6970     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6971     if (VT == Op.getValueType())
6972       return RetVal;
6973     else
6974       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6975   }
6976
6977   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6978   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6979   // for fneg/fabs.
6980   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6981     // Make -1 and vspltisw -1:
6982     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6983
6984     // Make the VSLW intrinsic, computing 0x8000_0000.
6985     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6986                                    OnesV, DAG, dl);
6987
6988     // xor by OnesV to invert it.
6989     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6990     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6991   }
6992
6993   // Check to see if this is a wide variety of vsplti*, binop self cases.
6994   static const signed char SplatCsts[] = {
6995     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6996     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6997   };
6998
6999   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7000     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7001     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7002     int i = SplatCsts[idx];
7003
7004     // Figure out what shift amount will be used by altivec if shifted by i in
7005     // this splat size.
7006     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7007
7008     // vsplti + shl self.
7009     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7010       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7011       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7012         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7013         Intrinsic::ppc_altivec_vslw
7014       };
7015       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7016       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7017     }
7018
7019     // vsplti + srl self.
7020     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7021       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7022       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7023         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7024         Intrinsic::ppc_altivec_vsrw
7025       };
7026       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7027       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7028     }
7029
7030     // vsplti + sra self.
7031     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7032       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7033       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7034         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7035         Intrinsic::ppc_altivec_vsraw
7036       };
7037       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7038       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7039     }
7040
7041     // vsplti + rol self.
7042     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7043                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7044       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7045       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7046         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7047         Intrinsic::ppc_altivec_vrlw
7048       };
7049       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7050       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7051     }
7052
7053     // t = vsplti c, result = vsldoi t, t, 1
7054     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7055       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7056       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7057       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7058     }
7059     // t = vsplti c, result = vsldoi t, t, 2
7060     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7061       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7062       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7063       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7064     }
7065     // t = vsplti c, result = vsldoi t, t, 3
7066     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7067       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7068       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7069       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7070     }
7071   }
7072
7073   return SDValue();
7074 }
7075
7076 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7077 /// the specified operations to build the shuffle.
7078 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7079                                       SDValue RHS, SelectionDAG &DAG,
7080                                       SDLoc dl) {
7081   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7082   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7083   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7084
7085   enum {
7086     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7087     OP_VMRGHW,
7088     OP_VMRGLW,
7089     OP_VSPLTISW0,
7090     OP_VSPLTISW1,
7091     OP_VSPLTISW2,
7092     OP_VSPLTISW3,
7093     OP_VSLDOI4,
7094     OP_VSLDOI8,
7095     OP_VSLDOI12
7096   };
7097
7098   if (OpNum == OP_COPY) {
7099     if (LHSID == (1*9+2)*9+3) return LHS;
7100     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7101     return RHS;
7102   }
7103
7104   SDValue OpLHS, OpRHS;
7105   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7106   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7107
7108   int ShufIdxs[16];
7109   switch (OpNum) {
7110   default: llvm_unreachable("Unknown i32 permute!");
7111   case OP_VMRGHW:
7112     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7113     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7114     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7115     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7116     break;
7117   case OP_VMRGLW:
7118     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7119     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7120     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7121     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7122     break;
7123   case OP_VSPLTISW0:
7124     for (unsigned i = 0; i != 16; ++i)
7125       ShufIdxs[i] = (i&3)+0;
7126     break;
7127   case OP_VSPLTISW1:
7128     for (unsigned i = 0; i != 16; ++i)
7129       ShufIdxs[i] = (i&3)+4;
7130     break;
7131   case OP_VSPLTISW2:
7132     for (unsigned i = 0; i != 16; ++i)
7133       ShufIdxs[i] = (i&3)+8;
7134     break;
7135   case OP_VSPLTISW3:
7136     for (unsigned i = 0; i != 16; ++i)
7137       ShufIdxs[i] = (i&3)+12;
7138     break;
7139   case OP_VSLDOI4:
7140     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7141   case OP_VSLDOI8:
7142     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7143   case OP_VSLDOI12:
7144     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7145   }
7146   EVT VT = OpLHS.getValueType();
7147   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7148   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7149   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7150   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7151 }
7152
7153 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7154 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7155 /// return the code it can be lowered into.  Worst case, it can always be
7156 /// lowered into a vperm.
7157 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7158                                                SelectionDAG &DAG) const {
7159   SDLoc dl(Op);
7160   SDValue V1 = Op.getOperand(0);
7161   SDValue V2 = Op.getOperand(1);
7162   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7163   EVT VT = Op.getValueType();
7164   bool isLittleEndian = Subtarget.isLittleEndian();
7165
7166   if (Subtarget.hasQPX()) {
7167     if (VT.getVectorNumElements() != 4)
7168       return SDValue();
7169
7170     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7171
7172     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7173     if (AlignIdx != -1) {
7174       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7175                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7176     } else if (SVOp->isSplat()) {
7177       int SplatIdx = SVOp->getSplatIndex();
7178       if (SplatIdx >= 4) {
7179         std::swap(V1, V2);
7180         SplatIdx -= 4;
7181       }
7182
7183       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
7184       // nothing to do.
7185
7186       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7187                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7188     }
7189
7190     // Lower this into a qvgpci/qvfperm pair.
7191
7192     // Compute the qvgpci literal
7193     unsigned idx = 0;
7194     for (unsigned i = 0; i < 4; ++i) {
7195       int m = SVOp->getMaskElt(i);
7196       unsigned mm = m >= 0 ? (unsigned) m : i;
7197       idx |= mm << (3-i)*3;
7198     }
7199
7200     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7201                              DAG.getConstant(idx, dl, MVT::i32));
7202     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7203   }
7204
7205   // Cases that are handled by instructions that take permute immediates
7206   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7207   // selected by the instruction selector.
7208   if (V2.getOpcode() == ISD::UNDEF) {
7209     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7210         PPC::isSplatShuffleMask(SVOp, 2) ||
7211         PPC::isSplatShuffleMask(SVOp, 4) ||
7212         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7213         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7214         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7215         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7216         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7217         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7218         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7219         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7220         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7221         (Subtarget.hasP8Altivec() && (
7222          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7223          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7224          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7225       return Op;
7226     }
7227   }
7228
7229   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7230   // and produce a fixed permutation.  If any of these match, do not lower to
7231   // VPERM.
7232   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7233   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7234       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7235       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7236       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7237       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7238       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7239       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7240       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7241       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7242       (Subtarget.hasP8Altivec() && (
7243        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7244        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7245        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7246     return Op;
7247
7248   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7249   // perfect shuffle table to emit an optimal matching sequence.
7250   ArrayRef<int> PermMask = SVOp->getMask();
7251
7252   unsigned PFIndexes[4];
7253   bool isFourElementShuffle = true;
7254   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7255     unsigned EltNo = 8;   // Start out undef.
7256     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7257       if (PermMask[i*4+j] < 0)
7258         continue;   // Undef, ignore it.
7259
7260       unsigned ByteSource = PermMask[i*4+j];
7261       if ((ByteSource & 3) != j) {
7262         isFourElementShuffle = false;
7263         break;
7264       }
7265
7266       if (EltNo == 8) {
7267         EltNo = ByteSource/4;
7268       } else if (EltNo != ByteSource/4) {
7269         isFourElementShuffle = false;
7270         break;
7271       }
7272     }
7273     PFIndexes[i] = EltNo;
7274   }
7275
7276   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7277   // perfect shuffle vector to determine if it is cost effective to do this as
7278   // discrete instructions, or whether we should use a vperm.
7279   // For now, we skip this for little endian until such time as we have a
7280   // little-endian perfect shuffle table.
7281   if (isFourElementShuffle && !isLittleEndian) {
7282     // Compute the index in the perfect shuffle table.
7283     unsigned PFTableIndex =
7284       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7285
7286     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7287     unsigned Cost  = (PFEntry >> 30);
7288
7289     // Determining when to avoid vperm is tricky.  Many things affect the cost
7290     // of vperm, particularly how many times the perm mask needs to be computed.
7291     // For example, if the perm mask can be hoisted out of a loop or is already
7292     // used (perhaps because there are multiple permutes with the same shuffle
7293     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7294     // the loop requires an extra register.
7295     //
7296     // As a compromise, we only emit discrete instructions if the shuffle can be
7297     // generated in 3 or fewer operations.  When we have loop information
7298     // available, if this block is within a loop, we should avoid using vperm
7299     // for 3-operation perms and use a constant pool load instead.
7300     if (Cost < 3)
7301       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7302   }
7303
7304   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7305   // vector that will get spilled to the constant pool.
7306   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7307
7308   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7309   // that it is in input element units, not in bytes.  Convert now.
7310
7311   // For little endian, the order of the input vectors is reversed, and
7312   // the permutation mask is complemented with respect to 31.  This is
7313   // necessary to produce proper semantics with the big-endian-biased vperm
7314   // instruction.
7315   EVT EltVT = V1.getValueType().getVectorElementType();
7316   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7317
7318   SmallVector<SDValue, 16> ResultMask;
7319   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7320     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7321
7322     for (unsigned j = 0; j != BytesPerElement; ++j)
7323       if (isLittleEndian)
7324         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7325                                              dl, MVT::i32));
7326       else
7327         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7328                                              MVT::i32));
7329   }
7330
7331   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7332                                   ResultMask);
7333   if (isLittleEndian)
7334     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7335                        V2, V1, VPermMask);
7336   else
7337     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7338                        V1, V2, VPermMask);
7339 }
7340
7341 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7342 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7343 /// information about the intrinsic.
7344 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7345                                  bool &isDot, const PPCSubtarget &Subtarget) {
7346   unsigned IntrinsicID =
7347     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7348   CompareOpc = -1;
7349   isDot = false;
7350   switch (IntrinsicID) {
7351   default: return false;
7352     // Comparison predicates.
7353   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7354   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7355   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7356   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7357   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7358   case Intrinsic::ppc_altivec_vcmpequd_p:
7359     if (Subtarget.hasP8Altivec()) {
7360       CompareOpc = 199;
7361       isDot = 1;
7362     } else
7363       return false;
7364
7365     break;
7366   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7367   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7368   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7369   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7370   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7371   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7372     if (Subtarget.hasP8Altivec()) {
7373       CompareOpc = 967;
7374       isDot = 1;
7375     } else
7376       return false;
7377
7378     break;
7379   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7380   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7381   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7382   case Intrinsic::ppc_altivec_vcmpgtud_p:
7383     if (Subtarget.hasP8Altivec()) {
7384       CompareOpc = 711;
7385       isDot = 1;
7386     } else
7387       return false;
7388
7389     break;
7390     // VSX predicate comparisons use the same infrastructure
7391   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7392   case Intrinsic::ppc_vsx_xvcmpgedp_p:
7393   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7394   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7395   case Intrinsic::ppc_vsx_xvcmpgesp_p:
7396   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7397     if (Subtarget.hasVSX()) {
7398       switch (IntrinsicID) {
7399       case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break;
7400       case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break;
7401       case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break;
7402       case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break;
7403       case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break;
7404       case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break;
7405       }
7406       isDot = 1;
7407     }
7408     else
7409       return false;
7410
7411     break;
7412
7413     // Normal Comparisons.
7414   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7415   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7416   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7417   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7418   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7419   case Intrinsic::ppc_altivec_vcmpequd:
7420     if (Subtarget.hasP8Altivec()) {
7421       CompareOpc = 199;
7422       isDot = 0;
7423     } else
7424       return false;
7425
7426     break;
7427   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7428   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7429   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7430   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7431   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7432   case Intrinsic::ppc_altivec_vcmpgtsd:
7433     if (Subtarget.hasP8Altivec()) {
7434       CompareOpc = 967;
7435       isDot = 0;
7436     } else
7437       return false;
7438
7439     break;
7440   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7441   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7442   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7443   case Intrinsic::ppc_altivec_vcmpgtud:
7444     if (Subtarget.hasP8Altivec()) {
7445       CompareOpc = 711;
7446       isDot = 0;
7447     } else
7448       return false;
7449
7450     break;
7451   }
7452   return true;
7453 }
7454
7455 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7456 /// lower, do it, otherwise return null.
7457 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7458                                                    SelectionDAG &DAG) const {
7459   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7460   // opcode number of the comparison.
7461   SDLoc dl(Op);
7462   int CompareOpc;
7463   bool isDot;
7464   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
7465     return SDValue();    // Don't custom lower most intrinsics.
7466
7467   // If this is a non-dot comparison, make the VCMP node and we are done.
7468   if (!isDot) {
7469     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7470                               Op.getOperand(1), Op.getOperand(2),
7471                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7472     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7473   }
7474
7475   // Create the PPCISD altivec 'dot' comparison node.
7476   SDValue Ops[] = {
7477     Op.getOperand(2),  // LHS
7478     Op.getOperand(3),  // RHS
7479     DAG.getConstant(CompareOpc, dl, MVT::i32)
7480   };
7481   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7482   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7483
7484   // Now that we have the comparison, emit a copy from the CR to a GPR.
7485   // This is flagged to the above dot comparison.
7486   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7487                                 DAG.getRegister(PPC::CR6, MVT::i32),
7488                                 CompNode.getValue(1));
7489
7490   // Unpack the result based on how the target uses it.
7491   unsigned BitNo;   // Bit # of CR6.
7492   bool InvertBit;   // Invert result?
7493   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7494   default:  // Can't happen, don't crash on invalid number though.
7495   case 0:   // Return the value of the EQ bit of CR6.
7496     BitNo = 0; InvertBit = false;
7497     break;
7498   case 1:   // Return the inverted value of the EQ bit of CR6.
7499     BitNo = 0; InvertBit = true;
7500     break;
7501   case 2:   // Return the value of the LT bit of CR6.
7502     BitNo = 2; InvertBit = false;
7503     break;
7504   case 3:   // Return the inverted value of the LT bit of CR6.
7505     BitNo = 2; InvertBit = true;
7506     break;
7507   }
7508
7509   // Shift the bit into the low position.
7510   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7511                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7512   // Isolate the bit.
7513   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7514                       DAG.getConstant(1, dl, MVT::i32));
7515
7516   // If we are supposed to, toggle the bit.
7517   if (InvertBit)
7518     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7519                         DAG.getConstant(1, dl, MVT::i32));
7520   return Flags;
7521 }
7522
7523 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7524                                                   SelectionDAG &DAG) const {
7525   SDLoc dl(Op);
7526   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7527   // instructions), but for smaller types, we need to first extend up to v2i32
7528   // before doing going farther.
7529   if (Op.getValueType() == MVT::v2i64) {
7530     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7531     if (ExtVT != MVT::v2i32) {
7532       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7533       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7534                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7535                                         ExtVT.getVectorElementType(), 4)));
7536       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7537       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7538                        DAG.getValueType(MVT::v2i32));
7539     }
7540
7541     return Op;
7542   }
7543
7544   return SDValue();
7545 }
7546
7547 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7548                                                    SelectionDAG &DAG) const {
7549   SDLoc dl(Op);
7550   // Create a stack slot that is 16-byte aligned.
7551   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7552   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7553   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7554   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7555
7556   // Store the input value into Value#0 of the stack slot.
7557   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7558                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7559                                false, false, 0);
7560   // Load it out.
7561   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7562                      false, false, false, 0);
7563 }
7564
7565 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7566                                                    SelectionDAG &DAG) const {
7567   SDLoc dl(Op);
7568   SDNode *N = Op.getNode();
7569
7570   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7571          "Unknown extract_vector_elt type");
7572
7573   SDValue Value = N->getOperand(0);
7574
7575   // The first part of this is like the store lowering except that we don't
7576   // need to track the chain.
7577
7578   // The values are now known to be -1 (false) or 1 (true). To convert this
7579   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7580   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7581   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7582
7583   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7584   // understand how to form the extending load.
7585   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7586   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7587                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7588
7589   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7590
7591   // Now convert to an integer and store.
7592   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7593     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7594     Value);
7595
7596   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7597   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7598   MachinePointerInfo PtrInfo =
7599       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7600   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7601   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7602
7603   SDValue StoreChain = DAG.getEntryNode();
7604   SmallVector<SDValue, 2> Ops;
7605   Ops.push_back(StoreChain);
7606   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7607   Ops.push_back(Value);
7608   Ops.push_back(FIdx);
7609
7610   SmallVector<EVT, 2> ValueVTs;
7611   ValueVTs.push_back(MVT::Other); // chain
7612   SDVTList VTs = DAG.getVTList(ValueVTs);
7613
7614   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7615     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7616
7617   // Extract the value requested.
7618   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7619   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7620   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7621
7622   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7623                                PtrInfo.getWithOffset(Offset),
7624                                false, false, false, 0);
7625
7626   if (!Subtarget.useCRBits())
7627     return IntVal;
7628
7629   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7630 }
7631
7632 /// Lowering for QPX v4i1 loads
7633 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7634                                            SelectionDAG &DAG) const {
7635   SDLoc dl(Op);
7636   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7637   SDValue LoadChain = LN->getChain();
7638   SDValue BasePtr = LN->getBasePtr();
7639
7640   if (Op.getValueType() == MVT::v4f64 ||
7641       Op.getValueType() == MVT::v4f32) {
7642     EVT MemVT = LN->getMemoryVT();
7643     unsigned Alignment = LN->getAlignment();
7644
7645     // If this load is properly aligned, then it is legal.
7646     if (Alignment >= MemVT.getStoreSize())
7647       return Op;
7648
7649     EVT ScalarVT = Op.getValueType().getScalarType(),
7650         ScalarMemVT = MemVT.getScalarType();
7651     unsigned Stride = ScalarMemVT.getStoreSize();
7652
7653     SmallVector<SDValue, 8> Vals, LoadChains;
7654     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7655       SDValue Load;
7656       if (ScalarVT != ScalarMemVT)
7657         Load =
7658           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7659                          BasePtr,
7660                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7661                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7662                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7663                          LN->getAAInfo());
7664       else
7665         Load =
7666           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7667                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7668                        LN->isVolatile(), LN->isNonTemporal(),
7669                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7670                        LN->getAAInfo());
7671
7672       if (Idx == 0 && LN->isIndexed()) {
7673         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7674                "Unknown addressing mode on vector load");
7675         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7676                                   LN->getAddressingMode());
7677       }
7678
7679       Vals.push_back(Load);
7680       LoadChains.push_back(Load.getValue(1));
7681
7682       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7683                             DAG.getConstant(Stride, dl,
7684                                             BasePtr.getValueType()));
7685     }
7686
7687     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7688     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7689                                 Op.getValueType(), Vals);
7690
7691     if (LN->isIndexed()) {
7692       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7693       return DAG.getMergeValues(RetOps, dl);
7694     }
7695
7696     SDValue RetOps[] = { Value, TF };
7697     return DAG.getMergeValues(RetOps, dl);
7698   }
7699
7700   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7701   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7702
7703   // To lower v4i1 from a byte array, we load the byte elements of the
7704   // vector and then reuse the BUILD_VECTOR logic.
7705
7706   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7707   for (unsigned i = 0; i < 4; ++i) {
7708     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7709     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7710
7711     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7712                         dl, MVT::i32, LoadChain, Idx,
7713                         LN->getPointerInfo().getWithOffset(i),
7714                         MVT::i8 /* memory type */,
7715                         LN->isVolatile(), LN->isNonTemporal(),
7716                         LN->isInvariant(),
7717                         1 /* alignment */, LN->getAAInfo()));
7718     VectElmtChains.push_back(VectElmts[i].getValue(1));
7719   }
7720
7721   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7722   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7723
7724   SDValue RVals[] = { Value, LoadChain };
7725   return DAG.getMergeValues(RVals, dl);
7726 }
7727
7728 /// Lowering for QPX v4i1 stores
7729 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7730                                             SelectionDAG &DAG) const {
7731   SDLoc dl(Op);
7732   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7733   SDValue StoreChain = SN->getChain();
7734   SDValue BasePtr = SN->getBasePtr();
7735   SDValue Value = SN->getValue();
7736
7737   if (Value.getValueType() == MVT::v4f64 ||
7738       Value.getValueType() == MVT::v4f32) {
7739     EVT MemVT = SN->getMemoryVT();
7740     unsigned Alignment = SN->getAlignment();
7741
7742     // If this store is properly aligned, then it is legal.
7743     if (Alignment >= MemVT.getStoreSize())
7744       return Op;
7745
7746     EVT ScalarVT = Value.getValueType().getScalarType(),
7747         ScalarMemVT = MemVT.getScalarType();
7748     unsigned Stride = ScalarMemVT.getStoreSize();
7749
7750     SmallVector<SDValue, 8> Stores;
7751     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7752       SDValue Ex = DAG.getNode(
7753           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7754           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
7755       SDValue Store;
7756       if (ScalarVT != ScalarMemVT)
7757         Store =
7758           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7759                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7760                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7761                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7762       else
7763         Store =
7764           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7765                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7766                        SN->isVolatile(), SN->isNonTemporal(),
7767                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7768
7769       if (Idx == 0 && SN->isIndexed()) {
7770         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7771                "Unknown addressing mode on vector store");
7772         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7773                                     SN->getAddressingMode());
7774       }
7775
7776       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7777                             DAG.getConstant(Stride, dl,
7778                                             BasePtr.getValueType()));
7779       Stores.push_back(Store);
7780     }
7781
7782     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7783
7784     if (SN->isIndexed()) {
7785       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7786       return DAG.getMergeValues(RetOps, dl);
7787     }
7788
7789     return TF;
7790   }
7791
7792   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7793   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7794
7795   // The values are now known to be -1 (false) or 1 (true). To convert this
7796   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7797   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7798   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7799
7800   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7801   // understand how to form the extending load.
7802   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7803   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7804                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7805
7806   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7807
7808   // Now convert to an integer and store.
7809   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7810     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7811     Value);
7812
7813   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7814   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7815   MachinePointerInfo PtrInfo =
7816       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7817   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7818   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7819
7820   SmallVector<SDValue, 2> Ops;
7821   Ops.push_back(StoreChain);
7822   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7823   Ops.push_back(Value);
7824   Ops.push_back(FIdx);
7825
7826   SmallVector<EVT, 2> ValueVTs;
7827   ValueVTs.push_back(MVT::Other); // chain
7828   SDVTList VTs = DAG.getVTList(ValueVTs);
7829
7830   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7831     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7832
7833   // Move data into the byte array.
7834   SmallVector<SDValue, 4> Loads, LoadChains;
7835   for (unsigned i = 0; i < 4; ++i) {
7836     unsigned Offset = 4*i;
7837     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7838     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7839
7840     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7841                                    PtrInfo.getWithOffset(Offset),
7842                                    false, false, false, 0));
7843     LoadChains.push_back(Loads[i].getValue(1));
7844   }
7845
7846   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7847
7848   SmallVector<SDValue, 4> Stores;
7849   for (unsigned i = 0; i < 4; ++i) {
7850     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7851     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7852
7853     Stores.push_back(DAG.getTruncStore(
7854         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
7855         MVT::i8 /* memory type */, SN->isNonTemporal(), SN->isVolatile(),
7856         1 /* alignment */, SN->getAAInfo()));
7857   }
7858
7859   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7860
7861   return StoreChain;
7862 }
7863
7864 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7865   SDLoc dl(Op);
7866   if (Op.getValueType() == MVT::v4i32) {
7867     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7868
7869     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7870     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7871
7872     SDValue RHSSwap =   // = vrlw RHS, 16
7873       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7874
7875     // Shrinkify inputs to v8i16.
7876     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7877     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7878     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7879
7880     // Low parts multiplied together, generating 32-bit results (we ignore the
7881     // top parts).
7882     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7883                                         LHS, RHS, DAG, dl, MVT::v4i32);
7884
7885     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7886                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7887     // Shift the high parts up 16 bits.
7888     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7889                               Neg16, DAG, dl);
7890     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7891   } else if (Op.getValueType() == MVT::v8i16) {
7892     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7893
7894     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7895
7896     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7897                             LHS, RHS, Zero, DAG, dl);
7898   } else if (Op.getValueType() == MVT::v16i8) {
7899     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7900     bool isLittleEndian = Subtarget.isLittleEndian();
7901
7902     // Multiply the even 8-bit parts, producing 16-bit sums.
7903     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7904                                            LHS, RHS, DAG, dl, MVT::v8i16);
7905     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7906
7907     // Multiply the odd 8-bit parts, producing 16-bit sums.
7908     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7909                                           LHS, RHS, DAG, dl, MVT::v8i16);
7910     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7911
7912     // Merge the results together.  Because vmuleub and vmuloub are
7913     // instructions with a big-endian bias, we must reverse the
7914     // element numbering and reverse the meaning of "odd" and "even"
7915     // when generating little endian code.
7916     int Ops[16];
7917     for (unsigned i = 0; i != 8; ++i) {
7918       if (isLittleEndian) {
7919         Ops[i*2  ] = 2*i;
7920         Ops[i*2+1] = 2*i+16;
7921       } else {
7922         Ops[i*2  ] = 2*i+1;
7923         Ops[i*2+1] = 2*i+1+16;
7924       }
7925     }
7926     if (isLittleEndian)
7927       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7928     else
7929       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7930   } else {
7931     llvm_unreachable("Unknown mul to lower!");
7932   }
7933 }
7934
7935 /// LowerOperation - Provide custom lowering hooks for some operations.
7936 ///
7937 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7938   switch (Op.getOpcode()) {
7939   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7940   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7941   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7942   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7943   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7944   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7945   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7946   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7947   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7948   case ISD::VASTART:
7949     return LowerVASTART(Op, DAG, Subtarget);
7950
7951   case ISD::VAARG:
7952     return LowerVAARG(Op, DAG, Subtarget);
7953
7954   case ISD::VACOPY:
7955     return LowerVACOPY(Op, DAG, Subtarget);
7956
7957   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7958   case ISD::DYNAMIC_STACKALLOC:
7959     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7960   case ISD::GET_DYNAMIC_AREA_OFFSET: return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG, Subtarget);
7961
7962   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7963   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7964
7965   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7966   case ISD::STORE:              return LowerSTORE(Op, DAG);
7967   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7968   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7969   case ISD::FP_TO_UINT:
7970   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7971                                                       SDLoc(Op));
7972   case ISD::UINT_TO_FP:
7973   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7974   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7975
7976   // Lower 64-bit shifts.
7977   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7978   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7979   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7980
7981   // Vector-related lowering.
7982   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7983   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7984   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7985   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7986   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7987   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7988   case ISD::MUL:                return LowerMUL(Op, DAG);
7989
7990   // For counter-based loop handling.
7991   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7992
7993   // Frame & Return address.
7994   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7995   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7996   }
7997 }
7998
7999 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8000                                            SmallVectorImpl<SDValue>&Results,
8001                                            SelectionDAG &DAG) const {
8002   SDLoc dl(N);
8003   switch (N->getOpcode()) {
8004   default:
8005     llvm_unreachable("Do not know how to custom type legalize this operation!");
8006   case ISD::READCYCLECOUNTER: {
8007     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8008     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8009
8010     Results.push_back(RTB);
8011     Results.push_back(RTB.getValue(1));
8012     Results.push_back(RTB.getValue(2));
8013     break;
8014   }
8015   case ISD::INTRINSIC_W_CHAIN: {
8016     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8017         Intrinsic::ppc_is_decremented_ctr_nonzero)
8018       break;
8019
8020     assert(N->getValueType(0) == MVT::i1 &&
8021            "Unexpected result type for CTR decrement intrinsic");
8022     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8023                                  N->getValueType(0));
8024     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8025     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8026                                  N->getOperand(1));
8027
8028     Results.push_back(NewInt);
8029     Results.push_back(NewInt.getValue(1));
8030     break;
8031   }
8032   case ISD::VAARG: {
8033     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8034       return;
8035
8036     EVT VT = N->getValueType(0);
8037
8038     if (VT == MVT::i64) {
8039       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
8040
8041       Results.push_back(NewNode);
8042       Results.push_back(NewNode.getValue(1));
8043     }
8044     return;
8045   }
8046   case ISD::FP_ROUND_INREG: {
8047     assert(N->getValueType(0) == MVT::ppcf128);
8048     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8049     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8050                              MVT::f64, N->getOperand(0),
8051                              DAG.getIntPtrConstant(0, dl));
8052     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8053                              MVT::f64, N->getOperand(0),
8054                              DAG.getIntPtrConstant(1, dl));
8055
8056     // Add the two halves of the long double in round-to-zero mode.
8057     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8058
8059     // We know the low half is about to be thrown away, so just use something
8060     // convenient.
8061     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8062                                 FPreg, FPreg));
8063     return;
8064   }
8065   case ISD::FP_TO_SINT:
8066   case ISD::FP_TO_UINT:
8067     // LowerFP_TO_INT() can only handle f32 and f64.
8068     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8069       return;
8070     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8071     return;
8072   }
8073 }
8074
8075 //===----------------------------------------------------------------------===//
8076 //  Other Lowering Code
8077 //===----------------------------------------------------------------------===//
8078
8079 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8080   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8081   Function *Func = Intrinsic::getDeclaration(M, Id);
8082   return Builder.CreateCall(Func, {});
8083 }
8084
8085 // The mappings for emitLeading/TrailingFence is taken from
8086 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8087 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8088                                          AtomicOrdering Ord, bool IsStore,
8089                                          bool IsLoad) const {
8090   if (Ord == SequentiallyConsistent)
8091     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8092   if (isAtLeastRelease(Ord))
8093     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8094   return nullptr;
8095 }
8096
8097 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8098                                           AtomicOrdering Ord, bool IsStore,
8099                                           bool IsLoad) const {
8100   if (IsLoad && isAtLeastAcquire(Ord))
8101     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8102   // FIXME: this is too conservative, a dependent branch + isync is enough.
8103   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8104   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8105   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8106   return nullptr;
8107 }
8108
8109 MachineBasicBlock *
8110 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
8111                                     unsigned AtomicSize,
8112                                     unsigned BinOpcode) const {
8113   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8114   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8115
8116   auto LoadMnemonic = PPC::LDARX;
8117   auto StoreMnemonic = PPC::STDCX;
8118   switch (AtomicSize) {
8119   default:
8120     llvm_unreachable("Unexpected size of atomic entity");
8121   case 1:
8122     LoadMnemonic = PPC::LBARX;
8123     StoreMnemonic = PPC::STBCX;
8124     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8125     break;
8126   case 2:
8127     LoadMnemonic = PPC::LHARX;
8128     StoreMnemonic = PPC::STHCX;
8129     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8130     break;
8131   case 4:
8132     LoadMnemonic = PPC::LWARX;
8133     StoreMnemonic = PPC::STWCX;
8134     break;
8135   case 8:
8136     LoadMnemonic = PPC::LDARX;
8137     StoreMnemonic = PPC::STDCX;
8138     break;
8139   }
8140
8141   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8142   MachineFunction *F = BB->getParent();
8143   MachineFunction::iterator It = ++BB->getIterator();
8144
8145   unsigned dest = MI->getOperand(0).getReg();
8146   unsigned ptrA = MI->getOperand(1).getReg();
8147   unsigned ptrB = MI->getOperand(2).getReg();
8148   unsigned incr = MI->getOperand(3).getReg();
8149   DebugLoc dl = MI->getDebugLoc();
8150
8151   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8152   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8153   F->insert(It, loopMBB);
8154   F->insert(It, exitMBB);
8155   exitMBB->splice(exitMBB->begin(), BB,
8156                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8157   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8158
8159   MachineRegisterInfo &RegInfo = F->getRegInfo();
8160   unsigned TmpReg = (!BinOpcode) ? incr :
8161     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8162                                            : &PPC::GPRCRegClass);
8163
8164   //  thisMBB:
8165   //   ...
8166   //   fallthrough --> loopMBB
8167   BB->addSuccessor(loopMBB);
8168
8169   //  loopMBB:
8170   //   l[wd]arx dest, ptr
8171   //   add r0, dest, incr
8172   //   st[wd]cx. r0, ptr
8173   //   bne- loopMBB
8174   //   fallthrough --> exitMBB
8175   BB = loopMBB;
8176   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8177     .addReg(ptrA).addReg(ptrB);
8178   if (BinOpcode)
8179     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8180   BuildMI(BB, dl, TII->get(StoreMnemonic))
8181     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8182   BuildMI(BB, dl, TII->get(PPC::BCC))
8183     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8184   BB->addSuccessor(loopMBB);
8185   BB->addSuccessor(exitMBB);
8186
8187   //  exitMBB:
8188   //   ...
8189   BB = exitMBB;
8190   return BB;
8191 }
8192
8193 MachineBasicBlock *
8194 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8195                                             MachineBasicBlock *BB,
8196                                             bool is8bit,    // operation
8197                                             unsigned BinOpcode) const {
8198   // If we support part-word atomic mnemonics, just use them
8199   if (Subtarget.hasPartwordAtomics())
8200     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8201
8202   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8203   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8204   // In 64 bit mode we have to use 64 bits for addresses, even though the
8205   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8206   // registers without caring whether they're 32 or 64, but here we're
8207   // doing actual arithmetic on the addresses.
8208   bool is64bit = Subtarget.isPPC64();
8209   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8210
8211   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8212   MachineFunction *F = BB->getParent();
8213   MachineFunction::iterator It = ++BB->getIterator();
8214
8215   unsigned dest = MI->getOperand(0).getReg();
8216   unsigned ptrA = MI->getOperand(1).getReg();
8217   unsigned ptrB = MI->getOperand(2).getReg();
8218   unsigned incr = MI->getOperand(3).getReg();
8219   DebugLoc dl = MI->getDebugLoc();
8220
8221   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8222   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8223   F->insert(It, loopMBB);
8224   F->insert(It, exitMBB);
8225   exitMBB->splice(exitMBB->begin(), BB,
8226                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8227   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8228
8229   MachineRegisterInfo &RegInfo = F->getRegInfo();
8230   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8231                                           : &PPC::GPRCRegClass;
8232   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8233   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8234   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8235   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8236   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8237   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8238   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8239   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8240   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8241   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8242   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8243   unsigned Ptr1Reg;
8244   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8245
8246   //  thisMBB:
8247   //   ...
8248   //   fallthrough --> loopMBB
8249   BB->addSuccessor(loopMBB);
8250
8251   // The 4-byte load must be aligned, while a char or short may be
8252   // anywhere in the word.  Hence all this nasty bookkeeping code.
8253   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8254   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8255   //   xori shift, shift1, 24 [16]
8256   //   rlwinm ptr, ptr1, 0, 0, 29
8257   //   slw incr2, incr, shift
8258   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8259   //   slw mask, mask2, shift
8260   //  loopMBB:
8261   //   lwarx tmpDest, ptr
8262   //   add tmp, tmpDest, incr2
8263   //   andc tmp2, tmpDest, mask
8264   //   and tmp3, tmp, mask
8265   //   or tmp4, tmp3, tmp2
8266   //   stwcx. tmp4, ptr
8267   //   bne- loopMBB
8268   //   fallthrough --> exitMBB
8269   //   srw dest, tmpDest, shift
8270   if (ptrA != ZeroReg) {
8271     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8272     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8273       .addReg(ptrA).addReg(ptrB);
8274   } else {
8275     Ptr1Reg = ptrB;
8276   }
8277   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8278       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8279   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8280       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8281   if (is64bit)
8282     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8283       .addReg(Ptr1Reg).addImm(0).addImm(61);
8284   else
8285     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8286       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8287   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8288       .addReg(incr).addReg(ShiftReg);
8289   if (is8bit)
8290     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8291   else {
8292     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8293     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8294   }
8295   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8296       .addReg(Mask2Reg).addReg(ShiftReg);
8297
8298   BB = loopMBB;
8299   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8300     .addReg(ZeroReg).addReg(PtrReg);
8301   if (BinOpcode)
8302     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8303       .addReg(Incr2Reg).addReg(TmpDestReg);
8304   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8305     .addReg(TmpDestReg).addReg(MaskReg);
8306   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8307     .addReg(TmpReg).addReg(MaskReg);
8308   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8309     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8310   BuildMI(BB, dl, TII->get(PPC::STWCX))
8311     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8312   BuildMI(BB, dl, TII->get(PPC::BCC))
8313     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8314   BB->addSuccessor(loopMBB);
8315   BB->addSuccessor(exitMBB);
8316
8317   //  exitMBB:
8318   //   ...
8319   BB = exitMBB;
8320   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8321     .addReg(ShiftReg);
8322   return BB;
8323 }
8324
8325 llvm::MachineBasicBlock*
8326 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8327                                     MachineBasicBlock *MBB) const {
8328   DebugLoc DL = MI->getDebugLoc();
8329   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8330
8331   MachineFunction *MF = MBB->getParent();
8332   MachineRegisterInfo &MRI = MF->getRegInfo();
8333
8334   const BasicBlock *BB = MBB->getBasicBlock();
8335   MachineFunction::iterator I = ++MBB->getIterator();
8336
8337   // Memory Reference
8338   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8339   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8340
8341   unsigned DstReg = MI->getOperand(0).getReg();
8342   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8343   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8344   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8345   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8346
8347   MVT PVT = getPointerTy(MF->getDataLayout());
8348   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8349          "Invalid Pointer Size!");
8350   // For v = setjmp(buf), we generate
8351   //
8352   // thisMBB:
8353   //  SjLjSetup mainMBB
8354   //  bl mainMBB
8355   //  v_restore = 1
8356   //  b sinkMBB
8357   //
8358   // mainMBB:
8359   //  buf[LabelOffset] = LR
8360   //  v_main = 0
8361   //
8362   // sinkMBB:
8363   //  v = phi(main, restore)
8364   //
8365
8366   MachineBasicBlock *thisMBB = MBB;
8367   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8368   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8369   MF->insert(I, mainMBB);
8370   MF->insert(I, sinkMBB);
8371
8372   MachineInstrBuilder MIB;
8373
8374   // Transfer the remainder of BB and its successor edges to sinkMBB.
8375   sinkMBB->splice(sinkMBB->begin(), MBB,
8376                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8377   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8378
8379   // Note that the structure of the jmp_buf used here is not compatible
8380   // with that used by libc, and is not designed to be. Specifically, it
8381   // stores only those 'reserved' registers that LLVM does not otherwise
8382   // understand how to spill. Also, by convention, by the time this
8383   // intrinsic is called, Clang has already stored the frame address in the
8384   // first slot of the buffer and stack address in the third. Following the
8385   // X86 target code, we'll store the jump address in the second slot. We also
8386   // need to save the TOC pointer (R2) to handle jumps between shared
8387   // libraries, and that will be stored in the fourth slot. The thread
8388   // identifier (R13) is not affected.
8389
8390   // thisMBB:
8391   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8392   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8393   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8394
8395   // Prepare IP either in reg.
8396   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8397   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8398   unsigned BufReg = MI->getOperand(1).getReg();
8399
8400   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8401     setUsesTOCBasePtr(*MBB->getParent());
8402     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8403             .addReg(PPC::X2)
8404             .addImm(TOCOffset)
8405             .addReg(BufReg);
8406     MIB.setMemRefs(MMOBegin, MMOEnd);
8407   }
8408
8409   // Naked functions never have a base pointer, and so we use r1. For all
8410   // other functions, this decision must be delayed until during PEI.
8411   unsigned BaseReg;
8412   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8413     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8414   else
8415     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8416
8417   MIB = BuildMI(*thisMBB, MI, DL,
8418                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8419             .addReg(BaseReg)
8420             .addImm(BPOffset)
8421             .addReg(BufReg);
8422   MIB.setMemRefs(MMOBegin, MMOEnd);
8423
8424   // Setup
8425   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8426   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8427   MIB.addRegMask(TRI->getNoPreservedMask());
8428
8429   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8430
8431   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8432           .addMBB(mainMBB);
8433   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8434
8435   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
8436   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
8437
8438   // mainMBB:
8439   //  mainDstReg = 0
8440   MIB =
8441       BuildMI(mainMBB, DL,
8442               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8443
8444   // Store IP
8445   if (Subtarget.isPPC64()) {
8446     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8447             .addReg(LabelReg)
8448             .addImm(LabelOffset)
8449             .addReg(BufReg);
8450   } else {
8451     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8452             .addReg(LabelReg)
8453             .addImm(LabelOffset)
8454             .addReg(BufReg);
8455   }
8456
8457   MIB.setMemRefs(MMOBegin, MMOEnd);
8458
8459   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8460   mainMBB->addSuccessor(sinkMBB);
8461
8462   // sinkMBB:
8463   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8464           TII->get(PPC::PHI), DstReg)
8465     .addReg(mainDstReg).addMBB(mainMBB)
8466     .addReg(restoreDstReg).addMBB(thisMBB);
8467
8468   MI->eraseFromParent();
8469   return sinkMBB;
8470 }
8471
8472 MachineBasicBlock *
8473 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8474                                      MachineBasicBlock *MBB) const {
8475   DebugLoc DL = MI->getDebugLoc();
8476   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8477
8478   MachineFunction *MF = MBB->getParent();
8479   MachineRegisterInfo &MRI = MF->getRegInfo();
8480
8481   // Memory Reference
8482   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8483   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8484
8485   MVT PVT = getPointerTy(MF->getDataLayout());
8486   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8487          "Invalid Pointer Size!");
8488
8489   const TargetRegisterClass *RC =
8490     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8491   unsigned Tmp = MRI.createVirtualRegister(RC);
8492   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8493   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8494   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8495   unsigned BP =
8496       (PVT == MVT::i64)
8497           ? PPC::X30
8498           : (Subtarget.isSVR4ABI() &&
8499                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8500                  ? PPC::R29
8501                  : PPC::R30);
8502
8503   MachineInstrBuilder MIB;
8504
8505   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8506   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8507   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8508   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8509
8510   unsigned BufReg = MI->getOperand(0).getReg();
8511
8512   // Reload FP (the jumped-to function may not have had a
8513   // frame pointer, and if so, then its r31 will be restored
8514   // as necessary).
8515   if (PVT == MVT::i64) {
8516     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8517             .addImm(0)
8518             .addReg(BufReg);
8519   } else {
8520     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8521             .addImm(0)
8522             .addReg(BufReg);
8523   }
8524   MIB.setMemRefs(MMOBegin, MMOEnd);
8525
8526   // Reload IP
8527   if (PVT == MVT::i64) {
8528     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8529             .addImm(LabelOffset)
8530             .addReg(BufReg);
8531   } else {
8532     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8533             .addImm(LabelOffset)
8534             .addReg(BufReg);
8535   }
8536   MIB.setMemRefs(MMOBegin, MMOEnd);
8537
8538   // Reload SP
8539   if (PVT == MVT::i64) {
8540     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8541             .addImm(SPOffset)
8542             .addReg(BufReg);
8543   } else {
8544     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8545             .addImm(SPOffset)
8546             .addReg(BufReg);
8547   }
8548   MIB.setMemRefs(MMOBegin, MMOEnd);
8549
8550   // Reload BP
8551   if (PVT == MVT::i64) {
8552     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8553             .addImm(BPOffset)
8554             .addReg(BufReg);
8555   } else {
8556     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8557             .addImm(BPOffset)
8558             .addReg(BufReg);
8559   }
8560   MIB.setMemRefs(MMOBegin, MMOEnd);
8561
8562   // Reload TOC
8563   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8564     setUsesTOCBasePtr(*MBB->getParent());
8565     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8566             .addImm(TOCOffset)
8567             .addReg(BufReg);
8568
8569     MIB.setMemRefs(MMOBegin, MMOEnd);
8570   }
8571
8572   // Jump
8573   BuildMI(*MBB, MI, DL,
8574           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8575   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8576
8577   MI->eraseFromParent();
8578   return MBB;
8579 }
8580
8581 MachineBasicBlock *
8582 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8583                                                MachineBasicBlock *BB) const {
8584   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8585       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8586     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8587         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8588       // Call lowering should have added an r2 operand to indicate a dependence
8589       // on the TOC base pointer value. It can't however, because there is no
8590       // way to mark the dependence as implicit there, and so the stackmap code
8591       // will confuse it with a regular operand. Instead, add the dependence
8592       // here.
8593       setUsesTOCBasePtr(*BB->getParent());
8594       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8595     }
8596
8597     return emitPatchPoint(MI, BB);
8598   }
8599
8600   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8601       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8602     return emitEHSjLjSetJmp(MI, BB);
8603   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8604              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8605     return emitEHSjLjLongJmp(MI, BB);
8606   }
8607
8608   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8609
8610   // To "insert" these instructions we actually have to insert their
8611   // control-flow patterns.
8612   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8613   MachineFunction::iterator It = ++BB->getIterator();
8614
8615   MachineFunction *F = BB->getParent();
8616
8617   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8618                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8619                               MI->getOpcode() == PPC::SELECT_I4 ||
8620                               MI->getOpcode() == PPC::SELECT_I8)) {
8621     SmallVector<MachineOperand, 2> Cond;
8622     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8623         MI->getOpcode() == PPC::SELECT_CC_I8)
8624       Cond.push_back(MI->getOperand(4));
8625     else
8626       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8627     Cond.push_back(MI->getOperand(1));
8628
8629     DebugLoc dl = MI->getDebugLoc();
8630     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8631                       Cond, MI->getOperand(2).getReg(),
8632                       MI->getOperand(3).getReg());
8633   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8634              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8635              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8636              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8637              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8638              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8639              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8640              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8641              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8642              MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8643              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8644              MI->getOpcode() == PPC::SELECT_I4 ||
8645              MI->getOpcode() == PPC::SELECT_I8 ||
8646              MI->getOpcode() == PPC::SELECT_F4 ||
8647              MI->getOpcode() == PPC::SELECT_F8 ||
8648              MI->getOpcode() == PPC::SELECT_QFRC ||
8649              MI->getOpcode() == PPC::SELECT_QSRC ||
8650              MI->getOpcode() == PPC::SELECT_QBRC ||
8651              MI->getOpcode() == PPC::SELECT_VRRC ||
8652              MI->getOpcode() == PPC::SELECT_VSFRC ||
8653              MI->getOpcode() == PPC::SELECT_VSSRC ||
8654              MI->getOpcode() == PPC::SELECT_VSRC) {
8655     // The incoming instruction knows the destination vreg to set, the
8656     // condition code register to branch on, the true/false values to
8657     // select between, and a branch opcode to use.
8658
8659     //  thisMBB:
8660     //  ...
8661     //   TrueVal = ...
8662     //   cmpTY ccX, r1, r2
8663     //   bCC copy1MBB
8664     //   fallthrough --> copy0MBB
8665     MachineBasicBlock *thisMBB = BB;
8666     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8667     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8668     DebugLoc dl = MI->getDebugLoc();
8669     F->insert(It, copy0MBB);
8670     F->insert(It, sinkMBB);
8671
8672     // Transfer the remainder of BB and its successor edges to sinkMBB.
8673     sinkMBB->splice(sinkMBB->begin(), BB,
8674                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8675     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8676
8677     // Next, add the true and fallthrough blocks as its successors.
8678     BB->addSuccessor(copy0MBB);
8679     BB->addSuccessor(sinkMBB);
8680
8681     if (MI->getOpcode() == PPC::SELECT_I4 ||
8682         MI->getOpcode() == PPC::SELECT_I8 ||
8683         MI->getOpcode() == PPC::SELECT_F4 ||
8684         MI->getOpcode() == PPC::SELECT_F8 ||
8685         MI->getOpcode() == PPC::SELECT_QFRC ||
8686         MI->getOpcode() == PPC::SELECT_QSRC ||
8687         MI->getOpcode() == PPC::SELECT_QBRC ||
8688         MI->getOpcode() == PPC::SELECT_VRRC ||
8689         MI->getOpcode() == PPC::SELECT_VSFRC ||
8690         MI->getOpcode() == PPC::SELECT_VSSRC ||
8691         MI->getOpcode() == PPC::SELECT_VSRC) {
8692       BuildMI(BB, dl, TII->get(PPC::BC))
8693         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8694     } else {
8695       unsigned SelectPred = MI->getOperand(4).getImm();
8696       BuildMI(BB, dl, TII->get(PPC::BCC))
8697         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8698     }
8699
8700     //  copy0MBB:
8701     //   %FalseValue = ...
8702     //   # fallthrough to sinkMBB
8703     BB = copy0MBB;
8704
8705     // Update machine-CFG edges
8706     BB->addSuccessor(sinkMBB);
8707
8708     //  sinkMBB:
8709     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8710     //  ...
8711     BB = sinkMBB;
8712     BuildMI(*BB, BB->begin(), dl,
8713             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8714       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8715       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8716   } else if (MI->getOpcode() == PPC::ReadTB) {
8717     // To read the 64-bit time-base register on a 32-bit target, we read the
8718     // two halves. Should the counter have wrapped while it was being read, we
8719     // need to try again.
8720     // ...
8721     // readLoop:
8722     // mfspr Rx,TBU # load from TBU
8723     // mfspr Ry,TB  # load from TB
8724     // mfspr Rz,TBU # load from TBU
8725     // cmpw crX,Rx,Rz # check if 'old'='new'
8726     // bne readLoop   # branch if they're not equal
8727     // ...
8728
8729     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8730     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8731     DebugLoc dl = MI->getDebugLoc();
8732     F->insert(It, readMBB);
8733     F->insert(It, sinkMBB);
8734
8735     // Transfer the remainder of BB and its successor edges to sinkMBB.
8736     sinkMBB->splice(sinkMBB->begin(), BB,
8737                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8738     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8739
8740     BB->addSuccessor(readMBB);
8741     BB = readMBB;
8742
8743     MachineRegisterInfo &RegInfo = F->getRegInfo();
8744     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8745     unsigned LoReg = MI->getOperand(0).getReg();
8746     unsigned HiReg = MI->getOperand(1).getReg();
8747
8748     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8749     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8750     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8751
8752     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8753
8754     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8755       .addReg(HiReg).addReg(ReadAgainReg);
8756     BuildMI(BB, dl, TII->get(PPC::BCC))
8757       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8758
8759     BB->addSuccessor(readMBB);
8760     BB->addSuccessor(sinkMBB);
8761   }
8762   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8763     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8764   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8765     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8766   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8767     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8768   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8769     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8770
8771   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8772     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8773   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8774     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8775   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8776     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8777   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8778     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8779
8780   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8781     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8782   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8783     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8784   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8785     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8786   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8787     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8788
8789   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8790     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8791   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8792     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8793   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8794     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8795   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8796     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8797
8798   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8799     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8800   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8801     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8802   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8803     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8804   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8805     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8806
8807   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8808     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8809   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8810     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8811   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8812     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8813   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8814     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8815
8816   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8817     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8818   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8819     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8820   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8821     BB = EmitAtomicBinary(MI, BB, 4, 0);
8822   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8823     BB = EmitAtomicBinary(MI, BB, 8, 0);
8824
8825   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8826            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8827            (Subtarget.hasPartwordAtomics() &&
8828             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8829            (Subtarget.hasPartwordAtomics() &&
8830             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8831     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8832
8833     auto LoadMnemonic = PPC::LDARX;
8834     auto StoreMnemonic = PPC::STDCX;
8835     switch(MI->getOpcode()) {
8836     default:
8837       llvm_unreachable("Compare and swap of unknown size");
8838     case PPC::ATOMIC_CMP_SWAP_I8:
8839       LoadMnemonic = PPC::LBARX;
8840       StoreMnemonic = PPC::STBCX;
8841       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8842       break;
8843     case PPC::ATOMIC_CMP_SWAP_I16:
8844       LoadMnemonic = PPC::LHARX;
8845       StoreMnemonic = PPC::STHCX;
8846       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8847       break;
8848     case PPC::ATOMIC_CMP_SWAP_I32:
8849       LoadMnemonic = PPC::LWARX;
8850       StoreMnemonic = PPC::STWCX;
8851       break;
8852     case PPC::ATOMIC_CMP_SWAP_I64:
8853       LoadMnemonic = PPC::LDARX;
8854       StoreMnemonic = PPC::STDCX;
8855       break;
8856     }
8857     unsigned dest   = MI->getOperand(0).getReg();
8858     unsigned ptrA   = MI->getOperand(1).getReg();
8859     unsigned ptrB   = MI->getOperand(2).getReg();
8860     unsigned oldval = MI->getOperand(3).getReg();
8861     unsigned newval = MI->getOperand(4).getReg();
8862     DebugLoc dl     = MI->getDebugLoc();
8863
8864     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8865     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8866     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8867     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8868     F->insert(It, loop1MBB);
8869     F->insert(It, loop2MBB);
8870     F->insert(It, midMBB);
8871     F->insert(It, exitMBB);
8872     exitMBB->splice(exitMBB->begin(), BB,
8873                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8874     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8875
8876     //  thisMBB:
8877     //   ...
8878     //   fallthrough --> loopMBB
8879     BB->addSuccessor(loop1MBB);
8880
8881     // loop1MBB:
8882     //   l[bhwd]arx dest, ptr
8883     //   cmp[wd] dest, oldval
8884     //   bne- midMBB
8885     // loop2MBB:
8886     //   st[bhwd]cx. newval, ptr
8887     //   bne- loopMBB
8888     //   b exitBB
8889     // midMBB:
8890     //   st[bhwd]cx. dest, ptr
8891     // exitBB:
8892     BB = loop1MBB;
8893     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8894       .addReg(ptrA).addReg(ptrB);
8895     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8896       .addReg(oldval).addReg(dest);
8897     BuildMI(BB, dl, TII->get(PPC::BCC))
8898       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8899     BB->addSuccessor(loop2MBB);
8900     BB->addSuccessor(midMBB);
8901
8902     BB = loop2MBB;
8903     BuildMI(BB, dl, TII->get(StoreMnemonic))
8904       .addReg(newval).addReg(ptrA).addReg(ptrB);
8905     BuildMI(BB, dl, TII->get(PPC::BCC))
8906       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8907     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8908     BB->addSuccessor(loop1MBB);
8909     BB->addSuccessor(exitMBB);
8910
8911     BB = midMBB;
8912     BuildMI(BB, dl, TII->get(StoreMnemonic))
8913       .addReg(dest).addReg(ptrA).addReg(ptrB);
8914     BB->addSuccessor(exitMBB);
8915
8916     //  exitMBB:
8917     //   ...
8918     BB = exitMBB;
8919   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8920              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8921     // We must use 64-bit registers for addresses when targeting 64-bit,
8922     // since we're actually doing arithmetic on them.  Other registers
8923     // can be 32-bit.
8924     bool is64bit = Subtarget.isPPC64();
8925     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8926
8927     unsigned dest   = MI->getOperand(0).getReg();
8928     unsigned ptrA   = MI->getOperand(1).getReg();
8929     unsigned ptrB   = MI->getOperand(2).getReg();
8930     unsigned oldval = MI->getOperand(3).getReg();
8931     unsigned newval = MI->getOperand(4).getReg();
8932     DebugLoc dl     = MI->getDebugLoc();
8933
8934     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8935     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8936     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8937     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8938     F->insert(It, loop1MBB);
8939     F->insert(It, loop2MBB);
8940     F->insert(It, midMBB);
8941     F->insert(It, exitMBB);
8942     exitMBB->splice(exitMBB->begin(), BB,
8943                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8944     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8945
8946     MachineRegisterInfo &RegInfo = F->getRegInfo();
8947     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8948                                             : &PPC::GPRCRegClass;
8949     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8950     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8951     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8952     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8953     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8954     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8955     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8956     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8957     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8958     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8959     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8960     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8961     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8962     unsigned Ptr1Reg;
8963     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8964     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8965     //  thisMBB:
8966     //   ...
8967     //   fallthrough --> loopMBB
8968     BB->addSuccessor(loop1MBB);
8969
8970     // The 4-byte load must be aligned, while a char or short may be
8971     // anywhere in the word.  Hence all this nasty bookkeeping code.
8972     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8973     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8974     //   xori shift, shift1, 24 [16]
8975     //   rlwinm ptr, ptr1, 0, 0, 29
8976     //   slw newval2, newval, shift
8977     //   slw oldval2, oldval,shift
8978     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8979     //   slw mask, mask2, shift
8980     //   and newval3, newval2, mask
8981     //   and oldval3, oldval2, mask
8982     // loop1MBB:
8983     //   lwarx tmpDest, ptr
8984     //   and tmp, tmpDest, mask
8985     //   cmpw tmp, oldval3
8986     //   bne- midMBB
8987     // loop2MBB:
8988     //   andc tmp2, tmpDest, mask
8989     //   or tmp4, tmp2, newval3
8990     //   stwcx. tmp4, ptr
8991     //   bne- loop1MBB
8992     //   b exitBB
8993     // midMBB:
8994     //   stwcx. tmpDest, ptr
8995     // exitBB:
8996     //   srw dest, tmpDest, shift
8997     if (ptrA != ZeroReg) {
8998       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8999       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9000         .addReg(ptrA).addReg(ptrB);
9001     } else {
9002       Ptr1Reg = ptrB;
9003     }
9004     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9005         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9006     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9007         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9008     if (is64bit)
9009       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9010         .addReg(Ptr1Reg).addImm(0).addImm(61);
9011     else
9012       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9013         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9014     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9015         .addReg(newval).addReg(ShiftReg);
9016     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9017         .addReg(oldval).addReg(ShiftReg);
9018     if (is8bit)
9019       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9020     else {
9021       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9022       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9023         .addReg(Mask3Reg).addImm(65535);
9024     }
9025     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9026         .addReg(Mask2Reg).addReg(ShiftReg);
9027     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9028         .addReg(NewVal2Reg).addReg(MaskReg);
9029     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9030         .addReg(OldVal2Reg).addReg(MaskReg);
9031
9032     BB = loop1MBB;
9033     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9034         .addReg(ZeroReg).addReg(PtrReg);
9035     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9036         .addReg(TmpDestReg).addReg(MaskReg);
9037     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9038         .addReg(TmpReg).addReg(OldVal3Reg);
9039     BuildMI(BB, dl, TII->get(PPC::BCC))
9040         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9041     BB->addSuccessor(loop2MBB);
9042     BB->addSuccessor(midMBB);
9043
9044     BB = loop2MBB;
9045     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9046         .addReg(TmpDestReg).addReg(MaskReg);
9047     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9048         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9049     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9050         .addReg(ZeroReg).addReg(PtrReg);
9051     BuildMI(BB, dl, TII->get(PPC::BCC))
9052       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9053     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9054     BB->addSuccessor(loop1MBB);
9055     BB->addSuccessor(exitMBB);
9056
9057     BB = midMBB;
9058     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9059       .addReg(ZeroReg).addReg(PtrReg);
9060     BB->addSuccessor(exitMBB);
9061
9062     //  exitMBB:
9063     //   ...
9064     BB = exitMBB;
9065     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9066       .addReg(ShiftReg);
9067   } else if (MI->getOpcode() == PPC::FADDrtz) {
9068     // This pseudo performs an FADD with rounding mode temporarily forced
9069     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9070     // is not modeled at the SelectionDAG level.
9071     unsigned Dest = MI->getOperand(0).getReg();
9072     unsigned Src1 = MI->getOperand(1).getReg();
9073     unsigned Src2 = MI->getOperand(2).getReg();
9074     DebugLoc dl   = MI->getDebugLoc();
9075
9076     MachineRegisterInfo &RegInfo = F->getRegInfo();
9077     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9078
9079     // Save FPSCR value.
9080     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9081
9082     // Set rounding mode to round-to-zero.
9083     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9084     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9085
9086     // Perform addition.
9087     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9088
9089     // Restore FPSCR value.
9090     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9091   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9092              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
9093              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9094              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9095     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9096                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
9097                       PPC::ANDIo8 : PPC::ANDIo;
9098     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9099                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9100
9101     MachineRegisterInfo &RegInfo = F->getRegInfo();
9102     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9103                                                   &PPC::GPRCRegClass :
9104                                                   &PPC::G8RCRegClass);
9105
9106     DebugLoc dl   = MI->getDebugLoc();
9107     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9108       .addReg(MI->getOperand(1).getReg()).addImm(1);
9109     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9110             MI->getOperand(0).getReg())
9111       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9112   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
9113     DebugLoc Dl = MI->getDebugLoc();
9114     MachineRegisterInfo &RegInfo = F->getRegInfo();
9115     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9116     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9117     return BB;
9118   } else {
9119     llvm_unreachable("Unexpected instr type to insert");
9120   }
9121
9122   MI->eraseFromParent();   // The pseudo instruction is gone now.
9123   return BB;
9124 }
9125
9126 //===----------------------------------------------------------------------===//
9127 // Target Optimization Hooks
9128 //===----------------------------------------------------------------------===//
9129
9130 static std::string getRecipOp(const char *Base, EVT VT) {
9131   std::string RecipOp(Base);
9132   if (VT.getScalarType() == MVT::f64)
9133     RecipOp += "d";
9134   else
9135     RecipOp += "f";
9136
9137   if (VT.isVector())
9138     RecipOp = "vec-" + RecipOp;
9139
9140   return RecipOp;
9141 }
9142
9143 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
9144                                             DAGCombinerInfo &DCI,
9145                                             unsigned &RefinementSteps,
9146                                             bool &UseOneConstNR) const {
9147   EVT VT = Operand.getValueType();
9148   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9149       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9150       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9151       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9152       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9153       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9154     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9155     std::string RecipOp = getRecipOp("sqrt", VT);
9156     if (!Recips.isEnabled(RecipOp))
9157       return SDValue();
9158
9159     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9160     UseOneConstNR = true;
9161     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9162   }
9163   return SDValue();
9164 }
9165
9166 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
9167                                             DAGCombinerInfo &DCI,
9168                                             unsigned &RefinementSteps) const {
9169   EVT VT = Operand.getValueType();
9170   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9171       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9172       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9173       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9174       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9175       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9176     TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
9177     std::string RecipOp = getRecipOp("div", VT);
9178     if (!Recips.isEnabled(RecipOp))
9179       return SDValue();
9180
9181     RefinementSteps = Recips.getRefinementSteps(RecipOp);
9182     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9183   }
9184   return SDValue();
9185 }
9186
9187 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9188   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9189   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9190   // enabled for division), this functionality is redundant with the default
9191   // combiner logic (once the division -> reciprocal/multiply transformation
9192   // has taken place). As a result, this matters more for older cores than for
9193   // newer ones.
9194
9195   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9196   // reciprocal if there are two or more FDIVs (for embedded cores with only
9197   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9198   switch (Subtarget.getDarwinDirective()) {
9199   default:
9200     return 3;
9201   case PPC::DIR_440:
9202   case PPC::DIR_A2:
9203   case PPC::DIR_E500mc:
9204   case PPC::DIR_E5500:
9205     return 2;
9206   }
9207 }
9208
9209 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9210 // collapsed, and so we need to look through chains of them.
9211 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9212                                      int64_t& Offset, SelectionDAG &DAG) {
9213   if (DAG.isBaseWithConstantOffset(Loc)) {
9214     Base = Loc.getOperand(0);
9215     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9216
9217     // The base might itself be a base plus an offset, and if so, accumulate
9218     // that as well.
9219     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9220   }
9221 }
9222
9223 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9224                             unsigned Bytes, int Dist,
9225                             SelectionDAG &DAG) {
9226   if (VT.getSizeInBits() / 8 != Bytes)
9227     return false;
9228
9229   SDValue BaseLoc = Base->getBasePtr();
9230   if (Loc.getOpcode() == ISD::FrameIndex) {
9231     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9232       return false;
9233     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9234     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9235     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9236     int FS  = MFI->getObjectSize(FI);
9237     int BFS = MFI->getObjectSize(BFI);
9238     if (FS != BFS || FS != (int)Bytes) return false;
9239     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9240   }
9241
9242   SDValue Base1 = Loc, Base2 = BaseLoc;
9243   int64_t Offset1 = 0, Offset2 = 0;
9244   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
9245   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
9246   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
9247     return true;
9248
9249   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9250   const GlobalValue *GV1 = nullptr;
9251   const GlobalValue *GV2 = nullptr;
9252   Offset1 = 0;
9253   Offset2 = 0;
9254   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9255   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9256   if (isGA1 && isGA2 && GV1 == GV2)
9257     return Offset1 == (Offset2 + Dist*Bytes);
9258   return false;
9259 }
9260
9261 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9262 // not enforce equality of the chain operands.
9263 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9264                             unsigned Bytes, int Dist,
9265                             SelectionDAG &DAG) {
9266   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9267     EVT VT = LS->getMemoryVT();
9268     SDValue Loc = LS->getBasePtr();
9269     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9270   }
9271
9272   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9273     EVT VT;
9274     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9275     default: return false;
9276     case Intrinsic::ppc_qpx_qvlfd:
9277     case Intrinsic::ppc_qpx_qvlfda:
9278       VT = MVT::v4f64;
9279       break;
9280     case Intrinsic::ppc_qpx_qvlfs:
9281     case Intrinsic::ppc_qpx_qvlfsa:
9282       VT = MVT::v4f32;
9283       break;
9284     case Intrinsic::ppc_qpx_qvlfcd:
9285     case Intrinsic::ppc_qpx_qvlfcda:
9286       VT = MVT::v2f64;
9287       break;
9288     case Intrinsic::ppc_qpx_qvlfcs:
9289     case Intrinsic::ppc_qpx_qvlfcsa:
9290       VT = MVT::v2f32;
9291       break;
9292     case Intrinsic::ppc_qpx_qvlfiwa:
9293     case Intrinsic::ppc_qpx_qvlfiwz:
9294     case Intrinsic::ppc_altivec_lvx:
9295     case Intrinsic::ppc_altivec_lvxl:
9296     case Intrinsic::ppc_vsx_lxvw4x:
9297       VT = MVT::v4i32;
9298       break;
9299     case Intrinsic::ppc_vsx_lxvd2x:
9300       VT = MVT::v2f64;
9301       break;
9302     case Intrinsic::ppc_altivec_lvebx:
9303       VT = MVT::i8;
9304       break;
9305     case Intrinsic::ppc_altivec_lvehx:
9306       VT = MVT::i16;
9307       break;
9308     case Intrinsic::ppc_altivec_lvewx:
9309       VT = MVT::i32;
9310       break;
9311     }
9312
9313     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9314   }
9315
9316   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9317     EVT VT;
9318     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9319     default: return false;
9320     case Intrinsic::ppc_qpx_qvstfd:
9321     case Intrinsic::ppc_qpx_qvstfda:
9322       VT = MVT::v4f64;
9323       break;
9324     case Intrinsic::ppc_qpx_qvstfs:
9325     case Intrinsic::ppc_qpx_qvstfsa:
9326       VT = MVT::v4f32;
9327       break;
9328     case Intrinsic::ppc_qpx_qvstfcd:
9329     case Intrinsic::ppc_qpx_qvstfcda:
9330       VT = MVT::v2f64;
9331       break;
9332     case Intrinsic::ppc_qpx_qvstfcs:
9333     case Intrinsic::ppc_qpx_qvstfcsa:
9334       VT = MVT::v2f32;
9335       break;
9336     case Intrinsic::ppc_qpx_qvstfiw:
9337     case Intrinsic::ppc_qpx_qvstfiwa:
9338     case Intrinsic::ppc_altivec_stvx:
9339     case Intrinsic::ppc_altivec_stvxl:
9340     case Intrinsic::ppc_vsx_stxvw4x:
9341       VT = MVT::v4i32;
9342       break;
9343     case Intrinsic::ppc_vsx_stxvd2x:
9344       VT = MVT::v2f64;
9345       break;
9346     case Intrinsic::ppc_altivec_stvebx:
9347       VT = MVT::i8;
9348       break;
9349     case Intrinsic::ppc_altivec_stvehx:
9350       VT = MVT::i16;
9351       break;
9352     case Intrinsic::ppc_altivec_stvewx:
9353       VT = MVT::i32;
9354       break;
9355     }
9356
9357     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9358   }
9359
9360   return false;
9361 }
9362
9363 // Return true is there is a nearyby consecutive load to the one provided
9364 // (regardless of alignment). We search up and down the chain, looking though
9365 // token factors and other loads (but nothing else). As a result, a true result
9366 // indicates that it is safe to create a new consecutive load adjacent to the
9367 // load provided.
9368 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9369   SDValue Chain = LD->getChain();
9370   EVT VT = LD->getMemoryVT();
9371
9372   SmallSet<SDNode *, 16> LoadRoots;
9373   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9374   SmallSet<SDNode *, 16> Visited;
9375
9376   // First, search up the chain, branching to follow all token-factor operands.
9377   // If we find a consecutive load, then we're done, otherwise, record all
9378   // nodes just above the top-level loads and token factors.
9379   while (!Queue.empty()) {
9380     SDNode *ChainNext = Queue.pop_back_val();
9381     if (!Visited.insert(ChainNext).second)
9382       continue;
9383
9384     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9385       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9386         return true;
9387
9388       if (!Visited.count(ChainLD->getChain().getNode()))
9389         Queue.push_back(ChainLD->getChain().getNode());
9390     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9391       for (const SDUse &O : ChainNext->ops())
9392         if (!Visited.count(O.getNode()))
9393           Queue.push_back(O.getNode());
9394     } else
9395       LoadRoots.insert(ChainNext);
9396   }
9397
9398   // Second, search down the chain, starting from the top-level nodes recorded
9399   // in the first phase. These top-level nodes are the nodes just above all
9400   // loads and token factors. Starting with their uses, recursively look though
9401   // all loads (just the chain uses) and token factors to find a consecutive
9402   // load.
9403   Visited.clear();
9404   Queue.clear();
9405
9406   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9407        IE = LoadRoots.end(); I != IE; ++I) {
9408     Queue.push_back(*I);
9409
9410     while (!Queue.empty()) {
9411       SDNode *LoadRoot = Queue.pop_back_val();
9412       if (!Visited.insert(LoadRoot).second)
9413         continue;
9414
9415       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9416         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9417           return true;
9418
9419       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9420            UE = LoadRoot->use_end(); UI != UE; ++UI)
9421         if (((isa<MemSDNode>(*UI) &&
9422             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9423             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9424           Queue.push_back(*UI);
9425     }
9426   }
9427
9428   return false;
9429 }
9430
9431 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9432                                                   DAGCombinerInfo &DCI) const {
9433   SelectionDAG &DAG = DCI.DAG;
9434   SDLoc dl(N);
9435
9436   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9437   // If we're tracking CR bits, we need to be careful that we don't have:
9438   //   trunc(binary-ops(zext(x), zext(y)))
9439   // or
9440   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9441   // such that we're unnecessarily moving things into GPRs when it would be
9442   // better to keep them in CR bits.
9443
9444   // Note that trunc here can be an actual i1 trunc, or can be the effective
9445   // truncation that comes from a setcc or select_cc.
9446   if (N->getOpcode() == ISD::TRUNCATE &&
9447       N->getValueType(0) != MVT::i1)
9448     return SDValue();
9449
9450   if (N->getOperand(0).getValueType() != MVT::i32 &&
9451       N->getOperand(0).getValueType() != MVT::i64)
9452     return SDValue();
9453
9454   if (N->getOpcode() == ISD::SETCC ||
9455       N->getOpcode() == ISD::SELECT_CC) {
9456     // If we're looking at a comparison, then we need to make sure that the
9457     // high bits (all except for the first) don't matter the result.
9458     ISD::CondCode CC =
9459       cast<CondCodeSDNode>(N->getOperand(
9460         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9461     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9462
9463     if (ISD::isSignedIntSetCC(CC)) {
9464       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9465           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9466         return SDValue();
9467     } else if (ISD::isUnsignedIntSetCC(CC)) {
9468       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9469                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9470           !DAG.MaskedValueIsZero(N->getOperand(1),
9471                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9472         return SDValue();
9473     } else {
9474       // This is neither a signed nor an unsigned comparison, just make sure
9475       // that the high bits are equal.
9476       APInt Op1Zero, Op1One;
9477       APInt Op2Zero, Op2One;
9478       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9479       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9480
9481       // We don't really care about what is known about the first bit (if
9482       // anything), so clear it in all masks prior to comparing them.
9483       Op1Zero.clearBit(0); Op1One.clearBit(0);
9484       Op2Zero.clearBit(0); Op2One.clearBit(0);
9485
9486       if (Op1Zero != Op2Zero || Op1One != Op2One)
9487         return SDValue();
9488     }
9489   }
9490
9491   // We now know that the higher-order bits are irrelevant, we just need to
9492   // make sure that all of the intermediate operations are bit operations, and
9493   // all inputs are extensions.
9494   if (N->getOperand(0).getOpcode() != ISD::AND &&
9495       N->getOperand(0).getOpcode() != ISD::OR  &&
9496       N->getOperand(0).getOpcode() != ISD::XOR &&
9497       N->getOperand(0).getOpcode() != ISD::SELECT &&
9498       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9499       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9500       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9501       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9502       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9503     return SDValue();
9504
9505   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9506       N->getOperand(1).getOpcode() != ISD::AND &&
9507       N->getOperand(1).getOpcode() != ISD::OR  &&
9508       N->getOperand(1).getOpcode() != ISD::XOR &&
9509       N->getOperand(1).getOpcode() != ISD::SELECT &&
9510       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9511       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9512       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9513       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9514       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9515     return SDValue();
9516
9517   SmallVector<SDValue, 4> Inputs;
9518   SmallVector<SDValue, 8> BinOps, PromOps;
9519   SmallPtrSet<SDNode *, 16> Visited;
9520
9521   for (unsigned i = 0; i < 2; ++i) {
9522     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9523           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9524           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9525           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9526         isa<ConstantSDNode>(N->getOperand(i)))
9527       Inputs.push_back(N->getOperand(i));
9528     else
9529       BinOps.push_back(N->getOperand(i));
9530
9531     if (N->getOpcode() == ISD::TRUNCATE)
9532       break;
9533   }
9534
9535   // Visit all inputs, collect all binary operations (and, or, xor and
9536   // select) that are all fed by extensions.
9537   while (!BinOps.empty()) {
9538     SDValue BinOp = BinOps.back();
9539     BinOps.pop_back();
9540
9541     if (!Visited.insert(BinOp.getNode()).second)
9542       continue;
9543
9544     PromOps.push_back(BinOp);
9545
9546     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9547       // The condition of the select is not promoted.
9548       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9549         continue;
9550       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9551         continue;
9552
9553       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9554             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9555             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9556            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9557           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9558         Inputs.push_back(BinOp.getOperand(i));
9559       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9560                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9561                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9562                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9563                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9564                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9565                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9566                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9567                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9568         BinOps.push_back(BinOp.getOperand(i));
9569       } else {
9570         // We have an input that is not an extension or another binary
9571         // operation; we'll abort this transformation.
9572         return SDValue();
9573       }
9574     }
9575   }
9576
9577   // Make sure that this is a self-contained cluster of operations (which
9578   // is not quite the same thing as saying that everything has only one
9579   // use).
9580   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9581     if (isa<ConstantSDNode>(Inputs[i]))
9582       continue;
9583
9584     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9585                               UE = Inputs[i].getNode()->use_end();
9586          UI != UE; ++UI) {
9587       SDNode *User = *UI;
9588       if (User != N && !Visited.count(User))
9589         return SDValue();
9590
9591       // Make sure that we're not going to promote the non-output-value
9592       // operand(s) or SELECT or SELECT_CC.
9593       // FIXME: Although we could sometimes handle this, and it does occur in
9594       // practice that one of the condition inputs to the select is also one of
9595       // the outputs, we currently can't deal with this.
9596       if (User->getOpcode() == ISD::SELECT) {
9597         if (User->getOperand(0) == Inputs[i])
9598           return SDValue();
9599       } else if (User->getOpcode() == ISD::SELECT_CC) {
9600         if (User->getOperand(0) == Inputs[i] ||
9601             User->getOperand(1) == Inputs[i])
9602           return SDValue();
9603       }
9604     }
9605   }
9606
9607   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9608     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9609                               UE = PromOps[i].getNode()->use_end();
9610          UI != UE; ++UI) {
9611       SDNode *User = *UI;
9612       if (User != N && !Visited.count(User))
9613         return SDValue();
9614
9615       // Make sure that we're not going to promote the non-output-value
9616       // operand(s) or SELECT or SELECT_CC.
9617       // FIXME: Although we could sometimes handle this, and it does occur in
9618       // practice that one of the condition inputs to the select is also one of
9619       // the outputs, we currently can't deal with this.
9620       if (User->getOpcode() == ISD::SELECT) {
9621         if (User->getOperand(0) == PromOps[i])
9622           return SDValue();
9623       } else if (User->getOpcode() == ISD::SELECT_CC) {
9624         if (User->getOperand(0) == PromOps[i] ||
9625             User->getOperand(1) == PromOps[i])
9626           return SDValue();
9627       }
9628     }
9629   }
9630
9631   // Replace all inputs with the extension operand.
9632   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9633     // Constants may have users outside the cluster of to-be-promoted nodes,
9634     // and so we need to replace those as we do the promotions.
9635     if (isa<ConstantSDNode>(Inputs[i]))
9636       continue;
9637     else
9638       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
9639   }
9640
9641   // Replace all operations (these are all the same, but have a different
9642   // (i1) return type). DAG.getNode will validate that the types of
9643   // a binary operator match, so go through the list in reverse so that
9644   // we've likely promoted both operands first. Any intermediate truncations or
9645   // extensions disappear.
9646   while (!PromOps.empty()) {
9647     SDValue PromOp = PromOps.back();
9648     PromOps.pop_back();
9649
9650     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9651         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9652         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9653         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9654       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9655           PromOp.getOperand(0).getValueType() != MVT::i1) {
9656         // The operand is not yet ready (see comment below).
9657         PromOps.insert(PromOps.begin(), PromOp);
9658         continue;
9659       }
9660
9661       SDValue RepValue = PromOp.getOperand(0);
9662       if (isa<ConstantSDNode>(RepValue))
9663         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9664
9665       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9666       continue;
9667     }
9668
9669     unsigned C;
9670     switch (PromOp.getOpcode()) {
9671     default:             C = 0; break;
9672     case ISD::SELECT:    C = 1; break;
9673     case ISD::SELECT_CC: C = 2; break;
9674     }
9675
9676     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9677          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9678         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9679          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9680       // The to-be-promoted operands of this node have not yet been
9681       // promoted (this should be rare because we're going through the
9682       // list backward, but if one of the operands has several users in
9683       // this cluster of to-be-promoted nodes, it is possible).
9684       PromOps.insert(PromOps.begin(), PromOp);
9685       continue;
9686     }
9687
9688     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9689                                 PromOp.getNode()->op_end());
9690
9691     // If there are any constant inputs, make sure they're replaced now.
9692     for (unsigned i = 0; i < 2; ++i)
9693       if (isa<ConstantSDNode>(Ops[C+i]))
9694         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9695
9696     DAG.ReplaceAllUsesOfValueWith(PromOp,
9697       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9698   }
9699
9700   // Now we're left with the initial truncation itself.
9701   if (N->getOpcode() == ISD::TRUNCATE)
9702     return N->getOperand(0);
9703
9704   // Otherwise, this is a comparison. The operands to be compared have just
9705   // changed type (to i1), but everything else is the same.
9706   return SDValue(N, 0);
9707 }
9708
9709 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9710                                                   DAGCombinerInfo &DCI) const {
9711   SelectionDAG &DAG = DCI.DAG;
9712   SDLoc dl(N);
9713
9714   // If we're tracking CR bits, we need to be careful that we don't have:
9715   //   zext(binary-ops(trunc(x), trunc(y)))
9716   // or
9717   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9718   // such that we're unnecessarily moving things into CR bits that can more
9719   // efficiently stay in GPRs. Note that if we're not certain that the high
9720   // bits are set as required by the final extension, we still may need to do
9721   // some masking to get the proper behavior.
9722
9723   // This same functionality is important on PPC64 when dealing with
9724   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9725   // the return values of functions. Because it is so similar, it is handled
9726   // here as well.
9727
9728   if (N->getValueType(0) != MVT::i32 &&
9729       N->getValueType(0) != MVT::i64)
9730     return SDValue();
9731
9732   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9733         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9734     return SDValue();
9735
9736   if (N->getOperand(0).getOpcode() != ISD::AND &&
9737       N->getOperand(0).getOpcode() != ISD::OR  &&
9738       N->getOperand(0).getOpcode() != ISD::XOR &&
9739       N->getOperand(0).getOpcode() != ISD::SELECT &&
9740       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9741     return SDValue();
9742
9743   SmallVector<SDValue, 4> Inputs;
9744   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9745   SmallPtrSet<SDNode *, 16> Visited;
9746
9747   // Visit all inputs, collect all binary operations (and, or, xor and
9748   // select) that are all fed by truncations.
9749   while (!BinOps.empty()) {
9750     SDValue BinOp = BinOps.back();
9751     BinOps.pop_back();
9752
9753     if (!Visited.insert(BinOp.getNode()).second)
9754       continue;
9755
9756     PromOps.push_back(BinOp);
9757
9758     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9759       // The condition of the select is not promoted.
9760       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9761         continue;
9762       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9763         continue;
9764
9765       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9766           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9767         Inputs.push_back(BinOp.getOperand(i));
9768       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9769                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9770                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9771                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9772                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9773         BinOps.push_back(BinOp.getOperand(i));
9774       } else {
9775         // We have an input that is not a truncation or another binary
9776         // operation; we'll abort this transformation.
9777         return SDValue();
9778       }
9779     }
9780   }
9781
9782   // The operands of a select that must be truncated when the select is
9783   // promoted because the operand is actually part of the to-be-promoted set.
9784   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9785
9786   // Make sure that this is a self-contained cluster of operations (which
9787   // is not quite the same thing as saying that everything has only one
9788   // use).
9789   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9790     if (isa<ConstantSDNode>(Inputs[i]))
9791       continue;
9792
9793     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9794                               UE = Inputs[i].getNode()->use_end();
9795          UI != UE; ++UI) {
9796       SDNode *User = *UI;
9797       if (User != N && !Visited.count(User))
9798         return SDValue();
9799
9800       // If we're going to promote the non-output-value operand(s) or SELECT or
9801       // SELECT_CC, record them for truncation.
9802       if (User->getOpcode() == ISD::SELECT) {
9803         if (User->getOperand(0) == Inputs[i])
9804           SelectTruncOp[0].insert(std::make_pair(User,
9805                                     User->getOperand(0).getValueType()));
9806       } else if (User->getOpcode() == ISD::SELECT_CC) {
9807         if (User->getOperand(0) == Inputs[i])
9808           SelectTruncOp[0].insert(std::make_pair(User,
9809                                     User->getOperand(0).getValueType()));
9810         if (User->getOperand(1) == Inputs[i])
9811           SelectTruncOp[1].insert(std::make_pair(User,
9812                                     User->getOperand(1).getValueType()));
9813       }
9814     }
9815   }
9816
9817   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9818     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9819                               UE = PromOps[i].getNode()->use_end();
9820          UI != UE; ++UI) {
9821       SDNode *User = *UI;
9822       if (User != N && !Visited.count(User))
9823         return SDValue();
9824
9825       // If we're going to promote the non-output-value operand(s) or SELECT or
9826       // SELECT_CC, record them for truncation.
9827       if (User->getOpcode() == ISD::SELECT) {
9828         if (User->getOperand(0) == PromOps[i])
9829           SelectTruncOp[0].insert(std::make_pair(User,
9830                                     User->getOperand(0).getValueType()));
9831       } else if (User->getOpcode() == ISD::SELECT_CC) {
9832         if (User->getOperand(0) == PromOps[i])
9833           SelectTruncOp[0].insert(std::make_pair(User,
9834                                     User->getOperand(0).getValueType()));
9835         if (User->getOperand(1) == PromOps[i])
9836           SelectTruncOp[1].insert(std::make_pair(User,
9837                                     User->getOperand(1).getValueType()));
9838       }
9839     }
9840   }
9841
9842   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9843   bool ReallyNeedsExt = false;
9844   if (N->getOpcode() != ISD::ANY_EXTEND) {
9845     // If all of the inputs are not already sign/zero extended, then
9846     // we'll still need to do that at the end.
9847     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9848       if (isa<ConstantSDNode>(Inputs[i]))
9849         continue;
9850
9851       unsigned OpBits =
9852         Inputs[i].getOperand(0).getValueSizeInBits();
9853       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9854
9855       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9856            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9857                                   APInt::getHighBitsSet(OpBits,
9858                                                         OpBits-PromBits))) ||
9859           (N->getOpcode() == ISD::SIGN_EXTEND &&
9860            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9861              (OpBits-(PromBits-1)))) {
9862         ReallyNeedsExt = true;
9863         break;
9864       }
9865     }
9866   }
9867
9868   // Replace all inputs, either with the truncation operand, or a
9869   // truncation or extension to the final output type.
9870   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9871     // Constant inputs need to be replaced with the to-be-promoted nodes that
9872     // use them because they might have users outside of the cluster of
9873     // promoted nodes.
9874     if (isa<ConstantSDNode>(Inputs[i]))
9875       continue;
9876
9877     SDValue InSrc = Inputs[i].getOperand(0);
9878     if (Inputs[i].getValueType() == N->getValueType(0))
9879       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9880     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9881       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9882         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9883     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9884       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9885         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9886     else
9887       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9888         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9889   }
9890
9891   // Replace all operations (these are all the same, but have a different
9892   // (promoted) return type). DAG.getNode will validate that the types of
9893   // a binary operator match, so go through the list in reverse so that
9894   // we've likely promoted both operands first.
9895   while (!PromOps.empty()) {
9896     SDValue PromOp = PromOps.back();
9897     PromOps.pop_back();
9898
9899     unsigned C;
9900     switch (PromOp.getOpcode()) {
9901     default:             C = 0; break;
9902     case ISD::SELECT:    C = 1; break;
9903     case ISD::SELECT_CC: C = 2; break;
9904     }
9905
9906     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9907          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9908         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9909          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9910       // The to-be-promoted operands of this node have not yet been
9911       // promoted (this should be rare because we're going through the
9912       // list backward, but if one of the operands has several users in
9913       // this cluster of to-be-promoted nodes, it is possible).
9914       PromOps.insert(PromOps.begin(), PromOp);
9915       continue;
9916     }
9917
9918     // For SELECT and SELECT_CC nodes, we do a similar check for any
9919     // to-be-promoted comparison inputs.
9920     if (PromOp.getOpcode() == ISD::SELECT ||
9921         PromOp.getOpcode() == ISD::SELECT_CC) {
9922       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9923            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9924           (SelectTruncOp[1].count(PromOp.getNode()) &&
9925            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9926         PromOps.insert(PromOps.begin(), PromOp);
9927         continue;
9928       }
9929     }
9930
9931     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9932                                 PromOp.getNode()->op_end());
9933
9934     // If this node has constant inputs, then they'll need to be promoted here.
9935     for (unsigned i = 0; i < 2; ++i) {
9936       if (!isa<ConstantSDNode>(Ops[C+i]))
9937         continue;
9938       if (Ops[C+i].getValueType() == N->getValueType(0))
9939         continue;
9940
9941       if (N->getOpcode() == ISD::SIGN_EXTEND)
9942         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9943       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9944         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9945       else
9946         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9947     }
9948
9949     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9950     // truncate them again to the original value type.
9951     if (PromOp.getOpcode() == ISD::SELECT ||
9952         PromOp.getOpcode() == ISD::SELECT_CC) {
9953       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9954       if (SI0 != SelectTruncOp[0].end())
9955         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9956       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9957       if (SI1 != SelectTruncOp[1].end())
9958         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9959     }
9960
9961     DAG.ReplaceAllUsesOfValueWith(PromOp,
9962       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9963   }
9964
9965   // Now we're left with the initial extension itself.
9966   if (!ReallyNeedsExt)
9967     return N->getOperand(0);
9968
9969   // To zero extend, just mask off everything except for the first bit (in the
9970   // i1 case).
9971   if (N->getOpcode() == ISD::ZERO_EXTEND)
9972     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9973                        DAG.getConstant(APInt::getLowBitsSet(
9974                                          N->getValueSizeInBits(0), PromBits),
9975                                        dl, N->getValueType(0)));
9976
9977   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9978          "Invalid extension type");
9979   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
9980   SDValue ShiftCst =
9981       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9982   return DAG.getNode(
9983       ISD::SRA, dl, N->getValueType(0),
9984       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
9985       ShiftCst);
9986 }
9987
9988 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9989                                               DAGCombinerInfo &DCI) const {
9990   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9991           N->getOpcode() == ISD::UINT_TO_FP) &&
9992          "Need an int -> FP conversion node here");
9993
9994   if (!Subtarget.has64BitSupport())
9995     return SDValue();
9996
9997   SelectionDAG &DAG = DCI.DAG;
9998   SDLoc dl(N);
9999   SDValue Op(N, 0);
10000
10001   // Don't handle ppc_fp128 here or i1 conversions.
10002   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
10003     return SDValue();
10004   if (Op.getOperand(0).getValueType() == MVT::i1)
10005     return SDValue();
10006
10007   // For i32 intermediate values, unfortunately, the conversion functions
10008   // leave the upper 32 bits of the value are undefined. Within the set of
10009   // scalar instructions, we have no method for zero- or sign-extending the
10010   // value. Thus, we cannot handle i32 intermediate values here.
10011   if (Op.getOperand(0).getValueType() == MVT::i32)
10012     return SDValue();
10013
10014   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
10015          "UINT_TO_FP is supported only with FPCVT");
10016
10017   // If we have FCFIDS, then use it when converting to single-precision.
10018   // Otherwise, convert to double-precision and then round.
10019   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10020                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
10021                                                             : PPCISD::FCFIDS)
10022                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
10023                                                             : PPCISD::FCFID);
10024   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
10025                   ? MVT::f32
10026                   : MVT::f64;
10027
10028   // If we're converting from a float, to an int, and back to a float again,
10029   // then we don't need the store/load pair at all.
10030   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
10031        Subtarget.hasFPCVT()) ||
10032       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
10033     SDValue Src = Op.getOperand(0).getOperand(0);
10034     if (Src.getValueType() == MVT::f32) {
10035       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
10036       DCI.AddToWorklist(Src.getNode());
10037     } else if (Src.getValueType() != MVT::f64) {
10038       // Make sure that we don't pick up a ppc_fp128 source value.
10039       return SDValue();
10040     }
10041
10042     unsigned FCTOp =
10043       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
10044                                                         PPCISD::FCTIDUZ;
10045
10046     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
10047     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
10048
10049     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
10050       FP = DAG.getNode(ISD::FP_ROUND, dl,
10051                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
10052       DCI.AddToWorklist(FP.getNode());
10053     }
10054
10055     return FP;
10056   }
10057
10058   return SDValue();
10059 }
10060
10061 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
10062 // builtins) into loads with swaps.
10063 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
10064                                               DAGCombinerInfo &DCI) const {
10065   SelectionDAG &DAG = DCI.DAG;
10066   SDLoc dl(N);
10067   SDValue Chain;
10068   SDValue Base;
10069   MachineMemOperand *MMO;
10070
10071   switch (N->getOpcode()) {
10072   default:
10073     llvm_unreachable("Unexpected opcode for little endian VSX load");
10074   case ISD::LOAD: {
10075     LoadSDNode *LD = cast<LoadSDNode>(N);
10076     Chain = LD->getChain();
10077     Base = LD->getBasePtr();
10078     MMO = LD->getMemOperand();
10079     // If the MMO suggests this isn't a load of a full vector, leave
10080     // things alone.  For a built-in, we have to make the change for
10081     // correctness, so if there is a size problem that will be a bug.
10082     if (MMO->getSize() < 16)
10083       return SDValue();
10084     break;
10085   }
10086   case ISD::INTRINSIC_W_CHAIN: {
10087     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10088     Chain = Intrin->getChain();
10089     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
10090     // us what we want. Get operand 2 instead.
10091     Base = Intrin->getOperand(2);
10092     MMO = Intrin->getMemOperand();
10093     break;
10094   }
10095   }
10096
10097   MVT VecTy = N->getValueType(0).getSimpleVT();
10098   SDValue LoadOps[] = { Chain, Base };
10099   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
10100                                          DAG.getVTList(VecTy, MVT::Other),
10101                                          LoadOps, VecTy, MMO);
10102   DCI.AddToWorklist(Load.getNode());
10103   Chain = Load.getValue(1);
10104   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10105                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
10106   DCI.AddToWorklist(Swap.getNode());
10107   return Swap;
10108 }
10109
10110 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
10111 // builtins) into stores with swaps.
10112 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
10113                                                DAGCombinerInfo &DCI) const {
10114   SelectionDAG &DAG = DCI.DAG;
10115   SDLoc dl(N);
10116   SDValue Chain;
10117   SDValue Base;
10118   unsigned SrcOpnd;
10119   MachineMemOperand *MMO;
10120
10121   switch (N->getOpcode()) {
10122   default:
10123     llvm_unreachable("Unexpected opcode for little endian VSX store");
10124   case ISD::STORE: {
10125     StoreSDNode *ST = cast<StoreSDNode>(N);
10126     Chain = ST->getChain();
10127     Base = ST->getBasePtr();
10128     MMO = ST->getMemOperand();
10129     SrcOpnd = 1;
10130     // If the MMO suggests this isn't a store of a full vector, leave
10131     // things alone.  For a built-in, we have to make the change for
10132     // correctness, so if there is a size problem that will be a bug.
10133     if (MMO->getSize() < 16)
10134       return SDValue();
10135     break;
10136   }
10137   case ISD::INTRINSIC_VOID: {
10138     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
10139     Chain = Intrin->getChain();
10140     // Intrin->getBasePtr() oddly does not get what we want.
10141     Base = Intrin->getOperand(3);
10142     MMO = Intrin->getMemOperand();
10143     SrcOpnd = 2;
10144     break;
10145   }
10146   }
10147
10148   SDValue Src = N->getOperand(SrcOpnd);
10149   MVT VecTy = Src.getValueType().getSimpleVT();
10150   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
10151                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
10152   DCI.AddToWorklist(Swap.getNode());
10153   Chain = Swap.getValue(1);
10154   SDValue StoreOps[] = { Chain, Swap, Base };
10155   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
10156                                           DAG.getVTList(MVT::Other),
10157                                           StoreOps, VecTy, MMO);
10158   DCI.AddToWorklist(Store.getNode());
10159   return Store;
10160 }
10161
10162 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
10163                                              DAGCombinerInfo &DCI) const {
10164   SelectionDAG &DAG = DCI.DAG;
10165   SDLoc dl(N);
10166   switch (N->getOpcode()) {
10167   default: break;
10168   case PPCISD::SHL:
10169     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
10170         return N->getOperand(0);
10171     break;
10172   case PPCISD::SRL:
10173     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
10174         return N->getOperand(0);
10175     break;
10176   case PPCISD::SRA:
10177     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10178       if (C->isNullValue() ||   //  0 >>s V -> 0.
10179           C->isAllOnesValue())    // -1 >>s V -> -1.
10180         return N->getOperand(0);
10181     }
10182     break;
10183   case ISD::SIGN_EXTEND:
10184   case ISD::ZERO_EXTEND:
10185   case ISD::ANY_EXTEND:
10186     return DAGCombineExtBoolTrunc(N, DCI);
10187   case ISD::TRUNCATE:
10188   case ISD::SETCC:
10189   case ISD::SELECT_CC:
10190     return DAGCombineTruncBoolExt(N, DCI);
10191   case ISD::SINT_TO_FP:
10192   case ISD::UINT_TO_FP:
10193     return combineFPToIntToFP(N, DCI);
10194   case ISD::STORE: {
10195     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
10196     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
10197         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
10198         N->getOperand(1).getValueType() == MVT::i32 &&
10199         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
10200       SDValue Val = N->getOperand(1).getOperand(0);
10201       if (Val.getValueType() == MVT::f32) {
10202         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
10203         DCI.AddToWorklist(Val.getNode());
10204       }
10205       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
10206       DCI.AddToWorklist(Val.getNode());
10207
10208       SDValue Ops[] = {
10209         N->getOperand(0), Val, N->getOperand(2),
10210         DAG.getValueType(N->getOperand(1).getValueType())
10211       };
10212
10213       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
10214               DAG.getVTList(MVT::Other), Ops,
10215               cast<StoreSDNode>(N)->getMemoryVT(),
10216               cast<StoreSDNode>(N)->getMemOperand());
10217       DCI.AddToWorklist(Val.getNode());
10218       return Val;
10219     }
10220
10221     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10222     if (cast<StoreSDNode>(N)->isUnindexed() &&
10223         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10224         N->getOperand(1).getNode()->hasOneUse() &&
10225         (N->getOperand(1).getValueType() == MVT::i32 ||
10226          N->getOperand(1).getValueType() == MVT::i16 ||
10227          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10228           N->getOperand(1).getValueType() == MVT::i64))) {
10229       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10230       // Do an any-extend to 32-bits if this is a half-word input.
10231       if (BSwapOp.getValueType() == MVT::i16)
10232         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10233
10234       SDValue Ops[] = {
10235         N->getOperand(0), BSwapOp, N->getOperand(2),
10236         DAG.getValueType(N->getOperand(1).getValueType())
10237       };
10238       return
10239         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10240                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10241                                 cast<StoreSDNode>(N)->getMemOperand());
10242     }
10243
10244     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10245     EVT VT = N->getOperand(1).getValueType();
10246     if (VT.isSimple()) {
10247       MVT StoreVT = VT.getSimpleVT();
10248       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10249           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10250            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10251         return expandVSXStoreForLE(N, DCI);
10252     }
10253     break;
10254   }
10255   case ISD::LOAD: {
10256     LoadSDNode *LD = cast<LoadSDNode>(N);
10257     EVT VT = LD->getValueType(0);
10258
10259     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10260     if (VT.isSimple()) {
10261       MVT LoadVT = VT.getSimpleVT();
10262       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10263           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10264            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10265         return expandVSXLoadForLE(N, DCI);
10266     }
10267
10268     EVT MemVT = LD->getMemoryVT();
10269     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10270     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
10271     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10272     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
10273     if (LD->isUnindexed() && VT.isVector() &&
10274         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10275           // P8 and later hardware should just use LOAD.
10276           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10277                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10278          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10279           LD->getAlignment() >= ScalarABIAlignment)) &&
10280         LD->getAlignment() < ABIAlignment) {
10281       // This is a type-legal unaligned Altivec or QPX load.
10282       SDValue Chain = LD->getChain();
10283       SDValue Ptr = LD->getBasePtr();
10284       bool isLittleEndian = Subtarget.isLittleEndian();
10285
10286       // This implements the loading of unaligned vectors as described in
10287       // the venerable Apple Velocity Engine overview. Specifically:
10288       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10289       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10290       //
10291       // The general idea is to expand a sequence of one or more unaligned
10292       // loads into an alignment-based permutation-control instruction (lvsl
10293       // or lvsr), a series of regular vector loads (which always truncate
10294       // their input address to an aligned address), and a series of
10295       // permutations.  The results of these permutations are the requested
10296       // loaded values.  The trick is that the last "extra" load is not taken
10297       // from the address you might suspect (sizeof(vector) bytes after the
10298       // last requested load), but rather sizeof(vector) - 1 bytes after the
10299       // last requested vector. The point of this is to avoid a page fault if
10300       // the base address happened to be aligned. This works because if the
10301       // base address is aligned, then adding less than a full vector length
10302       // will cause the last vector in the sequence to be (re)loaded.
10303       // Otherwise, the next vector will be fetched as you might suspect was
10304       // necessary.
10305
10306       // We might be able to reuse the permutation generation from
10307       // a different base address offset from this one by an aligned amount.
10308       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10309       // optimization later.
10310       Intrinsic::ID Intr, IntrLD, IntrPerm;
10311       MVT PermCntlTy, PermTy, LDTy;
10312       if (Subtarget.hasAltivec()) {
10313         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10314                                  Intrinsic::ppc_altivec_lvsl;
10315         IntrLD = Intrinsic::ppc_altivec_lvx;
10316         IntrPerm = Intrinsic::ppc_altivec_vperm;
10317         PermCntlTy = MVT::v16i8;
10318         PermTy = MVT::v4i32;
10319         LDTy = MVT::v4i32;
10320       } else {
10321         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10322                                        Intrinsic::ppc_qpx_qvlpcls;
10323         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10324                                        Intrinsic::ppc_qpx_qvlfs;
10325         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10326         PermCntlTy = MVT::v4f64;
10327         PermTy = MVT::v4f64;
10328         LDTy = MemVT.getSimpleVT();
10329       }
10330
10331       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10332
10333       // Create the new MMO for the new base load. It is like the original MMO,
10334       // but represents an area in memory almost twice the vector size centered
10335       // on the original address. If the address is unaligned, we might start
10336       // reading up to (sizeof(vector)-1) bytes below the address of the
10337       // original unaligned load.
10338       MachineFunction &MF = DAG.getMachineFunction();
10339       MachineMemOperand *BaseMMO =
10340         MF.getMachineMemOperand(LD->getMemOperand(),
10341                                 -(long)MemVT.getStoreSize()+1,
10342                                 2*MemVT.getStoreSize()-1);
10343
10344       // Create the new base load.
10345       SDValue LDXIntID =
10346           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
10347       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10348       SDValue BaseLoad =
10349         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10350                                 DAG.getVTList(PermTy, MVT::Other),
10351                                 BaseLoadOps, LDTy, BaseMMO);
10352
10353       // Note that the value of IncOffset (which is provided to the next
10354       // load's pointer info offset value, and thus used to calculate the
10355       // alignment), and the value of IncValue (which is actually used to
10356       // increment the pointer value) are different! This is because we
10357       // require the next load to appear to be aligned, even though it
10358       // is actually offset from the base pointer by a lesser amount.
10359       int IncOffset = VT.getSizeInBits() / 8;
10360       int IncValue = IncOffset;
10361
10362       // Walk (both up and down) the chain looking for another load at the real
10363       // (aligned) offset (the alignment of the other load does not matter in
10364       // this case). If found, then do not use the offset reduction trick, as
10365       // that will prevent the loads from being later combined (as they would
10366       // otherwise be duplicates).
10367       if (!findConsecutiveLoad(LD, DAG))
10368         --IncValue;
10369
10370       SDValue Increment =
10371           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
10372       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10373
10374       MachineMemOperand *ExtraMMO =
10375         MF.getMachineMemOperand(LD->getMemOperand(),
10376                                 1, 2*MemVT.getStoreSize()-1);
10377       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10378       SDValue ExtraLoad =
10379         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10380                                 DAG.getVTList(PermTy, MVT::Other),
10381                                 ExtraLoadOps, LDTy, ExtraMMO);
10382
10383       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10384         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10385
10386       // Because vperm has a big-endian bias, we must reverse the order
10387       // of the input vectors and complement the permute control vector
10388       // when generating little endian code.  We have already handled the
10389       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10390       // and ExtraLoad here.
10391       SDValue Perm;
10392       if (isLittleEndian)
10393         Perm = BuildIntrinsicOp(IntrPerm,
10394                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10395       else
10396         Perm = BuildIntrinsicOp(IntrPerm,
10397                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10398
10399       if (VT != PermTy)
10400         Perm = Subtarget.hasAltivec() ?
10401                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10402                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10403                                DAG.getTargetConstant(1, dl, MVT::i64));
10404                                // second argument is 1 because this rounding
10405                                // is always exact.
10406
10407       // The output of the permutation is our loaded result, the TokenFactor is
10408       // our new chain.
10409       DCI.CombineTo(N, Perm, TF);
10410       return SDValue(N, 0);
10411     }
10412     }
10413     break;
10414     case ISD::INTRINSIC_WO_CHAIN: {
10415       bool isLittleEndian = Subtarget.isLittleEndian();
10416       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10417       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10418                                            : Intrinsic::ppc_altivec_lvsl);
10419       if ((IID == Intr ||
10420            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10421            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10422         N->getOperand(1)->getOpcode() == ISD::ADD) {
10423         SDValue Add = N->getOperand(1);
10424
10425         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10426                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10427
10428         if (DAG.MaskedValueIsZero(
10429                 Add->getOperand(1),
10430                 APInt::getAllOnesValue(Bits /* alignment */)
10431                     .zext(
10432                         Add.getValueType().getScalarType().getSizeInBits()))) {
10433           SDNode *BasePtr = Add->getOperand(0).getNode();
10434           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10435                                     UE = BasePtr->use_end();
10436                UI != UE; ++UI) {
10437             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10438                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10439               // We've found another LVSL/LVSR, and this address is an aligned
10440               // multiple of that one. The results will be the same, so use the
10441               // one we've just found instead.
10442
10443               return SDValue(*UI, 0);
10444             }
10445           }
10446         }
10447
10448         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10449           SDNode *BasePtr = Add->getOperand(0).getNode();
10450           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10451                UE = BasePtr->use_end(); UI != UE; ++UI) {
10452             if (UI->getOpcode() == ISD::ADD &&
10453                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10454                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10455                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10456                 (1ULL << Bits) == 0) {
10457               SDNode *OtherAdd = *UI;
10458               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10459                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10460                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10461                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10462                   return SDValue(*VI, 0);
10463                 }
10464               }
10465             }
10466           }
10467         }
10468       }
10469     }
10470
10471     break;
10472   case ISD::INTRINSIC_W_CHAIN: {
10473     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10474     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10475       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10476       default:
10477         break;
10478       case Intrinsic::ppc_vsx_lxvw4x:
10479       case Intrinsic::ppc_vsx_lxvd2x:
10480         return expandVSXLoadForLE(N, DCI);
10481       }
10482     }
10483     break;
10484   }
10485   case ISD::INTRINSIC_VOID: {
10486     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10487     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10488       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10489       default:
10490         break;
10491       case Intrinsic::ppc_vsx_stxvw4x:
10492       case Intrinsic::ppc_vsx_stxvd2x:
10493         return expandVSXStoreForLE(N, DCI);
10494       }
10495     }
10496     break;
10497   }
10498   case ISD::BSWAP:
10499     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10500     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10501         N->getOperand(0).hasOneUse() &&
10502         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10503          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10504           N->getValueType(0) == MVT::i64))) {
10505       SDValue Load = N->getOperand(0);
10506       LoadSDNode *LD = cast<LoadSDNode>(Load);
10507       // Create the byte-swapping load.
10508       SDValue Ops[] = {
10509         LD->getChain(),    // Chain
10510         LD->getBasePtr(),  // Ptr
10511         DAG.getValueType(N->getValueType(0)) // VT
10512       };
10513       SDValue BSLoad =
10514         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10515                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10516                                               MVT::i64 : MVT::i32, MVT::Other),
10517                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10518
10519       // If this is an i16 load, insert the truncate.
10520       SDValue ResVal = BSLoad;
10521       if (N->getValueType(0) == MVT::i16)
10522         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10523
10524       // First, combine the bswap away.  This makes the value produced by the
10525       // load dead.
10526       DCI.CombineTo(N, ResVal);
10527
10528       // Next, combine the load away, we give it a bogus result value but a real
10529       // chain result.  The result value is dead because the bswap is dead.
10530       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10531
10532       // Return N so it doesn't get rechecked!
10533       return SDValue(N, 0);
10534     }
10535
10536     break;
10537   case PPCISD::VCMP: {
10538     // If a VCMPo node already exists with exactly the same operands as this
10539     // node, use its result instead of this node (VCMPo computes both a CR6 and
10540     // a normal output).
10541     //
10542     if (!N->getOperand(0).hasOneUse() &&
10543         !N->getOperand(1).hasOneUse() &&
10544         !N->getOperand(2).hasOneUse()) {
10545
10546       // Scan all of the users of the LHS, looking for VCMPo's that match.
10547       SDNode *VCMPoNode = nullptr;
10548
10549       SDNode *LHSN = N->getOperand(0).getNode();
10550       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10551            UI != E; ++UI)
10552         if (UI->getOpcode() == PPCISD::VCMPo &&
10553             UI->getOperand(1) == N->getOperand(1) &&
10554             UI->getOperand(2) == N->getOperand(2) &&
10555             UI->getOperand(0) == N->getOperand(0)) {
10556           VCMPoNode = *UI;
10557           break;
10558         }
10559
10560       // If there is no VCMPo node, or if the flag value has a single use, don't
10561       // transform this.
10562       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10563         break;
10564
10565       // Look at the (necessarily single) use of the flag value.  If it has a
10566       // chain, this transformation is more complex.  Note that multiple things
10567       // could use the value result, which we should ignore.
10568       SDNode *FlagUser = nullptr;
10569       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10570            FlagUser == nullptr; ++UI) {
10571         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10572         SDNode *User = *UI;
10573         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10574           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10575             FlagUser = User;
10576             break;
10577           }
10578         }
10579       }
10580
10581       // If the user is a MFOCRF instruction, we know this is safe.
10582       // Otherwise we give up for right now.
10583       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10584         return SDValue(VCMPoNode, 0);
10585     }
10586     break;
10587   }
10588   case ISD::BRCOND: {
10589     SDValue Cond = N->getOperand(1);
10590     SDValue Target = N->getOperand(2);
10591
10592     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10593         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10594           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10595
10596       // We now need to make the intrinsic dead (it cannot be instruction
10597       // selected).
10598       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10599       assert(Cond.getNode()->hasOneUse() &&
10600              "Counter decrement has more than one use");
10601
10602       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10603                          N->getOperand(0), Target);
10604     }
10605   }
10606   break;
10607   case ISD::BR_CC: {
10608     // If this is a branch on an altivec predicate comparison, lower this so
10609     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10610     // lowering is done pre-legalize, because the legalizer lowers the predicate
10611     // compare down to code that is difficult to reassemble.
10612     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10613     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10614
10615     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10616     // value. If so, pass-through the AND to get to the intrinsic.
10617     if (LHS.getOpcode() == ISD::AND &&
10618         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10619         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10620           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10621         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10622         !isNullConstant(LHS.getOperand(1)))
10623       LHS = LHS.getOperand(0);
10624
10625     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10626         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10627           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10628         isa<ConstantSDNode>(RHS)) {
10629       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10630              "Counter decrement comparison is not EQ or NE");
10631
10632       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10633       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10634                     (CC == ISD::SETNE && !Val);
10635
10636       // We now need to make the intrinsic dead (it cannot be instruction
10637       // selected).
10638       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10639       assert(LHS.getNode()->hasOneUse() &&
10640              "Counter decrement has more than one use");
10641
10642       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10643                          N->getOperand(0), N->getOperand(4));
10644     }
10645
10646     int CompareOpc;
10647     bool isDot;
10648
10649     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10650         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10651         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10652       assert(isDot && "Can't compare against a vector result!");
10653
10654       // If this is a comparison against something other than 0/1, then we know
10655       // that the condition is never/always true.
10656       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10657       if (Val != 0 && Val != 1) {
10658         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10659           return N->getOperand(0);
10660         // Always !=, turn it into an unconditional branch.
10661         return DAG.getNode(ISD::BR, dl, MVT::Other,
10662                            N->getOperand(0), N->getOperand(4));
10663       }
10664
10665       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10666
10667       // Create the PPCISD altivec 'dot' comparison node.
10668       SDValue Ops[] = {
10669         LHS.getOperand(2),  // LHS of compare
10670         LHS.getOperand(3),  // RHS of compare
10671         DAG.getConstant(CompareOpc, dl, MVT::i32)
10672       };
10673       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10674       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10675
10676       // Unpack the result based on how the target uses it.
10677       PPC::Predicate CompOpc;
10678       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10679       default:  // Can't happen, don't crash on invalid number though.
10680       case 0:   // Branch on the value of the EQ bit of CR6.
10681         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10682         break;
10683       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10684         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10685         break;
10686       case 2:   // Branch on the value of the LT bit of CR6.
10687         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10688         break;
10689       case 3:   // Branch on the inverted value of the LT bit of CR6.
10690         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10691         break;
10692       }
10693
10694       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10695                          DAG.getConstant(CompOpc, dl, MVT::i32),
10696                          DAG.getRegister(PPC::CR6, MVT::i32),
10697                          N->getOperand(4), CompNode.getValue(1));
10698     }
10699     break;
10700   }
10701   }
10702
10703   return SDValue();
10704 }
10705
10706 SDValue
10707 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10708                                   SelectionDAG &DAG,
10709                                   std::vector<SDNode *> *Created) const {
10710   // fold (sdiv X, pow2)
10711   EVT VT = N->getValueType(0);
10712   if (VT == MVT::i64 && !Subtarget.isPPC64())
10713     return SDValue();
10714   if ((VT != MVT::i32 && VT != MVT::i64) ||
10715       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10716     return SDValue();
10717
10718   SDLoc DL(N);
10719   SDValue N0 = N->getOperand(0);
10720
10721   bool IsNegPow2 = (-Divisor).isPowerOf2();
10722   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10723   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10724
10725   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10726   if (Created)
10727     Created->push_back(Op.getNode());
10728
10729   if (IsNegPow2) {
10730     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10731     if (Created)
10732       Created->push_back(Op.getNode());
10733   }
10734
10735   return Op;
10736 }
10737
10738 //===----------------------------------------------------------------------===//
10739 // Inline Assembly Support
10740 //===----------------------------------------------------------------------===//
10741
10742 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10743                                                       APInt &KnownZero,
10744                                                       APInt &KnownOne,
10745                                                       const SelectionDAG &DAG,
10746                                                       unsigned Depth) const {
10747   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10748   switch (Op.getOpcode()) {
10749   default: break;
10750   case PPCISD::LBRX: {
10751     // lhbrx is known to have the top bits cleared out.
10752     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10753       KnownZero = 0xFFFF0000;
10754     break;
10755   }
10756   case ISD::INTRINSIC_WO_CHAIN: {
10757     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10758     default: break;
10759     case Intrinsic::ppc_altivec_vcmpbfp_p:
10760     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10761     case Intrinsic::ppc_altivec_vcmpequb_p:
10762     case Intrinsic::ppc_altivec_vcmpequh_p:
10763     case Intrinsic::ppc_altivec_vcmpequw_p:
10764     case Intrinsic::ppc_altivec_vcmpequd_p:
10765     case Intrinsic::ppc_altivec_vcmpgefp_p:
10766     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10767     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10768     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10769     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10770     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10771     case Intrinsic::ppc_altivec_vcmpgtub_p:
10772     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10773     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10774     case Intrinsic::ppc_altivec_vcmpgtud_p:
10775       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10776       break;
10777     }
10778   }
10779   }
10780 }
10781
10782 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10783   switch (Subtarget.getDarwinDirective()) {
10784   default: break;
10785   case PPC::DIR_970:
10786   case PPC::DIR_PWR4:
10787   case PPC::DIR_PWR5:
10788   case PPC::DIR_PWR5X:
10789   case PPC::DIR_PWR6:
10790   case PPC::DIR_PWR6X:
10791   case PPC::DIR_PWR7:
10792   case PPC::DIR_PWR8: {
10793     if (!ML)
10794       break;
10795
10796     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10797
10798     // For small loops (between 5 and 8 instructions), align to a 32-byte
10799     // boundary so that the entire loop fits in one instruction-cache line.
10800     uint64_t LoopSize = 0;
10801     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10802       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10803         LoopSize += TII->GetInstSizeInBytes(J);
10804
10805     if (LoopSize > 16 && LoopSize <= 32)
10806       return 5;
10807
10808     break;
10809   }
10810   }
10811
10812   return TargetLowering::getPrefLoopAlignment(ML);
10813 }
10814
10815 /// getConstraintType - Given a constraint, return the type of
10816 /// constraint it is for this target.
10817 PPCTargetLowering::ConstraintType
10818 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
10819   if (Constraint.size() == 1) {
10820     switch (Constraint[0]) {
10821     default: break;
10822     case 'b':
10823     case 'r':
10824     case 'f':
10825     case 'v':
10826     case 'y':
10827       return C_RegisterClass;
10828     case 'Z':
10829       // FIXME: While Z does indicate a memory constraint, it specifically
10830       // indicates an r+r address (used in conjunction with the 'y' modifier
10831       // in the replacement string). Currently, we're forcing the base
10832       // register to be r0 in the asm printer (which is interpreted as zero)
10833       // and forming the complete address in the second register. This is
10834       // suboptimal.
10835       return C_Memory;
10836     }
10837   } else if (Constraint == "wc") { // individual CR bits.
10838     return C_RegisterClass;
10839   } else if (Constraint == "wa" || Constraint == "wd" ||
10840              Constraint == "wf" || Constraint == "ws") {
10841     return C_RegisterClass; // VSX registers.
10842   }
10843   return TargetLowering::getConstraintType(Constraint);
10844 }
10845
10846 /// Examine constraint type and operand type and determine a weight value.
10847 /// This object must already have been set up with the operand type
10848 /// and the current alternative constraint selected.
10849 TargetLowering::ConstraintWeight
10850 PPCTargetLowering::getSingleConstraintMatchWeight(
10851     AsmOperandInfo &info, const char *constraint) const {
10852   ConstraintWeight weight = CW_Invalid;
10853   Value *CallOperandVal = info.CallOperandVal;
10854     // If we don't have a value, we can't do a match,
10855     // but allow it at the lowest weight.
10856   if (!CallOperandVal)
10857     return CW_Default;
10858   Type *type = CallOperandVal->getType();
10859
10860   // Look at the constraint type.
10861   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10862     return CW_Register; // an individual CR bit.
10863   else if ((StringRef(constraint) == "wa" ||
10864             StringRef(constraint) == "wd" ||
10865             StringRef(constraint) == "wf") &&
10866            type->isVectorTy())
10867     return CW_Register;
10868   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10869     return CW_Register;
10870
10871   switch (*constraint) {
10872   default:
10873     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10874     break;
10875   case 'b':
10876     if (type->isIntegerTy())
10877       weight = CW_Register;
10878     break;
10879   case 'f':
10880     if (type->isFloatTy())
10881       weight = CW_Register;
10882     break;
10883   case 'd':
10884     if (type->isDoubleTy())
10885       weight = CW_Register;
10886     break;
10887   case 'v':
10888     if (type->isVectorTy())
10889       weight = CW_Register;
10890     break;
10891   case 'y':
10892     weight = CW_Register;
10893     break;
10894   case 'Z':
10895     weight = CW_Memory;
10896     break;
10897   }
10898   return weight;
10899 }
10900
10901 std::pair<unsigned, const TargetRegisterClass *>
10902 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10903                                                 StringRef Constraint,
10904                                                 MVT VT) const {
10905   if (Constraint.size() == 1) {
10906     // GCC RS6000 Constraint Letters
10907     switch (Constraint[0]) {
10908     case 'b':   // R1-R31
10909       if (VT == MVT::i64 && Subtarget.isPPC64())
10910         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10911       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10912     case 'r':   // R0-R31
10913       if (VT == MVT::i64 && Subtarget.isPPC64())
10914         return std::make_pair(0U, &PPC::G8RCRegClass);
10915       return std::make_pair(0U, &PPC::GPRCRegClass);
10916     case 'f':
10917       if (VT == MVT::f32 || VT == MVT::i32)
10918         return std::make_pair(0U, &PPC::F4RCRegClass);
10919       if (VT == MVT::f64 || VT == MVT::i64)
10920         return std::make_pair(0U, &PPC::F8RCRegClass);
10921       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10922         return std::make_pair(0U, &PPC::QFRCRegClass);
10923       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10924         return std::make_pair(0U, &PPC::QSRCRegClass);
10925       break;
10926     case 'v':
10927       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10928         return std::make_pair(0U, &PPC::QFRCRegClass);
10929       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10930         return std::make_pair(0U, &PPC::QSRCRegClass);
10931       if (Subtarget.hasAltivec())
10932         return std::make_pair(0U, &PPC::VRRCRegClass);
10933     case 'y':   // crrc
10934       return std::make_pair(0U, &PPC::CRRCRegClass);
10935     }
10936   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
10937     // An individual CR bit.
10938     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10939   } else if ((Constraint == "wa" || Constraint == "wd" ||
10940              Constraint == "wf") && Subtarget.hasVSX()) {
10941     return std::make_pair(0U, &PPC::VSRCRegClass);
10942   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
10943     if (VT == MVT::f32 && Subtarget.hasP8Vector())
10944       return std::make_pair(0U, &PPC::VSSRCRegClass);
10945     else
10946       return std::make_pair(0U, &PPC::VSFRCRegClass);
10947   }
10948
10949   std::pair<unsigned, const TargetRegisterClass *> R =
10950       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10951
10952   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10953   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10954   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10955   // register.
10956   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10957   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10958   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10959       PPC::GPRCRegClass.contains(R.first))
10960     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10961                             PPC::sub_32, &PPC::G8RCRegClass),
10962                           &PPC::G8RCRegClass);
10963
10964   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10965   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10966     R.first = PPC::CR0;
10967     R.second = &PPC::CRRCRegClass;
10968   }
10969
10970   return R;
10971 }
10972
10973 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10974 /// vector.  If it is invalid, don't add anything to Ops.
10975 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10976                                                      std::string &Constraint,
10977                                                      std::vector<SDValue>&Ops,
10978                                                      SelectionDAG &DAG) const {
10979   SDValue Result;
10980
10981   // Only support length 1 constraints.
10982   if (Constraint.length() > 1) return;
10983
10984   char Letter = Constraint[0];
10985   switch (Letter) {
10986   default: break;
10987   case 'I':
10988   case 'J':
10989   case 'K':
10990   case 'L':
10991   case 'M':
10992   case 'N':
10993   case 'O':
10994   case 'P': {
10995     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10996     if (!CST) return; // Must be an immediate to match.
10997     SDLoc dl(Op);
10998     int64_t Value = CST->getSExtValue();
10999     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
11000                          // numbers are printed as such.
11001     switch (Letter) {
11002     default: llvm_unreachable("Unknown constraint letter!");
11003     case 'I':  // "I" is a signed 16-bit constant.
11004       if (isInt<16>(Value))
11005         Result = DAG.getTargetConstant(Value, dl, TCVT);
11006       break;
11007     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
11008       if (isShiftedUInt<16, 16>(Value))
11009         Result = DAG.getTargetConstant(Value, dl, TCVT);
11010       break;
11011     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
11012       if (isShiftedInt<16, 16>(Value))
11013         Result = DAG.getTargetConstant(Value, dl, TCVT);
11014       break;
11015     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
11016       if (isUInt<16>(Value))
11017         Result = DAG.getTargetConstant(Value, dl, TCVT);
11018       break;
11019     case 'M':  // "M" is a constant that is greater than 31.
11020       if (Value > 31)
11021         Result = DAG.getTargetConstant(Value, dl, TCVT);
11022       break;
11023     case 'N':  // "N" is a positive constant that is an exact power of two.
11024       if (Value > 0 && isPowerOf2_64(Value))
11025         Result = DAG.getTargetConstant(Value, dl, TCVT);
11026       break;
11027     case 'O':  // "O" is the constant zero.
11028       if (Value == 0)
11029         Result = DAG.getTargetConstant(Value, dl, TCVT);
11030       break;
11031     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
11032       if (isInt<16>(-Value))
11033         Result = DAG.getTargetConstant(Value, dl, TCVT);
11034       break;
11035     }
11036     break;
11037   }
11038   }
11039
11040   if (Result.getNode()) {
11041     Ops.push_back(Result);
11042     return;
11043   }
11044
11045   // Handle standard constraint letters.
11046   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11047 }
11048
11049 // isLegalAddressingMode - Return true if the addressing mode represented
11050 // by AM is legal for this target, for a load/store of the specified type.
11051 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11052                                               const AddrMode &AM, Type *Ty,
11053                                               unsigned AS) const {
11054   // PPC does not allow r+i addressing modes for vectors!
11055   if (Ty->isVectorTy() && AM.BaseOffs != 0)
11056     return false;
11057
11058   // PPC allows a sign-extended 16-bit immediate field.
11059   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
11060     return false;
11061
11062   // No global is ever allowed as a base.
11063   if (AM.BaseGV)
11064     return false;
11065
11066   // PPC only support r+r,
11067   switch (AM.Scale) {
11068   case 0:  // "r+i" or just "i", depending on HasBaseReg.
11069     break;
11070   case 1:
11071     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
11072       return false;
11073     // Otherwise we have r+r or r+i.
11074     break;
11075   case 2:
11076     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
11077       return false;
11078     // Allow 2*r as r+r.
11079     break;
11080   default:
11081     // No other scales are supported.
11082     return false;
11083   }
11084
11085   return true;
11086 }
11087
11088 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
11089                                            SelectionDAG &DAG) const {
11090   MachineFunction &MF = DAG.getMachineFunction();
11091   MachineFrameInfo *MFI = MF.getFrameInfo();
11092   MFI->setReturnAddressIsTaken(true);
11093
11094   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
11095     return SDValue();
11096
11097   SDLoc dl(Op);
11098   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11099
11100   // Make sure the function does not optimize away the store of the RA to
11101   // the stack.
11102   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
11103   FuncInfo->setLRStoreRequired();
11104   bool isPPC64 = Subtarget.isPPC64();
11105   auto PtrVT = getPointerTy(MF.getDataLayout());
11106
11107   if (Depth > 0) {
11108     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11109     SDValue Offset =
11110         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
11111                         isPPC64 ? MVT::i64 : MVT::i32);
11112     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11113                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
11114                        MachinePointerInfo(), false, false, false, 0);
11115   }
11116
11117   // Just load the return address off the stack.
11118   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
11119   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
11120                      MachinePointerInfo(), false, false, false, 0);
11121 }
11122
11123 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
11124                                           SelectionDAG &DAG) const {
11125   SDLoc dl(Op);
11126   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11127
11128   MachineFunction &MF = DAG.getMachineFunction();
11129   MachineFrameInfo *MFI = MF.getFrameInfo();
11130   MFI->setFrameAddressIsTaken(true);
11131
11132   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout());
11133   bool isPPC64 = PtrVT == MVT::i64;
11134
11135   // Naked functions never have a frame pointer, and so we use r1. For all
11136   // other functions, this decision must be delayed until during PEI.
11137   unsigned FrameReg;
11138   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
11139     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
11140   else
11141     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
11142
11143   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
11144                                          PtrVT);
11145   while (Depth--)
11146     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
11147                             FrameAddr, MachinePointerInfo(), false, false,
11148                             false, 0);
11149   return FrameAddr;
11150 }
11151
11152 // FIXME? Maybe this could be a TableGen attribute on some registers and
11153 // this table could be generated automatically from RegInfo.
11154 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
11155                                               SelectionDAG &DAG) const {
11156   bool isPPC64 = Subtarget.isPPC64();
11157   bool isDarwinABI = Subtarget.isDarwinABI();
11158
11159   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
11160       (!isPPC64 && VT != MVT::i32))
11161     report_fatal_error("Invalid register global variable type");
11162
11163   bool is64Bit = isPPC64 && VT == MVT::i64;
11164   unsigned Reg = StringSwitch<unsigned>(RegName)
11165                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
11166                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
11167                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
11168                                   (is64Bit ? PPC::X13 : PPC::R13))
11169                    .Default(0);
11170
11171   if (Reg)
11172     return Reg;
11173   report_fatal_error("Invalid register name global variable");
11174 }
11175
11176 bool
11177 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11178   // The PowerPC target isn't yet aware of offsets.
11179   return false;
11180 }
11181
11182 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11183                                            const CallInst &I,
11184                                            unsigned Intrinsic) const {
11185
11186   switch (Intrinsic) {
11187   case Intrinsic::ppc_qpx_qvlfd:
11188   case Intrinsic::ppc_qpx_qvlfs:
11189   case Intrinsic::ppc_qpx_qvlfcd:
11190   case Intrinsic::ppc_qpx_qvlfcs:
11191   case Intrinsic::ppc_qpx_qvlfiwa:
11192   case Intrinsic::ppc_qpx_qvlfiwz:
11193   case Intrinsic::ppc_altivec_lvx:
11194   case Intrinsic::ppc_altivec_lvxl:
11195   case Intrinsic::ppc_altivec_lvebx:
11196   case Intrinsic::ppc_altivec_lvehx:
11197   case Intrinsic::ppc_altivec_lvewx:
11198   case Intrinsic::ppc_vsx_lxvd2x:
11199   case Intrinsic::ppc_vsx_lxvw4x: {
11200     EVT VT;
11201     switch (Intrinsic) {
11202     case Intrinsic::ppc_altivec_lvebx:
11203       VT = MVT::i8;
11204       break;
11205     case Intrinsic::ppc_altivec_lvehx:
11206       VT = MVT::i16;
11207       break;
11208     case Intrinsic::ppc_altivec_lvewx:
11209       VT = MVT::i32;
11210       break;
11211     case Intrinsic::ppc_vsx_lxvd2x:
11212       VT = MVT::v2f64;
11213       break;
11214     case Intrinsic::ppc_qpx_qvlfd:
11215       VT = MVT::v4f64;
11216       break;
11217     case Intrinsic::ppc_qpx_qvlfs:
11218       VT = MVT::v4f32;
11219       break;
11220     case Intrinsic::ppc_qpx_qvlfcd:
11221       VT = MVT::v2f64;
11222       break;
11223     case Intrinsic::ppc_qpx_qvlfcs:
11224       VT = MVT::v2f32;
11225       break;
11226     default:
11227       VT = MVT::v4i32;
11228       break;
11229     }
11230
11231     Info.opc = ISD::INTRINSIC_W_CHAIN;
11232     Info.memVT = VT;
11233     Info.ptrVal = I.getArgOperand(0);
11234     Info.offset = -VT.getStoreSize()+1;
11235     Info.size = 2*VT.getStoreSize()-1;
11236     Info.align = 1;
11237     Info.vol = false;
11238     Info.readMem = true;
11239     Info.writeMem = false;
11240     return true;
11241   }
11242   case Intrinsic::ppc_qpx_qvlfda:
11243   case Intrinsic::ppc_qpx_qvlfsa:
11244   case Intrinsic::ppc_qpx_qvlfcda:
11245   case Intrinsic::ppc_qpx_qvlfcsa:
11246   case Intrinsic::ppc_qpx_qvlfiwaa:
11247   case Intrinsic::ppc_qpx_qvlfiwza: {
11248     EVT VT;
11249     switch (Intrinsic) {
11250     case Intrinsic::ppc_qpx_qvlfda:
11251       VT = MVT::v4f64;
11252       break;
11253     case Intrinsic::ppc_qpx_qvlfsa:
11254       VT = MVT::v4f32;
11255       break;
11256     case Intrinsic::ppc_qpx_qvlfcda:
11257       VT = MVT::v2f64;
11258       break;
11259     case Intrinsic::ppc_qpx_qvlfcsa:
11260       VT = MVT::v2f32;
11261       break;
11262     default:
11263       VT = MVT::v4i32;
11264       break;
11265     }
11266
11267     Info.opc = ISD::INTRINSIC_W_CHAIN;
11268     Info.memVT = VT;
11269     Info.ptrVal = I.getArgOperand(0);
11270     Info.offset = 0;
11271     Info.size = VT.getStoreSize();
11272     Info.align = 1;
11273     Info.vol = false;
11274     Info.readMem = true;
11275     Info.writeMem = false;
11276     return true;
11277   }
11278   case Intrinsic::ppc_qpx_qvstfd:
11279   case Intrinsic::ppc_qpx_qvstfs:
11280   case Intrinsic::ppc_qpx_qvstfcd:
11281   case Intrinsic::ppc_qpx_qvstfcs:
11282   case Intrinsic::ppc_qpx_qvstfiw:
11283   case Intrinsic::ppc_altivec_stvx:
11284   case Intrinsic::ppc_altivec_stvxl:
11285   case Intrinsic::ppc_altivec_stvebx:
11286   case Intrinsic::ppc_altivec_stvehx:
11287   case Intrinsic::ppc_altivec_stvewx:
11288   case Intrinsic::ppc_vsx_stxvd2x:
11289   case Intrinsic::ppc_vsx_stxvw4x: {
11290     EVT VT;
11291     switch (Intrinsic) {
11292     case Intrinsic::ppc_altivec_stvebx:
11293       VT = MVT::i8;
11294       break;
11295     case Intrinsic::ppc_altivec_stvehx:
11296       VT = MVT::i16;
11297       break;
11298     case Intrinsic::ppc_altivec_stvewx:
11299       VT = MVT::i32;
11300       break;
11301     case Intrinsic::ppc_vsx_stxvd2x:
11302       VT = MVT::v2f64;
11303       break;
11304     case Intrinsic::ppc_qpx_qvstfd:
11305       VT = MVT::v4f64;
11306       break;
11307     case Intrinsic::ppc_qpx_qvstfs:
11308       VT = MVT::v4f32;
11309       break;
11310     case Intrinsic::ppc_qpx_qvstfcd:
11311       VT = MVT::v2f64;
11312       break;
11313     case Intrinsic::ppc_qpx_qvstfcs:
11314       VT = MVT::v2f32;
11315       break;
11316     default:
11317       VT = MVT::v4i32;
11318       break;
11319     }
11320
11321     Info.opc = ISD::INTRINSIC_VOID;
11322     Info.memVT = VT;
11323     Info.ptrVal = I.getArgOperand(1);
11324     Info.offset = -VT.getStoreSize()+1;
11325     Info.size = 2*VT.getStoreSize()-1;
11326     Info.align = 1;
11327     Info.vol = false;
11328     Info.readMem = false;
11329     Info.writeMem = true;
11330     return true;
11331   }
11332   case Intrinsic::ppc_qpx_qvstfda:
11333   case Intrinsic::ppc_qpx_qvstfsa:
11334   case Intrinsic::ppc_qpx_qvstfcda:
11335   case Intrinsic::ppc_qpx_qvstfcsa:
11336   case Intrinsic::ppc_qpx_qvstfiwa: {
11337     EVT VT;
11338     switch (Intrinsic) {
11339     case Intrinsic::ppc_qpx_qvstfda:
11340       VT = MVT::v4f64;
11341       break;
11342     case Intrinsic::ppc_qpx_qvstfsa:
11343       VT = MVT::v4f32;
11344       break;
11345     case Intrinsic::ppc_qpx_qvstfcda:
11346       VT = MVT::v2f64;
11347       break;
11348     case Intrinsic::ppc_qpx_qvstfcsa:
11349       VT = MVT::v2f32;
11350       break;
11351     default:
11352       VT = MVT::v4i32;
11353       break;
11354     }
11355
11356     Info.opc = ISD::INTRINSIC_VOID;
11357     Info.memVT = VT;
11358     Info.ptrVal = I.getArgOperand(1);
11359     Info.offset = 0;
11360     Info.size = VT.getStoreSize();
11361     Info.align = 1;
11362     Info.vol = false;
11363     Info.readMem = false;
11364     Info.writeMem = true;
11365     return true;
11366   }
11367   default:
11368     break;
11369   }
11370
11371   return false;
11372 }
11373
11374 /// getOptimalMemOpType - Returns the target specific optimal type for load
11375 /// and store operations as a result of memset, memcpy, and memmove
11376 /// lowering. If DstAlign is zero that means it's safe to destination
11377 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11378 /// means there isn't a need to check it against alignment requirement,
11379 /// probably because the source does not need to be loaded. If 'IsMemset' is
11380 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11381 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11382 /// source is constant so it does not need to be loaded.
11383 /// It returns EVT::Other if the type should be determined using generic
11384 /// target-independent logic.
11385 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11386                                            unsigned DstAlign, unsigned SrcAlign,
11387                                            bool IsMemset, bool ZeroMemset,
11388                                            bool MemcpyStrSrc,
11389                                            MachineFunction &MF) const {
11390   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11391     const Function *F = MF.getFunction();
11392     // When expanding a memset, require at least two QPX instructions to cover
11393     // the cost of loading the value to be stored from the constant pool.
11394     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11395        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11396         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11397       return MVT::v4f64;
11398     }
11399
11400     // We should use Altivec/VSX loads and stores when available. For unaligned
11401     // addresses, unaligned VSX loads are only fast starting with the P8.
11402     if (Subtarget.hasAltivec() && Size >= 16 &&
11403         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11404          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11405       return MVT::v4i32;
11406   }
11407
11408   if (Subtarget.isPPC64()) {
11409     return MVT::i64;
11410   }
11411
11412   return MVT::i32;
11413 }
11414
11415 /// \brief Returns true if it is beneficial to convert a load of a constant
11416 /// to just the constant itself.
11417 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11418                                                           Type *Ty) const {
11419   assert(Ty->isIntegerTy());
11420
11421   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11422   if (BitSize == 0 || BitSize > 64)
11423     return false;
11424   return true;
11425 }
11426
11427 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11428   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11429     return false;
11430   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11431   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11432   return NumBits1 == 64 && NumBits2 == 32;
11433 }
11434
11435 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11436   if (!VT1.isInteger() || !VT2.isInteger())
11437     return false;
11438   unsigned NumBits1 = VT1.getSizeInBits();
11439   unsigned NumBits2 = VT2.getSizeInBits();
11440   return NumBits1 == 64 && NumBits2 == 32;
11441 }
11442
11443 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11444   // Generally speaking, zexts are not free, but they are free when they can be
11445   // folded with other operations.
11446   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11447     EVT MemVT = LD->getMemoryVT();
11448     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11449          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11450         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11451          LD->getExtensionType() == ISD::ZEXTLOAD))
11452       return true;
11453   }
11454
11455   // FIXME: Add other cases...
11456   //  - 32-bit shifts with a zext to i64
11457   //  - zext after ctlz, bswap, etc.
11458   //  - zext after and by a constant mask
11459
11460   return TargetLowering::isZExtFree(Val, VT2);
11461 }
11462
11463 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11464   assert(VT.isFloatingPoint());
11465   return true;
11466 }
11467
11468 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11469   return isInt<16>(Imm) || isUInt<16>(Imm);
11470 }
11471
11472 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11473   return isInt<16>(Imm) || isUInt<16>(Imm);
11474 }
11475
11476 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11477                                                        unsigned,
11478                                                        unsigned,
11479                                                        bool *Fast) const {
11480   if (DisablePPCUnaligned)
11481     return false;
11482
11483   // PowerPC supports unaligned memory access for simple non-vector types.
11484   // Although accessing unaligned addresses is not as efficient as accessing
11485   // aligned addresses, it is generally more efficient than manual expansion,
11486   // and generally only traps for software emulation when crossing page
11487   // boundaries.
11488
11489   if (!VT.isSimple())
11490     return false;
11491
11492   if (VT.getSimpleVT().isVector()) {
11493     if (Subtarget.hasVSX()) {
11494       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11495           VT != MVT::v4f32 && VT != MVT::v4i32)
11496         return false;
11497     } else {
11498       return false;
11499     }
11500   }
11501
11502   if (VT == MVT::ppcf128)
11503     return false;
11504
11505   if (Fast)
11506     *Fast = true;
11507
11508   return true;
11509 }
11510
11511 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11512   VT = VT.getScalarType();
11513
11514   if (!VT.isSimple())
11515     return false;
11516
11517   switch (VT.getSimpleVT().SimpleTy) {
11518   case MVT::f32:
11519   case MVT::f64:
11520     return true;
11521   default:
11522     break;
11523   }
11524
11525   return false;
11526 }
11527
11528 const MCPhysReg *
11529 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11530   // LR is a callee-save register, but we must treat it as clobbered by any call
11531   // site. Hence we include LR in the scratch registers, which are in turn added
11532   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11533   // to CTR, which is used by any indirect call.
11534   static const MCPhysReg ScratchRegs[] = {
11535     PPC::X12, PPC::LR8, PPC::CTR8, 0
11536   };
11537
11538   return ScratchRegs;
11539 }
11540
11541 unsigned PPCTargetLowering::getExceptionPointerRegister(
11542     const Constant *PersonalityFn) const {
11543   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
11544 }
11545
11546 unsigned PPCTargetLowering::getExceptionSelectorRegister(
11547     const Constant *PersonalityFn) const {
11548   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
11549 }
11550
11551 bool
11552 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11553                      EVT VT , unsigned DefinedValues) const {
11554   if (VT == MVT::v2i64)
11555     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
11556
11557   if (Subtarget.hasQPX()) {
11558     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11559       return true;
11560   }
11561
11562   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11563 }
11564
11565 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11566   if (DisableILPPref || Subtarget.enableMachineScheduler())
11567     return TargetLowering::getSchedulingPreference(N);
11568
11569   return Sched::ILP;
11570 }
11571
11572 // Create a fast isel object.
11573 FastISel *
11574 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11575                                   const TargetLibraryInfo *LibInfo) const {
11576   return PPC::createFastISel(FuncInfo, LibInfo);
11577 }