This patch adds support for the vector quadword add/sub instructions introduced
[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
333   // We want to custom lower some of our intrinsics.
334   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
335
336   // To handle counter-based loop conditions.
337   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
338
339   // Comparisons that require checking two conditions.
340   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
341   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
343   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
345   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
347   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
349   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
351   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
352
353   if (Subtarget.has64BitSupport()) {
354     // They also have instructions for converting between i64 and fp.
355     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
356     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
357     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
358     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
359     // This is just the low 32 bits of a (signed) fp->i64 conversion.
360     // We cannot do this with Promote because i64 is not a legal type.
361     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
362
363     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
364       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
365   } else {
366     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
367     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
368   }
369
370   // With the instructions enabled under FPCVT, we can do everything.
371   if (Subtarget.hasFPCVT()) {
372     if (Subtarget.has64BitSupport()) {
373       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
374       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
375       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
376       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
377     }
378
379     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
380     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
381     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
382     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
383   }
384
385   if (Subtarget.use64BitRegs()) {
386     // 64-bit PowerPC implementations can support i64 types directly
387     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
388     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
389     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
390     // 64-bit PowerPC wants to expand i128 shifts itself.
391     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
393     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
394   } else {
395     // 32-bit PowerPC wants to expand i64 shifts itself.
396     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
398     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
399   }
400
401   if (Subtarget.hasAltivec()) {
402     // First set operation action for all vector types to expand. Then we
403     // will selectively turn on ones that can be effectively codegen'd.
404     for (MVT VT : MVT::vector_valuetypes()) {
405       // add/sub are legal for all supported vector VT's.
406       setOperationAction(ISD::ADD , VT, Legal);
407       setOperationAction(ISD::SUB , VT, Legal);
408       
409       // Vector instructions introduced in P8
410       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
411         setOperationAction(ISD::CTPOP, VT, Legal);
412         setOperationAction(ISD::CTLZ, VT, Legal);
413       }
414       else {
415         setOperationAction(ISD::CTPOP, VT, Expand);
416         setOperationAction(ISD::CTLZ, VT, Expand);
417       }
418
419       // We promote all shuffles to v16i8.
420       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
421       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
422
423       // We promote all non-typed operations to v4i32.
424       setOperationAction(ISD::AND   , VT, Promote);
425       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
426       setOperationAction(ISD::OR    , VT, Promote);
427       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
428       setOperationAction(ISD::XOR   , VT, Promote);
429       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
430       setOperationAction(ISD::LOAD  , VT, Promote);
431       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
432       setOperationAction(ISD::SELECT, VT, Promote);
433       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
434       setOperationAction(ISD::STORE, VT, Promote);
435       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
436
437       // No other operations are legal.
438       setOperationAction(ISD::MUL , VT, Expand);
439       setOperationAction(ISD::SDIV, VT, Expand);
440       setOperationAction(ISD::SREM, VT, Expand);
441       setOperationAction(ISD::UDIV, VT, Expand);
442       setOperationAction(ISD::UREM, VT, Expand);
443       setOperationAction(ISD::FDIV, VT, Expand);
444       setOperationAction(ISD::FREM, VT, Expand);
445       setOperationAction(ISD::FNEG, VT, Expand);
446       setOperationAction(ISD::FSQRT, VT, Expand);
447       setOperationAction(ISD::FLOG, VT, Expand);
448       setOperationAction(ISD::FLOG10, VT, Expand);
449       setOperationAction(ISD::FLOG2, VT, Expand);
450       setOperationAction(ISD::FEXP, VT, Expand);
451       setOperationAction(ISD::FEXP2, VT, Expand);
452       setOperationAction(ISD::FSIN, VT, Expand);
453       setOperationAction(ISD::FCOS, VT, Expand);
454       setOperationAction(ISD::FABS, VT, Expand);
455       setOperationAction(ISD::FPOWI, VT, Expand);
456       setOperationAction(ISD::FFLOOR, VT, Expand);
457       setOperationAction(ISD::FCEIL,  VT, Expand);
458       setOperationAction(ISD::FTRUNC, VT, Expand);
459       setOperationAction(ISD::FRINT,  VT, Expand);
460       setOperationAction(ISD::FNEARBYINT, VT, Expand);
461       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
462       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
463       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
464       setOperationAction(ISD::MULHU, VT, Expand);
465       setOperationAction(ISD::MULHS, VT, Expand);
466       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
467       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
468       setOperationAction(ISD::UDIVREM, VT, Expand);
469       setOperationAction(ISD::SDIVREM, VT, Expand);
470       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
471       setOperationAction(ISD::FPOW, VT, Expand);
472       setOperationAction(ISD::BSWAP, VT, Expand);
473       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
474       setOperationAction(ISD::CTTZ, VT, Expand);
475       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
476       setOperationAction(ISD::VSELECT, VT, Expand);
477       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
478
479       for (MVT InnerVT : MVT::vector_valuetypes()) {
480         setTruncStoreAction(VT, InnerVT, Expand);
481         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
482         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
483         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
484       }
485     }
486
487     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
488     // with merges, splats, etc.
489     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
490
491     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
492     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
493     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
494     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
495     setOperationAction(ISD::SELECT, MVT::v4i32,
496                        Subtarget.useCRBits() ? Legal : Expand);
497     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
498     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
499     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
500     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
501     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
502     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
503     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
504     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
505     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
506
507     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
508     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
509     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
510     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
511
512     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
513     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
514
515     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
516       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
517       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
518     }
519
520     
521     if (Subtarget.hasP8Altivec()) 
522       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
523     else
524       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
525       
526     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
527     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
528
529     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
530     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
531
532     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
533     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
534     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
535     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
536
537     // Altivec does not contain unordered floating-point compare instructions
538     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
539     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
540     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
541     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
542
543     if (Subtarget.hasVSX()) {
544       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
545       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
546
547       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
548       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
549       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
550       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
551       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
552
553       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
554
555       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
556       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
557
558       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
559       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
560
561       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
562       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
563       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
564       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
565       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
566
567       // Share the Altivec comparison restrictions.
568       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
569       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
570       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
571       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
572
573       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
574       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
575
576       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
577
578       if (Subtarget.hasP8Vector())
579         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
580
581       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
582
583       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
584       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
585
586       if (Subtarget.hasP8Altivec()) {
587         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
588         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
589         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
590
591         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
592       }
593       else {
594         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
595         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
596         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
597
598         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
599
600         // VSX v2i64 only supports non-arithmetic operations.
601         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
602         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
603       }
604
605       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
606       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
607       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
608       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
609
610       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
611
612       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
613       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
614       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
615       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
616
617       // Vector operation legalization checks the result type of
618       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
619       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
620       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
621       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
622       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
623
624       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
625     }
626
627     if (Subtarget.hasP8Altivec()) {
628       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
629       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
630     }
631   }
632
633   if (Subtarget.hasQPX()) {
634     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
635     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
636     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
637     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
638
639     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
640     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
641
642     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
643     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
644
645     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
646     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
647
648     if (!Subtarget.useCRBits())
649       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
650     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
651
652     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
653     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
654     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
655     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
656     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
657     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
658     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
659
660     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
661     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
662
663     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
664     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
665     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
666
667     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
668     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
669     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
670     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
671     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
672     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
673     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
674     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
675     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
676     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
677     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
678
679     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
680     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
681
682     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
683     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
684
685     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
686
687     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
688     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
689     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
690     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
691
692     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
693     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
694
695     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
696     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
697
698     if (!Subtarget.useCRBits())
699       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
700     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
701
702     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
703     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
704     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
705     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
706     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
707     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
708     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
709
710     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
711     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
712
713     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
714     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
715     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
716     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
717     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
718     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
719     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
720     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
721     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
722     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
723     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
724
725     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
726     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
727
728     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
729     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
730
731     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
732
733     setOperationAction(ISD::AND , MVT::v4i1, Legal);
734     setOperationAction(ISD::OR , MVT::v4i1, Legal);
735     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
736
737     if (!Subtarget.useCRBits())
738       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
739     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
740
741     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
742     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
743
744     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
745     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
746     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
747     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
748     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
749     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
750     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
751
752     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
753     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
754
755     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
756
757     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
758     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
759     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
760     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
761
762     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
763     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
764     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
765     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
766
767     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
768     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
769
770     // These need to set FE_INEXACT, and so cannot be vectorized here.
771     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
772     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
773
774     if (TM.Options.UnsafeFPMath) {
775       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
776       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
777
778       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
779       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
780     } else {
781       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
782       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
783
784       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
785       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
786     }
787   }
788
789   if (Subtarget.has64BitSupport())
790     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
791
792   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
793
794   if (!isPPC64) {
795     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
796     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
797   }
798
799   setBooleanContents(ZeroOrOneBooleanContent);
800
801   if (Subtarget.hasAltivec()) {
802     // Altivec instructions set fields to all zeros or all ones.
803     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
804   }
805
806   if (!isPPC64) {
807     // These libcalls are not available in 32-bit.
808     setLibcallName(RTLIB::SHL_I128, nullptr);
809     setLibcallName(RTLIB::SRL_I128, nullptr);
810     setLibcallName(RTLIB::SRA_I128, nullptr);
811   }
812
813   if (isPPC64) {
814     setStackPointerRegisterToSaveRestore(PPC::X1);
815     setExceptionPointerRegister(PPC::X3);
816     setExceptionSelectorRegister(PPC::X4);
817   } else {
818     setStackPointerRegisterToSaveRestore(PPC::R1);
819     setExceptionPointerRegister(PPC::R3);
820     setExceptionSelectorRegister(PPC::R4);
821   }
822
823   // We have target-specific dag combine patterns for the following nodes:
824   setTargetDAGCombine(ISD::SINT_TO_FP);
825   if (Subtarget.hasFPCVT())
826     setTargetDAGCombine(ISD::UINT_TO_FP);
827   setTargetDAGCombine(ISD::LOAD);
828   setTargetDAGCombine(ISD::STORE);
829   setTargetDAGCombine(ISD::BR_CC);
830   if (Subtarget.useCRBits())
831     setTargetDAGCombine(ISD::BRCOND);
832   setTargetDAGCombine(ISD::BSWAP);
833   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
834   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
835   setTargetDAGCombine(ISD::INTRINSIC_VOID);
836
837   setTargetDAGCombine(ISD::SIGN_EXTEND);
838   setTargetDAGCombine(ISD::ZERO_EXTEND);
839   setTargetDAGCombine(ISD::ANY_EXTEND);
840
841   if (Subtarget.useCRBits()) {
842     setTargetDAGCombine(ISD::TRUNCATE);
843     setTargetDAGCombine(ISD::SETCC);
844     setTargetDAGCombine(ISD::SELECT_CC);
845   }
846
847   // Use reciprocal estimates.
848   if (TM.Options.UnsafeFPMath) {
849     setTargetDAGCombine(ISD::FDIV);
850     setTargetDAGCombine(ISD::FSQRT);
851   }
852
853   // Darwin long double math library functions have $LDBL128 appended.
854   if (Subtarget.isDarwin()) {
855     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
856     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
857     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
858     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
859     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
860     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
861     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
862     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
863     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
864     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
865   }
866
867   // With 32 condition bits, we don't need to sink (and duplicate) compares
868   // aggressively in CodeGenPrep.
869   if (Subtarget.useCRBits()) {
870     setHasMultipleConditionRegisters();
871     setJumpIsExpensive();
872   }
873
874   setMinFunctionAlignment(2);
875   if (Subtarget.isDarwin())
876     setPrefFunctionAlignment(4);
877
878   switch (Subtarget.getDarwinDirective()) {
879   default: break;
880   case PPC::DIR_970:
881   case PPC::DIR_A2:
882   case PPC::DIR_E500mc:
883   case PPC::DIR_E5500:
884   case PPC::DIR_PWR4:
885   case PPC::DIR_PWR5:
886   case PPC::DIR_PWR5X:
887   case PPC::DIR_PWR6:
888   case PPC::DIR_PWR6X:
889   case PPC::DIR_PWR7:
890   case PPC::DIR_PWR8:
891     setPrefFunctionAlignment(4);
892     setPrefLoopAlignment(4);
893     break;
894   }
895
896   setInsertFencesForAtomic(true);
897
898   if (Subtarget.enableMachineScheduler())
899     setSchedulingPreference(Sched::Source);
900   else
901     setSchedulingPreference(Sched::Hybrid);
902
903   computeRegisterProperties(STI.getRegisterInfo());
904
905   // The Freescale cores do better with aggressive inlining of memcpy and
906   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
907   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
908       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
909     MaxStoresPerMemset = 32;
910     MaxStoresPerMemsetOptSize = 16;
911     MaxStoresPerMemcpy = 32;
912     MaxStoresPerMemcpyOptSize = 8;
913     MaxStoresPerMemmove = 32;
914     MaxStoresPerMemmoveOptSize = 8;
915   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
916     // The A2 also benefits from (very) aggressive inlining of memcpy and
917     // friends. The overhead of a the function call, even when warm, can be
918     // over one hundred cycles.
919     MaxStoresPerMemset = 128;
920     MaxStoresPerMemcpy = 128;
921     MaxStoresPerMemmove = 128;
922   }
923 }
924
925 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
926 /// the desired ByVal argument alignment.
927 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
928                              unsigned MaxMaxAlign) {
929   if (MaxAlign == MaxMaxAlign)
930     return;
931   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
932     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
933       MaxAlign = 32;
934     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
935       MaxAlign = 16;
936   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
937     unsigned EltAlign = 0;
938     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
939     if (EltAlign > MaxAlign)
940       MaxAlign = EltAlign;
941   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
942     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
943       unsigned EltAlign = 0;
944       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
945       if (EltAlign > MaxAlign)
946         MaxAlign = EltAlign;
947       if (MaxAlign == MaxMaxAlign)
948         break;
949     }
950   }
951 }
952
953 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
954 /// function arguments in the caller parameter area.
955 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
956   // Darwin passes everything on 4 byte boundary.
957   if (Subtarget.isDarwin())
958     return 4;
959
960   // 16byte and wider vectors are passed on 16byte boundary.
961   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
962   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
963   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
964     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
965   return Align;
966 }
967
968 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
969   switch ((PPCISD::NodeType)Opcode) {
970   case PPCISD::FIRST_NUMBER:    break;
971   case PPCISD::FSEL:            return "PPCISD::FSEL";
972   case PPCISD::FCFID:           return "PPCISD::FCFID";
973   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
974   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
975   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
976   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
977   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
978   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
979   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
980   case PPCISD::FRE:             return "PPCISD::FRE";
981   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
982   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
983   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
984   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
985   case PPCISD::VPERM:           return "PPCISD::VPERM";
986   case PPCISD::CMPB:            return "PPCISD::CMPB";
987   case PPCISD::Hi:              return "PPCISD::Hi";
988   case PPCISD::Lo:              return "PPCISD::Lo";
989   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
990   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
991   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
992   case PPCISD::SRL:             return "PPCISD::SRL";
993   case PPCISD::SRA:             return "PPCISD::SRA";
994   case PPCISD::SHL:             return "PPCISD::SHL";
995   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
996   case PPCISD::CALL:            return "PPCISD::CALL";
997   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
998   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
999   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1000   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1001   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1002   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1003   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1004   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1005   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1006   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1007   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1008   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1009   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1010   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1011   case PPCISD::VCMP:            return "PPCISD::VCMP";
1012   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1013   case PPCISD::LBRX:            return "PPCISD::LBRX";
1014   case PPCISD::STBRX:           return "PPCISD::STBRX";
1015   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1016   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1017   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1018   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1019   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1020   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1021   case PPCISD::BDZ:             return "PPCISD::BDZ";
1022   case PPCISD::MFFS:            return "PPCISD::MFFS";
1023   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1024   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1025   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1026   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1027   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1028   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1029   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1030   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1031   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1032   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1033   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1034   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1035   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1036   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1037   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1038   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1039   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1040   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1041   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1042   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1043   case PPCISD::SC:              return "PPCISD::SC";
1044   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1045   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1046   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1047   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1048   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1049   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1050   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1051   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1052   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1053   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1054   }
1055   return nullptr;
1056 }
1057
1058 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &C, EVT VT) const {
1059   if (!VT.isVector())
1060     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1061
1062   if (Subtarget.hasQPX())
1063     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1064
1065   return VT.changeVectorElementTypeToInteger();
1066 }
1067
1068 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1069   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1070   return true;
1071 }
1072
1073 //===----------------------------------------------------------------------===//
1074 // Node matching predicates, for use by the tblgen matching code.
1075 //===----------------------------------------------------------------------===//
1076
1077 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1078 static bool isFloatingPointZero(SDValue Op) {
1079   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1080     return CFP->getValueAPF().isZero();
1081   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1082     // Maybe this has already been legalized into the constant pool?
1083     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1084       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1085         return CFP->getValueAPF().isZero();
1086   }
1087   return false;
1088 }
1089
1090 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1091 /// true if Op is undef or if it matches the specified value.
1092 static bool isConstantOrUndef(int Op, int Val) {
1093   return Op < 0 || Op == Val;
1094 }
1095
1096 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1097 /// VPKUHUM instruction.
1098 /// The ShuffleKind distinguishes between big-endian operations with
1099 /// two different inputs (0), either-endian operations with two identical
1100 /// inputs (1), and little-endian operations with two different inputs (2).
1101 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1102 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1103                                SelectionDAG &DAG) {
1104   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1105   if (ShuffleKind == 0) {
1106     if (IsLE)
1107       return false;
1108     for (unsigned i = 0; i != 16; ++i)
1109       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1110         return false;
1111   } else if (ShuffleKind == 2) {
1112     if (!IsLE)
1113       return false;
1114     for (unsigned i = 0; i != 16; ++i)
1115       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1116         return false;
1117   } else if (ShuffleKind == 1) {
1118     unsigned j = IsLE ? 0 : 1;
1119     for (unsigned i = 0; i != 8; ++i)
1120       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1121           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1122         return false;
1123   }
1124   return true;
1125 }
1126
1127 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1128 /// VPKUWUM instruction.
1129 /// The ShuffleKind distinguishes between big-endian operations with
1130 /// two different inputs (0), either-endian operations with two identical
1131 /// inputs (1), and little-endian operations with two different inputs (2).
1132 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1133 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1134                                SelectionDAG &DAG) {
1135   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1136   if (ShuffleKind == 0) {
1137     if (IsLE)
1138       return false;
1139     for (unsigned i = 0; i != 16; i += 2)
1140       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1141           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1142         return false;
1143   } else if (ShuffleKind == 2) {
1144     if (!IsLE)
1145       return false;
1146     for (unsigned i = 0; i != 16; i += 2)
1147       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1148           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1149         return false;
1150   } else if (ShuffleKind == 1) {
1151     unsigned j = IsLE ? 0 : 2;
1152     for (unsigned i = 0; i != 8; i += 2)
1153       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1154           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1155           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1156           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1157         return false;
1158   }
1159   return true;
1160 }
1161
1162 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1163 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1164 /// current subtarget.
1165 ///
1166 /// The ShuffleKind distinguishes between big-endian operations with
1167 /// two different inputs (0), either-endian operations with two identical
1168 /// inputs (1), and little-endian operations with two different inputs (2).
1169 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1170 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1171                                SelectionDAG &DAG) {
1172   const PPCSubtarget& Subtarget =
1173     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1174   if (!Subtarget.hasP8Vector())
1175     return false;
1176
1177   bool IsLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1178   if (ShuffleKind == 0) {
1179     if (IsLE)
1180       return false;
1181     for (unsigned i = 0; i != 16; i += 4)
1182       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1183           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1184           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1185           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1186         return false;
1187   } else if (ShuffleKind == 2) {
1188     if (!IsLE)
1189       return false;
1190     for (unsigned i = 0; i != 16; i += 4)
1191       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1192           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1193           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1194           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1195         return false;
1196   } else if (ShuffleKind == 1) {
1197     unsigned j = IsLE ? 0 : 4;
1198     for (unsigned i = 0; i != 8; i += 4)
1199       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1200           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1201           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1202           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1203           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1204           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1205           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1206           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1207         return false;
1208   }
1209   return true;
1210 }
1211
1212 /// isVMerge - Common function, used to match vmrg* shuffles.
1213 ///
1214 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1215                      unsigned LHSStart, unsigned RHSStart) {
1216   if (N->getValueType(0) != MVT::v16i8)
1217     return false;
1218   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1219          "Unsupported merge size!");
1220
1221   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1222     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1223       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1224                              LHSStart+j+i*UnitSize) ||
1225           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1226                              RHSStart+j+i*UnitSize))
1227         return false;
1228     }
1229   return true;
1230 }
1231
1232 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1233 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1234 /// The ShuffleKind distinguishes between big-endian merges with two 
1235 /// different inputs (0), either-endian merges with two identical inputs (1),
1236 /// and little-endian merges with two different inputs (2).  For the latter,
1237 /// the input operands are swapped (see PPCInstrAltivec.td).
1238 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1239                              unsigned ShuffleKind, SelectionDAG &DAG) {
1240   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1241     if (ShuffleKind == 1) // unary
1242       return isVMerge(N, UnitSize, 0, 0);
1243     else if (ShuffleKind == 2) // swapped
1244       return isVMerge(N, UnitSize, 0, 16);
1245     else
1246       return false;
1247   } else {
1248     if (ShuffleKind == 1) // unary
1249       return isVMerge(N, UnitSize, 8, 8);
1250     else if (ShuffleKind == 0) // normal
1251       return isVMerge(N, UnitSize, 8, 24);
1252     else
1253       return false;
1254   }
1255 }
1256
1257 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1258 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1259 /// The ShuffleKind distinguishes between big-endian merges with two 
1260 /// different inputs (0), either-endian merges with two identical inputs (1),
1261 /// and little-endian merges with two different inputs (2).  For the latter,
1262 /// the input operands are swapped (see PPCInstrAltivec.td).
1263 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1264                              unsigned ShuffleKind, SelectionDAG &DAG) {
1265   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
1266     if (ShuffleKind == 1) // unary
1267       return isVMerge(N, UnitSize, 8, 8);
1268     else if (ShuffleKind == 2) // swapped
1269       return isVMerge(N, UnitSize, 8, 24);
1270     else
1271       return false;
1272   } else {
1273     if (ShuffleKind == 1) // unary
1274       return isVMerge(N, UnitSize, 0, 0);
1275     else if (ShuffleKind == 0) // normal
1276       return isVMerge(N, UnitSize, 0, 16);
1277     else
1278       return false;
1279   }
1280 }
1281
1282
1283 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1284 /// amount, otherwise return -1.
1285 /// The ShuffleKind distinguishes between big-endian operations with two 
1286 /// different inputs (0), either-endian operations with two identical inputs
1287 /// (1), and little-endian operations with two different inputs (2).  For the
1288 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1289 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1290                              SelectionDAG &DAG) {
1291   if (N->getValueType(0) != MVT::v16i8)
1292     return -1;
1293
1294   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1295
1296   // Find the first non-undef value in the shuffle mask.
1297   unsigned i;
1298   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1299     /*search*/;
1300
1301   if (i == 16) return -1;  // all undef.
1302
1303   // Otherwise, check to see if the rest of the elements are consecutively
1304   // numbered from this value.
1305   unsigned ShiftAmt = SVOp->getMaskElt(i);
1306   if (ShiftAmt < i) return -1;
1307
1308   ShiftAmt -= i;
1309   bool isLE = DAG.getTarget().getDataLayout()->isLittleEndian();
1310
1311   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1312     // Check the rest of the elements to see if they are consecutive.
1313     for (++i; i != 16; ++i)
1314       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1315         return -1;
1316   } else if (ShuffleKind == 1) {
1317     // Check the rest of the elements to see if they are consecutive.
1318     for (++i; i != 16; ++i)
1319       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1320         return -1;
1321   } else
1322     return -1;
1323
1324   if (ShuffleKind == 2 && isLE)
1325     ShiftAmt = 16 - ShiftAmt;
1326
1327   return ShiftAmt;
1328 }
1329
1330 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1331 /// specifies a splat of a single element that is suitable for input to
1332 /// VSPLTB/VSPLTH/VSPLTW.
1333 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1334   assert(N->getValueType(0) == MVT::v16i8 &&
1335          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1336
1337   // This is a splat operation if each element of the permute is the same, and
1338   // if the value doesn't reference the second vector.
1339   unsigned ElementBase = N->getMaskElt(0);
1340
1341   // FIXME: Handle UNDEF elements too!
1342   if (ElementBase >= 16)
1343     return false;
1344
1345   // Check that the indices are consecutive, in the case of a multi-byte element
1346   // splatted with a v16i8 mask.
1347   for (unsigned i = 1; i != EltSize; ++i)
1348     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1349       return false;
1350
1351   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1352     if (N->getMaskElt(i) < 0) continue;
1353     for (unsigned j = 0; j != EltSize; ++j)
1354       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1355         return false;
1356   }
1357   return true;
1358 }
1359
1360 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1361 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1362 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1363                                 SelectionDAG &DAG) {
1364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1365   assert(isSplatShuffleMask(SVOp, EltSize));
1366   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1367     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1368   else
1369     return SVOp->getMaskElt(0) / EltSize;
1370 }
1371
1372 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1373 /// by using a vspltis[bhw] instruction of the specified element size, return
1374 /// the constant being splatted.  The ByteSize field indicates the number of
1375 /// bytes of each element [124] -> [bhw].
1376 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1377   SDValue OpVal(nullptr, 0);
1378
1379   // If ByteSize of the splat is bigger than the element size of the
1380   // build_vector, then we have a case where we are checking for a splat where
1381   // multiple elements of the buildvector are folded together into a single
1382   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1383   unsigned EltSize = 16/N->getNumOperands();
1384   if (EltSize < ByteSize) {
1385     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1386     SDValue UniquedVals[4];
1387     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1388
1389     // See if all of the elements in the buildvector agree across.
1390     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1391       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1392       // If the element isn't a constant, bail fully out.
1393       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1394
1395
1396       if (!UniquedVals[i&(Multiple-1)].getNode())
1397         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1398       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1399         return SDValue();  // no match.
1400     }
1401
1402     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1403     // either constant or undef values that are identical for each chunk.  See
1404     // if these chunks can form into a larger vspltis*.
1405
1406     // Check to see if all of the leading entries are either 0 or -1.  If
1407     // neither, then this won't fit into the immediate field.
1408     bool LeadingZero = true;
1409     bool LeadingOnes = true;
1410     for (unsigned i = 0; i != Multiple-1; ++i) {
1411       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1412
1413       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1414       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1415     }
1416     // Finally, check the least significant entry.
1417     if (LeadingZero) {
1418       if (!UniquedVals[Multiple-1].getNode())
1419         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1420       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1421       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1422         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1423     }
1424     if (LeadingOnes) {
1425       if (!UniquedVals[Multiple-1].getNode())
1426         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1427       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1428       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1429         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1430     }
1431
1432     return SDValue();
1433   }
1434
1435   // Check to see if this buildvec has a single non-undef value in its elements.
1436   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1437     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1438     if (!OpVal.getNode())
1439       OpVal = N->getOperand(i);
1440     else if (OpVal != N->getOperand(i))
1441       return SDValue();
1442   }
1443
1444   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1445
1446   unsigned ValSizeInBytes = EltSize;
1447   uint64_t Value = 0;
1448   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1449     Value = CN->getZExtValue();
1450   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1451     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1452     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1453   }
1454
1455   // If the splat value is larger than the element value, then we can never do
1456   // this splat.  The only case that we could fit the replicated bits into our
1457   // immediate field for would be zero, and we prefer to use vxor for it.
1458   if (ValSizeInBytes < ByteSize) return SDValue();
1459
1460   // If the element value is larger than the splat value, check if it consists
1461   // of a repeated bit pattern of size ByteSize.
1462   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1463     return SDValue();
1464
1465   // Properly sign extend the value.
1466   int MaskVal = SignExtend32(Value, ByteSize * 8);
1467
1468   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1469   if (MaskVal == 0) return SDValue();
1470
1471   // Finally, if this value fits in a 5 bit sext field, return it
1472   if (SignExtend32<5>(MaskVal) == MaskVal)
1473     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1474   return SDValue();
1475 }
1476
1477 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1478 /// amount, otherwise return -1.
1479 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1480   EVT VT = N->getValueType(0);
1481   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1482     return -1;
1483
1484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1485
1486   // Find the first non-undef value in the shuffle mask.
1487   unsigned i;
1488   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1489     /*search*/;
1490
1491   if (i == 4) return -1;  // all undef.
1492
1493   // Otherwise, check to see if the rest of the elements are consecutively
1494   // numbered from this value.
1495   unsigned ShiftAmt = SVOp->getMaskElt(i);
1496   if (ShiftAmt < i) return -1;
1497   ShiftAmt -= i;
1498
1499   // Check the rest of the elements to see if they are consecutive.
1500   for (++i; i != 4; ++i)
1501     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1502       return -1;
1503
1504   return ShiftAmt;
1505 }
1506
1507 //===----------------------------------------------------------------------===//
1508 //  Addressing Mode Selection
1509 //===----------------------------------------------------------------------===//
1510
1511 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1512 /// or 64-bit immediate, and if the value can be accurately represented as a
1513 /// sign extension from a 16-bit value.  If so, this returns true and the
1514 /// immediate.
1515 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1516   if (!isa<ConstantSDNode>(N))
1517     return false;
1518
1519   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1520   if (N->getValueType(0) == MVT::i32)
1521     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1522   else
1523     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1524 }
1525 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1526   return isIntS16Immediate(Op.getNode(), Imm);
1527 }
1528
1529
1530 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1531 /// can be represented as an indexed [r+r] operation.  Returns false if it
1532 /// can be more efficiently represented with [r+imm].
1533 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1534                                             SDValue &Index,
1535                                             SelectionDAG &DAG) const {
1536   short imm = 0;
1537   if (N.getOpcode() == ISD::ADD) {
1538     if (isIntS16Immediate(N.getOperand(1), imm))
1539       return false;    // r+i
1540     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1541       return false;    // r+i
1542
1543     Base = N.getOperand(0);
1544     Index = N.getOperand(1);
1545     return true;
1546   } else if (N.getOpcode() == ISD::OR) {
1547     if (isIntS16Immediate(N.getOperand(1), imm))
1548       return false;    // r+i can fold it if we can.
1549
1550     // If this is an or of disjoint bitfields, we can codegen this as an add
1551     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1552     // disjoint.
1553     APInt LHSKnownZero, LHSKnownOne;
1554     APInt RHSKnownZero, RHSKnownOne;
1555     DAG.computeKnownBits(N.getOperand(0),
1556                          LHSKnownZero, LHSKnownOne);
1557
1558     if (LHSKnownZero.getBoolValue()) {
1559       DAG.computeKnownBits(N.getOperand(1),
1560                            RHSKnownZero, RHSKnownOne);
1561       // If all of the bits are known zero on the LHS or RHS, the add won't
1562       // carry.
1563       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1564         Base = N.getOperand(0);
1565         Index = N.getOperand(1);
1566         return true;
1567       }
1568     }
1569   }
1570
1571   return false;
1572 }
1573
1574 // If we happen to be doing an i64 load or store into a stack slot that has
1575 // less than a 4-byte alignment, then the frame-index elimination may need to
1576 // use an indexed load or store instruction (because the offset may not be a
1577 // multiple of 4). The extra register needed to hold the offset comes from the
1578 // register scavenger, and it is possible that the scavenger will need to use
1579 // an emergency spill slot. As a result, we need to make sure that a spill slot
1580 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1581 // stack slot.
1582 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1583   // FIXME: This does not handle the LWA case.
1584   if (VT != MVT::i64)
1585     return;
1586
1587   // NOTE: We'll exclude negative FIs here, which come from argument
1588   // lowering, because there are no known test cases triggering this problem
1589   // using packed structures (or similar). We can remove this exclusion if
1590   // we find such a test case. The reason why this is so test-case driven is
1591   // because this entire 'fixup' is only to prevent crashes (from the
1592   // register scavenger) on not-really-valid inputs. For example, if we have:
1593   //   %a = alloca i1
1594   //   %b = bitcast i1* %a to i64*
1595   //   store i64* a, i64 b
1596   // then the store should really be marked as 'align 1', but is not. If it
1597   // were marked as 'align 1' then the indexed form would have been
1598   // instruction-selected initially, and the problem this 'fixup' is preventing
1599   // won't happen regardless.
1600   if (FrameIdx < 0)
1601     return;
1602
1603   MachineFunction &MF = DAG.getMachineFunction();
1604   MachineFrameInfo *MFI = MF.getFrameInfo();
1605
1606   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1607   if (Align >= 4)
1608     return;
1609
1610   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1611   FuncInfo->setHasNonRISpills();
1612 }
1613
1614 /// Returns true if the address N can be represented by a base register plus
1615 /// a signed 16-bit displacement [r+imm], and if it is not better
1616 /// represented as reg+reg.  If Aligned is true, only accept displacements
1617 /// suitable for STD and friends, i.e. multiples of 4.
1618 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1619                                             SDValue &Base,
1620                                             SelectionDAG &DAG,
1621                                             bool Aligned) const {
1622   // FIXME dl should come from parent load or store, not from address
1623   SDLoc dl(N);
1624   // If this can be more profitably realized as r+r, fail.
1625   if (SelectAddressRegReg(N, Disp, Base, DAG))
1626     return false;
1627
1628   if (N.getOpcode() == ISD::ADD) {
1629     short imm = 0;
1630     if (isIntS16Immediate(N.getOperand(1), imm) &&
1631         (!Aligned || (imm & 3) == 0)) {
1632       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1633       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1634         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1635         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1636       } else {
1637         Base = N.getOperand(0);
1638       }
1639       return true; // [r+i]
1640     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1641       // Match LOAD (ADD (X, Lo(G))).
1642       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1643              && "Cannot handle constant offsets yet!");
1644       Disp = N.getOperand(1).getOperand(0);  // The global address.
1645       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1646              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1647              Disp.getOpcode() == ISD::TargetConstantPool ||
1648              Disp.getOpcode() == ISD::TargetJumpTable);
1649       Base = N.getOperand(0);
1650       return true;  // [&g+r]
1651     }
1652   } else if (N.getOpcode() == ISD::OR) {
1653     short imm = 0;
1654     if (isIntS16Immediate(N.getOperand(1), imm) &&
1655         (!Aligned || (imm & 3) == 0)) {
1656       // If this is an or of disjoint bitfields, we can codegen this as an add
1657       // (for better address arithmetic) if the LHS and RHS of the OR are
1658       // provably disjoint.
1659       APInt LHSKnownZero, LHSKnownOne;
1660       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1661
1662       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1663         // If all of the bits are known zero on the LHS or RHS, the add won't
1664         // carry.
1665         if (FrameIndexSDNode *FI =
1666               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1667           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1668           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1669         } else {
1670           Base = N.getOperand(0);
1671         }
1672         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1673         return true;
1674       }
1675     }
1676   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1677     // Loading from a constant address.
1678
1679     // If this address fits entirely in a 16-bit sext immediate field, codegen
1680     // this as "d, 0"
1681     short Imm;
1682     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1683       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1684       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1685                              CN->getValueType(0));
1686       return true;
1687     }
1688
1689     // Handle 32-bit sext immediates with LIS + addr mode.
1690     if ((CN->getValueType(0) == MVT::i32 ||
1691          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1692         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1693       int Addr = (int)CN->getZExtValue();
1694
1695       // Otherwise, break this down into an LIS + disp.
1696       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1697
1698       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1699                                    MVT::i32);
1700       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1701       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1702       return true;
1703     }
1704   }
1705
1706   Disp = DAG.getTargetConstant(0, dl, getPointerTy());
1707   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1708     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1709     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1710   } else
1711     Base = N;
1712   return true;      // [r+0]
1713 }
1714
1715 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1716 /// represented as an indexed [r+r] operation.
1717 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1718                                                 SDValue &Index,
1719                                                 SelectionDAG &DAG) const {
1720   // Check to see if we can easily represent this as an [r+r] address.  This
1721   // will fail if it thinks that the address is more profitably represented as
1722   // reg+imm, e.g. where imm = 0.
1723   if (SelectAddressRegReg(N, Base, Index, DAG))
1724     return true;
1725
1726   // If the operand is an addition, always emit this as [r+r], since this is
1727   // better (for code size, and execution, as the memop does the add for free)
1728   // than emitting an explicit add.
1729   if (N.getOpcode() == ISD::ADD) {
1730     Base = N.getOperand(0);
1731     Index = N.getOperand(1);
1732     return true;
1733   }
1734
1735   // Otherwise, do it the hard way, using R0 as the base register.
1736   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1737                          N.getValueType());
1738   Index = N;
1739   return true;
1740 }
1741
1742 /// getPreIndexedAddressParts - returns true by value, base pointer and
1743 /// offset pointer and addressing mode by reference if the node's address
1744 /// can be legally represented as pre-indexed load / store address.
1745 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1746                                                   SDValue &Offset,
1747                                                   ISD::MemIndexedMode &AM,
1748                                                   SelectionDAG &DAG) const {
1749   if (DisablePPCPreinc) return false;
1750
1751   bool isLoad = true;
1752   SDValue Ptr;
1753   EVT VT;
1754   unsigned Alignment;
1755   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1756     Ptr = LD->getBasePtr();
1757     VT = LD->getMemoryVT();
1758     Alignment = LD->getAlignment();
1759   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1760     Ptr = ST->getBasePtr();
1761     VT  = ST->getMemoryVT();
1762     Alignment = ST->getAlignment();
1763     isLoad = false;
1764   } else
1765     return false;
1766
1767   // PowerPC doesn't have preinc load/store instructions for vectors (except
1768   // for QPX, which does have preinc r+r forms).
1769   if (VT.isVector()) {
1770     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
1771       return false;
1772     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
1773       AM = ISD::PRE_INC;
1774       return true;
1775     }
1776   }
1777
1778   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1779
1780     // Common code will reject creating a pre-inc form if the base pointer
1781     // is a frame index, or if N is a store and the base pointer is either
1782     // the same as or a predecessor of the value being stored.  Check for
1783     // those situations here, and try with swapped Base/Offset instead.
1784     bool Swap = false;
1785
1786     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1787       Swap = true;
1788     else if (!isLoad) {
1789       SDValue Val = cast<StoreSDNode>(N)->getValue();
1790       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1791         Swap = true;
1792     }
1793
1794     if (Swap)
1795       std::swap(Base, Offset);
1796
1797     AM = ISD::PRE_INC;
1798     return true;
1799   }
1800
1801   // LDU/STU can only handle immediates that are a multiple of 4.
1802   if (VT != MVT::i64) {
1803     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1804       return false;
1805   } else {
1806     // LDU/STU need an address with at least 4-byte alignment.
1807     if (Alignment < 4)
1808       return false;
1809
1810     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1811       return false;
1812   }
1813
1814   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1815     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1816     // sext i32 to i64 when addr mode is r+i.
1817     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1818         LD->getExtensionType() == ISD::SEXTLOAD &&
1819         isa<ConstantSDNode>(Offset))
1820       return false;
1821   }
1822
1823   AM = ISD::PRE_INC;
1824   return true;
1825 }
1826
1827 //===----------------------------------------------------------------------===//
1828 //  LowerOperation implementation
1829 //===----------------------------------------------------------------------===//
1830
1831 /// GetLabelAccessInfo - Return true if we should reference labels using a
1832 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1833 static bool GetLabelAccessInfo(const TargetMachine &TM,
1834                                const PPCSubtarget &Subtarget,
1835                                unsigned &HiOpFlags, unsigned &LoOpFlags,
1836                                const GlobalValue *GV = nullptr) {
1837   HiOpFlags = PPCII::MO_HA;
1838   LoOpFlags = PPCII::MO_LO;
1839
1840   // Don't use the pic base if not in PIC relocation model.
1841   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1842
1843   if (isPIC) {
1844     HiOpFlags |= PPCII::MO_PIC_FLAG;
1845     LoOpFlags |= PPCII::MO_PIC_FLAG;
1846   }
1847
1848   // If this is a reference to a global value that requires a non-lazy-ptr, make
1849   // sure that instruction lowering adds it.
1850   if (GV && Subtarget.hasLazyResolverStub(GV)) {
1851     HiOpFlags |= PPCII::MO_NLP_FLAG;
1852     LoOpFlags |= PPCII::MO_NLP_FLAG;
1853
1854     if (GV->hasHiddenVisibility()) {
1855       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1856       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1857     }
1858   }
1859
1860   return isPIC;
1861 }
1862
1863 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1864                              SelectionDAG &DAG) {
1865   SDLoc DL(HiPart);
1866   EVT PtrVT = HiPart.getValueType();
1867   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
1868
1869   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1870   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1871
1872   // With PIC, the first instruction is actually "GR+hi(&G)".
1873   if (isPIC)
1874     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1875                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1876
1877   // Generate non-pic code that has direct accesses to the constant pool.
1878   // The address of the global is just (hi(&g)+lo(&g)).
1879   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1880 }
1881
1882 static void setUsesTOCBasePtr(MachineFunction &MF) {
1883   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1884   FuncInfo->setUsesTOCBasePtr();
1885 }
1886
1887 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
1888   setUsesTOCBasePtr(DAG.getMachineFunction());
1889 }
1890
1891 static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit,
1892                            SDValue GA) {
1893   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1894   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
1895                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
1896
1897   SDValue Ops[] = { GA, Reg };
1898   return DAG.getMemIntrinsicNode(PPCISD::TOC_ENTRY, dl,
1899                                  DAG.getVTList(VT, MVT::Other), Ops, VT,
1900                                  MachinePointerInfo::getGOT(), 0, false, true,
1901                                  false, 0);
1902 }
1903
1904 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1905                                              SelectionDAG &DAG) const {
1906   EVT PtrVT = Op.getValueType();
1907   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1908   const Constant *C = CP->getConstVal();
1909
1910   // 64-bit SVR4 ABI code is always position-independent.
1911   // The actual address of the GlobalValue is stored in the TOC.
1912   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1913     setUsesTOCBasePtr(DAG);
1914     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1915     return getTOCEntry(DAG, SDLoc(CP), true, GA);
1916   }
1917
1918   unsigned MOHiFlag, MOLoFlag;
1919   bool isPIC =
1920       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1921
1922   if (isPIC && Subtarget.isSVR4ABI()) {
1923     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1924                                            PPCII::MO_PIC_FLAG);
1925     return getTOCEntry(DAG, SDLoc(CP), false, GA);
1926   }
1927
1928   SDValue CPIHi =
1929     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1930   SDValue CPILo =
1931     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1932   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1933 }
1934
1935 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1936   EVT PtrVT = Op.getValueType();
1937   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1938
1939   // 64-bit SVR4 ABI code is always position-independent.
1940   // The actual address of the GlobalValue is stored in the TOC.
1941   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1942     setUsesTOCBasePtr(DAG);
1943     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1944     return getTOCEntry(DAG, SDLoc(JT), true, GA);
1945   }
1946
1947   unsigned MOHiFlag, MOLoFlag;
1948   bool isPIC =
1949       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1950
1951   if (isPIC && Subtarget.isSVR4ABI()) {
1952     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1953                                         PPCII::MO_PIC_FLAG);
1954     return getTOCEntry(DAG, SDLoc(GA), false, GA);
1955   }
1956
1957   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1958   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1959   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1960 }
1961
1962 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1963                                              SelectionDAG &DAG) const {
1964   EVT PtrVT = Op.getValueType();
1965   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1966   const BlockAddress *BA = BASDN->getBlockAddress();
1967
1968   // 64-bit SVR4 ABI code is always position-independent.
1969   // The actual BlockAddress is stored in the TOC.
1970   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1971     setUsesTOCBasePtr(DAG);
1972     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1973     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
1974   }
1975
1976   unsigned MOHiFlag, MOLoFlag;
1977   bool isPIC =
1978       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag);
1979   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1980   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1981   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1982 }
1983
1984 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1985                                               SelectionDAG &DAG) const {
1986
1987   // FIXME: TLS addresses currently use medium model code sequences,
1988   // which is the most useful form.  Eventually support for small and
1989   // large models could be added if users need it, at the cost of
1990   // additional complexity.
1991   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1992   SDLoc dl(GA);
1993   const GlobalValue *GV = GA->getGlobal();
1994   EVT PtrVT = getPointerTy();
1995   bool is64bit = Subtarget.isPPC64();
1996   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1997   PICLevel::Level picLevel = M->getPICLevel();
1998
1999   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2000
2001   if (Model == TLSModel::LocalExec) {
2002     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2003                                                PPCII::MO_TPREL_HA);
2004     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2005                                                PPCII::MO_TPREL_LO);
2006     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2007                                      is64bit ? MVT::i64 : MVT::i32);
2008     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2009     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2010   }
2011
2012   if (Model == TLSModel::InitialExec) {
2013     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2014     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2015                                                 PPCII::MO_TLS);
2016     SDValue GOTPtr;
2017     if (is64bit) {
2018       setUsesTOCBasePtr(DAG);
2019       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2020       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2021                            PtrVT, GOTReg, TGA);
2022     } else
2023       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2024     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2025                                    PtrVT, TGA, GOTPtr);
2026     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2027   }
2028
2029   if (Model == TLSModel::GeneralDynamic) {
2030     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2031     SDValue GOTPtr;
2032     if (is64bit) {
2033       setUsesTOCBasePtr(DAG);
2034       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2035       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2036                                    GOTReg, TGA);
2037     } else {
2038       if (picLevel == PICLevel::Small)
2039         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2040       else
2041         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2042     }
2043     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2044                        GOTPtr, TGA, TGA);
2045   }
2046
2047   if (Model == TLSModel::LocalDynamic) {
2048     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2049     SDValue GOTPtr;
2050     if (is64bit) {
2051       setUsesTOCBasePtr(DAG);
2052       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2053       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2054                            GOTReg, TGA);
2055     } else {
2056       if (picLevel == PICLevel::Small)
2057         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2058       else
2059         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2060     }
2061     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2062                                   PtrVT, GOTPtr, TGA, TGA);
2063     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2064                                       PtrVT, TLSAddr, TGA);
2065     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2066   }
2067
2068   llvm_unreachable("Unknown TLS model!");
2069 }
2070
2071 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2072                                               SelectionDAG &DAG) const {
2073   EVT PtrVT = Op.getValueType();
2074   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2075   SDLoc DL(GSDN);
2076   const GlobalValue *GV = GSDN->getGlobal();
2077
2078   // 64-bit SVR4 ABI code is always position-independent.
2079   // The actual address of the GlobalValue is stored in the TOC.
2080   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2081     setUsesTOCBasePtr(DAG);
2082     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2083     return getTOCEntry(DAG, DL, true, GA);
2084   }
2085
2086   unsigned MOHiFlag, MOLoFlag;
2087   bool isPIC =
2088       GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV);
2089
2090   if (isPIC && Subtarget.isSVR4ABI()) {
2091     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2092                                             GSDN->getOffset(),
2093                                             PPCII::MO_PIC_FLAG);
2094     return getTOCEntry(DAG, DL, false, GA);
2095   }
2096
2097   SDValue GAHi =
2098     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2099   SDValue GALo =
2100     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2101
2102   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
2103
2104   // If the global reference is actually to a non-lazy-pointer, we have to do an
2105   // extra load to get the address of the global.
2106   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2107     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
2108                       false, false, false, 0);
2109   return Ptr;
2110 }
2111
2112 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2113   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2114   SDLoc dl(Op);
2115
2116   if (Op.getValueType() == MVT::v2i64) {
2117     // When the operands themselves are v2i64 values, we need to do something
2118     // special because VSX has no underlying comparison operations for these.
2119     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2120       // Equality can be handled by casting to the legal type for Altivec
2121       // comparisons, everything else needs to be expanded.
2122       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2123         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2124                  DAG.getSetCC(dl, MVT::v4i32,
2125                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2126                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2127                    CC));
2128       }
2129
2130       return SDValue();
2131     }
2132
2133     // We handle most of these in the usual way.
2134     return Op;
2135   }
2136
2137   // If we're comparing for equality to zero, expose the fact that this is
2138   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
2139   // fold the new nodes.
2140   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2141     if (C->isNullValue() && CC == ISD::SETEQ) {
2142       EVT VT = Op.getOperand(0).getValueType();
2143       SDValue Zext = Op.getOperand(0);
2144       if (VT.bitsLT(MVT::i32)) {
2145         VT = MVT::i32;
2146         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
2147       }
2148       unsigned Log2b = Log2_32(VT.getSizeInBits());
2149       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
2150       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
2151                                 DAG.getConstant(Log2b, dl, MVT::i32));
2152       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
2153     }
2154     // Leave comparisons against 0 and -1 alone for now, since they're usually
2155     // optimized.  FIXME: revisit this when we can custom lower all setcc
2156     // optimizations.
2157     if (C->isAllOnesValue() || C->isNullValue())
2158       return SDValue();
2159   }
2160
2161   // If we have an integer seteq/setne, turn it into a compare against zero
2162   // by xor'ing the rhs with the lhs, which is faster than setting a
2163   // condition register, reading it back out, and masking the correct bit.  The
2164   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2165   // the result to other bit-twiddling opportunities.
2166   EVT LHSVT = Op.getOperand(0).getValueType();
2167   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2168     EVT VT = Op.getValueType();
2169     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2170                                 Op.getOperand(1));
2171     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2172   }
2173   return SDValue();
2174 }
2175
2176 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
2177                                       const PPCSubtarget &Subtarget) const {
2178   SDNode *Node = Op.getNode();
2179   EVT VT = Node->getValueType(0);
2180   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2181   SDValue InChain = Node->getOperand(0);
2182   SDValue VAListPtr = Node->getOperand(1);
2183   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2184   SDLoc dl(Node);
2185
2186   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2187
2188   // gpr_index
2189   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2190                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
2191                                     false, false, false, 0);
2192   InChain = GprIndex.getValue(1);
2193
2194   if (VT == MVT::i64) {
2195     // Check if GprIndex is even
2196     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2197                                  DAG.getConstant(1, dl, MVT::i32));
2198     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2199                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2200     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2201                                           DAG.getConstant(1, dl, MVT::i32));
2202     // Align GprIndex to be even if it isn't
2203     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2204                            GprIndex);
2205   }
2206
2207   // fpr index is 1 byte after gpr
2208   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2209                                DAG.getConstant(1, dl, MVT::i32));
2210
2211   // fpr
2212   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2213                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
2214                                     false, false, false, 0);
2215   InChain = FprIndex.getValue(1);
2216
2217   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2218                                        DAG.getConstant(8, dl, MVT::i32));
2219
2220   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2221                                         DAG.getConstant(4, dl, MVT::i32));
2222
2223   // areas
2224   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
2225                                      MachinePointerInfo(), false, false,
2226                                      false, 0);
2227   InChain = OverflowArea.getValue(1);
2228
2229   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
2230                                     MachinePointerInfo(), false, false,
2231                                     false, 0);
2232   InChain = RegSaveArea.getValue(1);
2233
2234   // select overflow_area if index > 8
2235   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2236                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2237
2238   // adjustment constant gpr_index * 4/8
2239   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2240                                     VT.isInteger() ? GprIndex : FprIndex,
2241                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2242                                                     MVT::i32));
2243
2244   // OurReg = RegSaveArea + RegConstant
2245   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2246                                RegConstant);
2247
2248   // Floating types are 32 bytes into RegSaveArea
2249   if (VT.isFloatingPoint())
2250     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2251                          DAG.getConstant(32, dl, MVT::i32));
2252
2253   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2254   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2255                                    VT.isInteger() ? GprIndex : FprIndex,
2256                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2257                                                    MVT::i32));
2258
2259   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2260                               VT.isInteger() ? VAListPtr : FprPtr,
2261                               MachinePointerInfo(SV),
2262                               MVT::i8, false, false, 0);
2263
2264   // determine if we should load from reg_save_area or overflow_area
2265   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2266
2267   // increase overflow_area by 4/8 if gpr/fpr > 8
2268   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2269                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2270                                           dl, MVT::i32));
2271
2272   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2273                              OverflowAreaPlusN);
2274
2275   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
2276                               OverflowAreaPtr,
2277                               MachinePointerInfo(),
2278                               MVT::i32, false, false, 0);
2279
2280   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
2281                      false, false, false, 0);
2282 }
2283
2284 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2285                                        const PPCSubtarget &Subtarget) const {
2286   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2287
2288   // We have to copy the entire va_list struct:
2289   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2290   return DAG.getMemcpy(Op.getOperand(0), Op,
2291                        Op.getOperand(1), Op.getOperand(2),
2292                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2293                        false, MachinePointerInfo(), MachinePointerInfo());
2294 }
2295
2296 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2297                                                   SelectionDAG &DAG) const {
2298   return Op.getOperand(0);
2299 }
2300
2301 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2302                                                 SelectionDAG &DAG) const {
2303   SDValue Chain = Op.getOperand(0);
2304   SDValue Trmp = Op.getOperand(1); // trampoline
2305   SDValue FPtr = Op.getOperand(2); // nested function
2306   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2307   SDLoc dl(Op);
2308
2309   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2310   bool isPPC64 = (PtrVT == MVT::i64);
2311   Type *IntPtrTy =
2312     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2313                                                              *DAG.getContext());
2314
2315   TargetLowering::ArgListTy Args;
2316   TargetLowering::ArgListEntry Entry;
2317
2318   Entry.Ty = IntPtrTy;
2319   Entry.Node = Trmp; Args.push_back(Entry);
2320
2321   // TrampSize == (isPPC64 ? 48 : 40);
2322   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2323                                isPPC64 ? MVT::i64 : MVT::i32);
2324   Args.push_back(Entry);
2325
2326   Entry.Node = FPtr; Args.push_back(Entry);
2327   Entry.Node = Nest; Args.push_back(Entry);
2328
2329   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2330   TargetLowering::CallLoweringInfo CLI(DAG);
2331   CLI.setDebugLoc(dl).setChain(Chain)
2332     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2333                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2334                std::move(Args), 0);
2335
2336   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2337   return CallResult.second;
2338 }
2339
2340 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2341                                         const PPCSubtarget &Subtarget) const {
2342   MachineFunction &MF = DAG.getMachineFunction();
2343   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2344
2345   SDLoc dl(Op);
2346
2347   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2348     // vastart just stores the address of the VarArgsFrameIndex slot into the
2349     // memory location argument.
2350     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2351     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2352     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2353     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2354                         MachinePointerInfo(SV),
2355                         false, false, 0);
2356   }
2357
2358   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2359   // We suppose the given va_list is already allocated.
2360   //
2361   // typedef struct {
2362   //  char gpr;     /* index into the array of 8 GPRs
2363   //                 * stored in the register save area
2364   //                 * gpr=0 corresponds to r3,
2365   //                 * gpr=1 to r4, etc.
2366   //                 */
2367   //  char fpr;     /* index into the array of 8 FPRs
2368   //                 * stored in the register save area
2369   //                 * fpr=0 corresponds to f1,
2370   //                 * fpr=1 to f2, etc.
2371   //                 */
2372   //  char *overflow_arg_area;
2373   //                /* location on stack that holds
2374   //                 * the next overflow argument
2375   //                 */
2376   //  char *reg_save_area;
2377   //               /* where r3:r10 and f1:f8 (if saved)
2378   //                * are stored
2379   //                */
2380   // } va_list[1];
2381
2382
2383   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2384   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2385
2386
2387   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2388
2389   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2390                                             PtrVT);
2391   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2392                                  PtrVT);
2393
2394   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2395   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2396
2397   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2398   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2399
2400   uint64_t FPROffset = 1;
2401   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2402
2403   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2404
2405   // Store first byte : number of int regs
2406   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2407                                          Op.getOperand(1),
2408                                          MachinePointerInfo(SV),
2409                                          MVT::i8, false, false, 0);
2410   uint64_t nextOffset = FPROffset;
2411   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2412                                   ConstFPROffset);
2413
2414   // Store second byte : number of float regs
2415   SDValue secondStore =
2416     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2417                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2418                       false, false, 0);
2419   nextOffset += StackOffset;
2420   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2421
2422   // Store second word : arguments given on stack
2423   SDValue thirdStore =
2424     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2425                  MachinePointerInfo(SV, nextOffset),
2426                  false, false, 0);
2427   nextOffset += FrameOffset;
2428   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2429
2430   // Store third word : arguments given in registers
2431   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2432                       MachinePointerInfo(SV, nextOffset),
2433                       false, false, 0);
2434
2435 }
2436
2437 #include "PPCGenCallingConv.inc"
2438
2439 // Function whose sole purpose is to kill compiler warnings 
2440 // stemming from unused functions included from PPCGenCallingConv.inc.
2441 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2442   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2443 }
2444
2445 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2446                                       CCValAssign::LocInfo &LocInfo,
2447                                       ISD::ArgFlagsTy &ArgFlags,
2448                                       CCState &State) {
2449   return true;
2450 }
2451
2452 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2453                                              MVT &LocVT,
2454                                              CCValAssign::LocInfo &LocInfo,
2455                                              ISD::ArgFlagsTy &ArgFlags,
2456                                              CCState &State) {
2457   static const MCPhysReg ArgRegs[] = {
2458     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2459     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2460   };
2461   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2462
2463   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2464
2465   // Skip one register if the first unallocated register has an even register
2466   // number and there are still argument registers available which have not been
2467   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2468   // need to skip a register if RegNum is odd.
2469   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2470     State.AllocateReg(ArgRegs[RegNum]);
2471   }
2472
2473   // Always return false here, as this function only makes sure that the first
2474   // unallocated register has an odd register number and does not actually
2475   // allocate a register for the current argument.
2476   return false;
2477 }
2478
2479 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2480                                                MVT &LocVT,
2481                                                CCValAssign::LocInfo &LocInfo,
2482                                                ISD::ArgFlagsTy &ArgFlags,
2483                                                CCState &State) {
2484   static const MCPhysReg ArgRegs[] = {
2485     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2486     PPC::F8
2487   };
2488
2489   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2490
2491   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2492
2493   // If there is only one Floating-point register left we need to put both f64
2494   // values of a split ppc_fp128 value on the stack.
2495   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2496     State.AllocateReg(ArgRegs[RegNum]);
2497   }
2498
2499   // Always return false here, as this function only makes sure that the two f64
2500   // values a ppc_fp128 value is split into are both passed in registers or both
2501   // passed on the stack and does not actually allocate a register for the
2502   // current argument.
2503   return false;
2504 }
2505
2506 /// FPR - The set of FP registers that should be allocated for arguments,
2507 /// on Darwin.
2508 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2509                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2510                                 PPC::F11, PPC::F12, PPC::F13};
2511
2512 /// QFPR - The set of QPX registers that should be allocated for arguments.
2513 static const MCPhysReg QFPR[] = {
2514     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2515     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2516
2517 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2518 /// the stack.
2519 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2520                                        unsigned PtrByteSize) {
2521   unsigned ArgSize = ArgVT.getStoreSize();
2522   if (Flags.isByVal())
2523     ArgSize = Flags.getByValSize();
2524
2525   // Round up to multiples of the pointer size, except for array members,
2526   // which are always packed.
2527   if (!Flags.isInConsecutiveRegs())
2528     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2529
2530   return ArgSize;
2531 }
2532
2533 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2534 /// on the stack.
2535 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2536                                             ISD::ArgFlagsTy Flags,
2537                                             unsigned PtrByteSize) {
2538   unsigned Align = PtrByteSize;
2539
2540   // Altivec parameters are padded to a 16 byte boundary.
2541   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2542       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2543       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2544       ArgVT == MVT::v1i128)
2545     Align = 16;
2546   // QPX vector types stored in double-precision are padded to a 32 byte
2547   // boundary.
2548   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2549     Align = 32;
2550
2551   // ByVal parameters are aligned as requested.
2552   if (Flags.isByVal()) {
2553     unsigned BVAlign = Flags.getByValAlign();
2554     if (BVAlign > PtrByteSize) {
2555       if (BVAlign % PtrByteSize != 0)
2556           llvm_unreachable(
2557             "ByVal alignment is not a multiple of the pointer size");
2558
2559       Align = BVAlign;
2560     }
2561   }
2562
2563   // Array members are always packed to their original alignment.
2564   if (Flags.isInConsecutiveRegs()) {
2565     // If the array member was split into multiple registers, the first
2566     // needs to be aligned to the size of the full type.  (Except for
2567     // ppcf128, which is only aligned as its f64 components.)
2568     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2569       Align = OrigVT.getStoreSize();
2570     else
2571       Align = ArgVT.getStoreSize();
2572   }
2573
2574   return Align;
2575 }
2576
2577 /// CalculateStackSlotUsed - Return whether this argument will use its
2578 /// stack slot (instead of being passed in registers).  ArgOffset,
2579 /// AvailableFPRs, and AvailableVRs must hold the current argument
2580 /// position, and will be updated to account for this argument.
2581 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2582                                    ISD::ArgFlagsTy Flags,
2583                                    unsigned PtrByteSize,
2584                                    unsigned LinkageSize,
2585                                    unsigned ParamAreaSize,
2586                                    unsigned &ArgOffset,
2587                                    unsigned &AvailableFPRs,
2588                                    unsigned &AvailableVRs, bool HasQPX) {
2589   bool UseMemory = false;
2590
2591   // Respect alignment of argument on the stack.
2592   unsigned Align =
2593     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2594   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2595   // If there's no space left in the argument save area, we must
2596   // use memory (this check also catches zero-sized arguments).
2597   if (ArgOffset >= LinkageSize + ParamAreaSize)
2598     UseMemory = true;
2599
2600   // Allocate argument on the stack.
2601   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2602   if (Flags.isInConsecutiveRegsLast())
2603     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2604   // If we overran the argument save area, we must use memory
2605   // (this check catches arguments passed partially in memory)
2606   if (ArgOffset > LinkageSize + ParamAreaSize)
2607     UseMemory = true;
2608
2609   // However, if the argument is actually passed in an FPR or a VR,
2610   // we don't use memory after all.
2611   if (!Flags.isByVal()) {
2612     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2613         // QPX registers overlap with the scalar FP registers.
2614         (HasQPX && (ArgVT == MVT::v4f32 ||
2615                     ArgVT == MVT::v4f64 ||
2616                     ArgVT == MVT::v4i1)))
2617       if (AvailableFPRs > 0) {
2618         --AvailableFPRs;
2619         return false;
2620       }
2621     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2622         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2623         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2624         ArgVT == MVT::v1i128)
2625       if (AvailableVRs > 0) {
2626         --AvailableVRs;
2627         return false;
2628       }
2629   }
2630
2631   return UseMemory;
2632 }
2633
2634 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2635 /// ensure minimum alignment required for target.
2636 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2637                                      unsigned NumBytes) {
2638   unsigned TargetAlign = Lowering->getStackAlignment();
2639   unsigned AlignMask = TargetAlign - 1;
2640   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2641   return NumBytes;
2642 }
2643
2644 SDValue
2645 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2646                                         CallingConv::ID CallConv, bool isVarArg,
2647                                         const SmallVectorImpl<ISD::InputArg>
2648                                           &Ins,
2649                                         SDLoc dl, SelectionDAG &DAG,
2650                                         SmallVectorImpl<SDValue> &InVals)
2651                                           const {
2652   if (Subtarget.isSVR4ABI()) {
2653     if (Subtarget.isPPC64())
2654       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2655                                          dl, DAG, InVals);
2656     else
2657       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2658                                          dl, DAG, InVals);
2659   } else {
2660     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2661                                        dl, DAG, InVals);
2662   }
2663 }
2664
2665 SDValue
2666 PPCTargetLowering::LowerFormalArguments_32SVR4(
2667                                       SDValue Chain,
2668                                       CallingConv::ID CallConv, bool isVarArg,
2669                                       const SmallVectorImpl<ISD::InputArg>
2670                                         &Ins,
2671                                       SDLoc dl, SelectionDAG &DAG,
2672                                       SmallVectorImpl<SDValue> &InVals) const {
2673
2674   // 32-bit SVR4 ABI Stack Frame Layout:
2675   //              +-----------------------------------+
2676   //        +-->  |            Back chain             |
2677   //        |     +-----------------------------------+
2678   //        |     | Floating-point register save area |
2679   //        |     +-----------------------------------+
2680   //        |     |    General register save area     |
2681   //        |     +-----------------------------------+
2682   //        |     |          CR save word             |
2683   //        |     +-----------------------------------+
2684   //        |     |         VRSAVE save word          |
2685   //        |     +-----------------------------------+
2686   //        |     |         Alignment padding         |
2687   //        |     +-----------------------------------+
2688   //        |     |     Vector register save area     |
2689   //        |     +-----------------------------------+
2690   //        |     |       Local variable space        |
2691   //        |     +-----------------------------------+
2692   //        |     |        Parameter list area        |
2693   //        |     +-----------------------------------+
2694   //        |     |           LR save word            |
2695   //        |     +-----------------------------------+
2696   // SP-->  +---  |            Back chain             |
2697   //              +-----------------------------------+
2698   //
2699   // Specifications:
2700   //   System V Application Binary Interface PowerPC Processor Supplement
2701   //   AltiVec Technology Programming Interface Manual
2702
2703   MachineFunction &MF = DAG.getMachineFunction();
2704   MachineFrameInfo *MFI = MF.getFrameInfo();
2705   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2706
2707   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2708   // Potential tail calls could cause overwriting of argument stack slots.
2709   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2710                        (CallConv == CallingConv::Fast));
2711   unsigned PtrByteSize = 4;
2712
2713   // Assign locations to all of the incoming arguments.
2714   SmallVector<CCValAssign, 16> ArgLocs;
2715   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2716                  *DAG.getContext());
2717
2718   // Reserve space for the linkage area on the stack.
2719   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2720   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2721
2722   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2723
2724   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2725     CCValAssign &VA = ArgLocs[i];
2726
2727     // Arguments stored in registers.
2728     if (VA.isRegLoc()) {
2729       const TargetRegisterClass *RC;
2730       EVT ValVT = VA.getValVT();
2731
2732       switch (ValVT.getSimpleVT().SimpleTy) {
2733         default:
2734           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2735         case MVT::i1:
2736         case MVT::i32:
2737           RC = &PPC::GPRCRegClass;
2738           break;
2739         case MVT::f32:
2740           if (Subtarget.hasP8Vector())
2741             RC = &PPC::VSSRCRegClass;
2742           else
2743             RC = &PPC::F4RCRegClass;
2744           break;
2745         case MVT::f64:
2746           if (Subtarget.hasVSX())
2747             RC = &PPC::VSFRCRegClass;
2748           else
2749             RC = &PPC::F8RCRegClass;
2750           break;
2751         case MVT::v16i8:
2752         case MVT::v8i16:
2753         case MVT::v4i32:
2754           RC = &PPC::VRRCRegClass;
2755           break;
2756         case MVT::v4f32:
2757           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
2758           break;
2759         case MVT::v2f64:
2760         case MVT::v2i64:
2761           RC = &PPC::VSHRCRegClass;
2762           break;
2763         case MVT::v4f64:
2764           RC = &PPC::QFRCRegClass;
2765           break;
2766         case MVT::v4i1:
2767           RC = &PPC::QBRCRegClass;
2768           break;
2769       }
2770
2771       // Transform the arguments stored in physical registers into virtual ones.
2772       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2773       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2774                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2775
2776       if (ValVT == MVT::i1)
2777         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2778
2779       InVals.push_back(ArgValue);
2780     } else {
2781       // Argument stored in memory.
2782       assert(VA.isMemLoc());
2783
2784       unsigned ArgSize = VA.getLocVT().getStoreSize();
2785       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2786                                       isImmutable);
2787
2788       // Create load nodes to retrieve arguments from the stack.
2789       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2790       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2791                                    MachinePointerInfo(),
2792                                    false, false, false, 0));
2793     }
2794   }
2795
2796   // Assign locations to all of the incoming aggregate by value arguments.
2797   // Aggregates passed by value are stored in the local variable space of the
2798   // caller's stack frame, right above the parameter list area.
2799   SmallVector<CCValAssign, 16> ByValArgLocs;
2800   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2801                       ByValArgLocs, *DAG.getContext());
2802
2803   // Reserve stack space for the allocations in CCInfo.
2804   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2805
2806   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2807
2808   // Area that is at least reserved in the caller of this function.
2809   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2810   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2811
2812   // Set the size that is at least reserved in caller of this function.  Tail
2813   // call optimized function's reserved stack space needs to be aligned so that
2814   // taking the difference between two stack areas will result in an aligned
2815   // stack.
2816   MinReservedArea =
2817       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
2818   FuncInfo->setMinReservedArea(MinReservedArea);
2819
2820   SmallVector<SDValue, 8> MemOps;
2821
2822   // If the function takes variable number of arguments, make a frame index for
2823   // the start of the first vararg value... for expansion of llvm.va_start.
2824   if (isVarArg) {
2825     static const MCPhysReg GPArgRegs[] = {
2826       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2827       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2828     };
2829     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2830
2831     static const MCPhysReg FPArgRegs[] = {
2832       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2833       PPC::F8
2834     };
2835     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2836     if (DisablePPCFloatInVariadic)
2837       NumFPArgRegs = 0;
2838
2839     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
2840     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
2841
2842     // Make room for NumGPArgRegs and NumFPArgRegs.
2843     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2844                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2845
2846     FuncInfo->setVarArgsStackOffset(
2847       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2848                              CCInfo.getNextStackOffset(), true));
2849
2850     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2851     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2852
2853     // The fixed integer arguments of a variadic function are stored to the
2854     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2855     // the result of va_next.
2856     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2857       // Get an existing live-in vreg, or add a new one.
2858       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2859       if (!VReg)
2860         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2861
2862       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2863       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2864                                    MachinePointerInfo(), false, false, 0);
2865       MemOps.push_back(Store);
2866       // Increment the address by four for the next argument to store
2867       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
2868       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2869     }
2870
2871     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2872     // is set.
2873     // The double arguments are stored to the VarArgsFrameIndex
2874     // on the stack.
2875     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2876       // Get an existing live-in vreg, or add a new one.
2877       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2878       if (!VReg)
2879         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2880
2881       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2882       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2883                                    MachinePointerInfo(), false, false, 0);
2884       MemOps.push_back(Store);
2885       // Increment the address by eight for the next argument to store
2886       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
2887                                          PtrVT);
2888       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2889     }
2890   }
2891
2892   if (!MemOps.empty())
2893     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2894
2895   return Chain;
2896 }
2897
2898 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2899 // value to MVT::i64 and then truncate to the correct register size.
2900 SDValue
2901 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2902                                      SelectionDAG &DAG, SDValue ArgVal,
2903                                      SDLoc dl) const {
2904   if (Flags.isSExt())
2905     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2906                          DAG.getValueType(ObjectVT));
2907   else if (Flags.isZExt())
2908     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2909                          DAG.getValueType(ObjectVT));
2910
2911   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2912 }
2913
2914 SDValue
2915 PPCTargetLowering::LowerFormalArguments_64SVR4(
2916                                       SDValue Chain,
2917                                       CallingConv::ID CallConv, bool isVarArg,
2918                                       const SmallVectorImpl<ISD::InputArg>
2919                                         &Ins,
2920                                       SDLoc dl, SelectionDAG &DAG,
2921                                       SmallVectorImpl<SDValue> &InVals) const {
2922   // TODO: add description of PPC stack frame format, or at least some docs.
2923   //
2924   bool isELFv2ABI = Subtarget.isELFv2ABI();
2925   bool isLittleEndian = Subtarget.isLittleEndian();
2926   MachineFunction &MF = DAG.getMachineFunction();
2927   MachineFrameInfo *MFI = MF.getFrameInfo();
2928   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2929
2930   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
2931          "fastcc not supported on varargs functions");
2932
2933   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2934   // Potential tail calls could cause overwriting of argument stack slots.
2935   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2936                        (CallConv == CallingConv::Fast));
2937   unsigned PtrByteSize = 8;
2938   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
2939
2940   static const MCPhysReg GPR[] = {
2941     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2942     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2943   };
2944   static const MCPhysReg VR[] = {
2945     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2946     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2947   };
2948   static const MCPhysReg VSRH[] = {
2949     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2950     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2951   };
2952
2953   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2954   const unsigned Num_FPR_Regs = 13;
2955   const unsigned Num_VR_Regs  = array_lengthof(VR);
2956   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
2957
2958   // Do a first pass over the arguments to determine whether the ABI
2959   // guarantees that our caller has allocated the parameter save area
2960   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2961   // in the ELFv2 ABI, it is true if this is a vararg function or if
2962   // any parameter is located in a stack slot.
2963
2964   bool HasParameterArea = !isELFv2ABI || isVarArg;
2965   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2966   unsigned NumBytes = LinkageSize;
2967   unsigned AvailableFPRs = Num_FPR_Regs;
2968   unsigned AvailableVRs = Num_VR_Regs;
2969   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2970     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2971                                PtrByteSize, LinkageSize, ParamAreaSize,
2972                                NumBytes, AvailableFPRs, AvailableVRs,
2973                                Subtarget.hasQPX()))
2974       HasParameterArea = true;
2975
2976   // Add DAG nodes to load the arguments or copy them out of registers.  On
2977   // entry to a function on PPC, the arguments start after the linkage area,
2978   // although the first ones are often in registers.
2979
2980   unsigned ArgOffset = LinkageSize;
2981   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2982   unsigned &QFPR_idx = FPR_idx;
2983   SmallVector<SDValue, 8> MemOps;
2984   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2985   unsigned CurArgIdx = 0;
2986   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2987     SDValue ArgVal;
2988     bool needsLoad = false;
2989     EVT ObjectVT = Ins[ArgNo].VT;
2990     EVT OrigVT = Ins[ArgNo].ArgVT;
2991     unsigned ObjSize = ObjectVT.getStoreSize();
2992     unsigned ArgSize = ObjSize;
2993     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2994     if (Ins[ArgNo].isOrigArg()) {
2995       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
2996       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
2997     }
2998     // We re-align the argument offset for each argument, except when using the
2999     // fast calling convention, when we need to make sure we do that only when
3000     // we'll actually use a stack slot.
3001     unsigned CurArgOffset, Align;
3002     auto ComputeArgOffset = [&]() {
3003       /* Respect alignment of argument on the stack.  */
3004       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3005       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3006       CurArgOffset = ArgOffset;
3007     };
3008
3009     if (CallConv != CallingConv::Fast) {
3010       ComputeArgOffset();
3011
3012       /* Compute GPR index associated with argument offset.  */
3013       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3014       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3015     }
3016
3017     // FIXME the codegen can be much improved in some cases.
3018     // We do not have to keep everything in memory.
3019     if (Flags.isByVal()) {
3020       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3021
3022       if (CallConv == CallingConv::Fast)
3023         ComputeArgOffset();
3024
3025       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3026       ObjSize = Flags.getByValSize();
3027       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3028       // Empty aggregate parameters do not take up registers.  Examples:
3029       //   struct { } a;
3030       //   union  { } b;
3031       //   int c[0];
3032       // etc.  However, we have to provide a place-holder in InVals, so
3033       // pretend we have an 8-byte item at the current address for that
3034       // purpose.
3035       if (!ObjSize) {
3036         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3037         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3038         InVals.push_back(FIN);
3039         continue;
3040       }
3041
3042       // Create a stack object covering all stack doublewords occupied
3043       // by the argument.  If the argument is (fully or partially) on
3044       // the stack, or if the argument is fully in registers but the
3045       // caller has allocated the parameter save anyway, we can refer
3046       // directly to the caller's stack frame.  Otherwise, create a
3047       // local copy in our own frame.
3048       int FI;
3049       if (HasParameterArea ||
3050           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3051         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
3052       else
3053         FI = MFI->CreateStackObject(ArgSize, Align, false);
3054       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3055
3056       // Handle aggregates smaller than 8 bytes.
3057       if (ObjSize < PtrByteSize) {
3058         // The value of the object is its address, which differs from the
3059         // address of the enclosing doubleword on big-endian systems.
3060         SDValue Arg = FIN;
3061         if (!isLittleEndian) {
3062           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3063           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3064         }
3065         InVals.push_back(Arg);
3066
3067         if (GPR_idx != Num_GPR_Regs) {
3068           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3069           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3070           SDValue Store;
3071
3072           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3073             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3074                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3075             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3076                                       MachinePointerInfo(FuncArg),
3077                                       ObjType, false, false, 0);
3078           } else {
3079             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3080             // store the whole register as-is to the parameter save area
3081             // slot.
3082             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3083                                  MachinePointerInfo(FuncArg),
3084                                  false, false, 0);
3085           }
3086
3087           MemOps.push_back(Store);
3088         }
3089         // Whether we copied from a register or not, advance the offset
3090         // into the parameter save area by a full doubleword.
3091         ArgOffset += PtrByteSize;
3092         continue;
3093       }
3094
3095       // The value of the object is its address, which is the address of
3096       // its first stack doubleword.
3097       InVals.push_back(FIN);
3098
3099       // Store whatever pieces of the object are in registers to memory.
3100       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3101         if (GPR_idx == Num_GPR_Regs)
3102           break;
3103
3104         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3105         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3106         SDValue Addr = FIN;
3107         if (j) {
3108           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3109           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3110         }
3111         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3112                                      MachinePointerInfo(FuncArg, j),
3113                                      false, false, 0);
3114         MemOps.push_back(Store);
3115         ++GPR_idx;
3116       }
3117       ArgOffset += ArgSize;
3118       continue;
3119     }
3120
3121     switch (ObjectVT.getSimpleVT().SimpleTy) {
3122     default: llvm_unreachable("Unhandled argument type!");
3123     case MVT::i1:
3124     case MVT::i32:
3125     case MVT::i64:
3126       // These can be scalar arguments or elements of an integer array type
3127       // passed directly.  Clang may use those instead of "byval" aggregate
3128       // types to avoid forcing arguments to memory unnecessarily.
3129       if (GPR_idx != Num_GPR_Regs) {
3130         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3131         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3132
3133         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3134           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3135           // value to MVT::i64 and then truncate to the correct register size.
3136           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3137       } else {
3138         if (CallConv == CallingConv::Fast)
3139           ComputeArgOffset();
3140
3141         needsLoad = true;
3142         ArgSize = PtrByteSize;
3143       }
3144       if (CallConv != CallingConv::Fast || needsLoad)
3145         ArgOffset += 8;
3146       break;
3147
3148     case MVT::f32:
3149     case MVT::f64:
3150       // These can be scalar arguments or elements of a float array type
3151       // passed directly.  The latter are used to implement ELFv2 homogenous
3152       // float aggregates.
3153       if (FPR_idx != Num_FPR_Regs) {
3154         unsigned VReg;
3155
3156         if (ObjectVT == MVT::f32)
3157           VReg = MF.addLiveIn(FPR[FPR_idx],
3158                               Subtarget.hasP8Vector()
3159                                   ? &PPC::VSSRCRegClass
3160                                   : &PPC::F4RCRegClass);
3161         else
3162           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3163                                                 ? &PPC::VSFRCRegClass
3164                                                 : &PPC::F8RCRegClass);
3165
3166         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3167         ++FPR_idx;
3168       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3169         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3170         // once we support fp <-> gpr moves.
3171
3172         // This can only ever happen in the presence of f32 array types,
3173         // since otherwise we never run out of FPRs before running out
3174         // of GPRs.
3175         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3176         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3177
3178         if (ObjectVT == MVT::f32) {
3179           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3180             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3181                                  DAG.getConstant(32, dl, MVT::i32));
3182           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3183         }
3184
3185         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3186       } else {
3187         if (CallConv == CallingConv::Fast)
3188           ComputeArgOffset();
3189
3190         needsLoad = true;
3191       }
3192
3193       // When passing an array of floats, the array occupies consecutive
3194       // space in the argument area; only round up to the next doubleword
3195       // at the end of the array.  Otherwise, each float takes 8 bytes.
3196       if (CallConv != CallingConv::Fast || needsLoad) {
3197         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3198         ArgOffset += ArgSize;
3199         if (Flags.isInConsecutiveRegsLast())
3200           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3201       }
3202       break;
3203     case MVT::v4f32:
3204     case MVT::v4i32:
3205     case MVT::v8i16:
3206     case MVT::v16i8:
3207     case MVT::v2f64:
3208     case MVT::v2i64:
3209     case MVT::v1i128:
3210       if (!Subtarget.hasQPX()) {
3211       // These can be scalar arguments or elements of a vector array type
3212       // passed directly.  The latter are used to implement ELFv2 homogenous
3213       // vector aggregates.
3214       if (VR_idx != Num_VR_Regs) {
3215         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
3216                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
3217                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3218         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3219         ++VR_idx;
3220       } else {
3221         if (CallConv == CallingConv::Fast)
3222           ComputeArgOffset();
3223
3224         needsLoad = true;
3225       }
3226       if (CallConv != CallingConv::Fast || needsLoad)
3227         ArgOffset += 16;
3228       break;
3229       } // not QPX
3230
3231       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3232              "Invalid QPX parameter type");
3233       /* fall through */
3234
3235     case MVT::v4f64:
3236     case MVT::v4i1:
3237       // QPX vectors are treated like their scalar floating-point subregisters
3238       // (except that they're larger).
3239       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3240       if (QFPR_idx != Num_QFPR_Regs) {
3241         const TargetRegisterClass *RC;
3242         switch (ObjectVT.getSimpleVT().SimpleTy) {
3243         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3244         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3245         default:         RC = &PPC::QBRCRegClass; break;
3246         }
3247
3248         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3249         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3250         ++QFPR_idx;
3251       } else {
3252         if (CallConv == CallingConv::Fast)
3253           ComputeArgOffset();
3254         needsLoad = true;
3255       }
3256       if (CallConv != CallingConv::Fast || needsLoad)
3257         ArgOffset += Sz;
3258       break;
3259     }
3260
3261     // We need to load the argument to a virtual register if we determined
3262     // above that we ran out of physical registers of the appropriate type.
3263     if (needsLoad) {
3264       if (ObjSize < ArgSize && !isLittleEndian)
3265         CurArgOffset += ArgSize - ObjSize;
3266       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3267       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3268       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3269                            false, false, false, 0);
3270     }
3271
3272     InVals.push_back(ArgVal);
3273   }
3274
3275   // Area that is at least reserved in the caller of this function.
3276   unsigned MinReservedArea;
3277   if (HasParameterArea)
3278     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3279   else
3280     MinReservedArea = LinkageSize;
3281
3282   // Set the size that is at least reserved in caller of this function.  Tail
3283   // call optimized functions' reserved stack space needs to be aligned so that
3284   // taking the difference between two stack areas will result in an aligned
3285   // stack.
3286   MinReservedArea =
3287       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3288   FuncInfo->setMinReservedArea(MinReservedArea);
3289
3290   // If the function takes variable number of arguments, make a frame index for
3291   // the start of the first vararg value... for expansion of llvm.va_start.
3292   if (isVarArg) {
3293     int Depth = ArgOffset;
3294
3295     FuncInfo->setVarArgsFrameIndex(
3296       MFI->CreateFixedObject(PtrByteSize, Depth, true));
3297     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3298
3299     // If this function is vararg, store any remaining integer argument regs
3300     // to their spots on the stack so that they may be loaded by deferencing the
3301     // result of va_next.
3302     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3303          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3304       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3305       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3306       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3307                                    MachinePointerInfo(), false, false, 0);
3308       MemOps.push_back(Store);
3309       // Increment the address by four for the next argument to store
3310       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3311       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3312     }
3313   }
3314
3315   if (!MemOps.empty())
3316     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3317
3318   return Chain;
3319 }
3320
3321 SDValue
3322 PPCTargetLowering::LowerFormalArguments_Darwin(
3323                                       SDValue Chain,
3324                                       CallingConv::ID CallConv, bool isVarArg,
3325                                       const SmallVectorImpl<ISD::InputArg>
3326                                         &Ins,
3327                                       SDLoc dl, SelectionDAG &DAG,
3328                                       SmallVectorImpl<SDValue> &InVals) const {
3329   // TODO: add description of PPC stack frame format, or at least some docs.
3330   //
3331   MachineFunction &MF = DAG.getMachineFunction();
3332   MachineFrameInfo *MFI = MF.getFrameInfo();
3333   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3334
3335   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3336   bool isPPC64 = PtrVT == MVT::i64;
3337   // Potential tail calls could cause overwriting of argument stack slots.
3338   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3339                        (CallConv == CallingConv::Fast));
3340   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3341   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3342   unsigned ArgOffset = LinkageSize;
3343   // Area that is at least reserved in caller of this function.
3344   unsigned MinReservedArea = ArgOffset;
3345
3346   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3347     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3348     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3349   };
3350   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3351     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3352     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3353   };
3354   static const MCPhysReg VR[] = {
3355     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3356     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3357   };
3358
3359   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3360   const unsigned Num_FPR_Regs = 13;
3361   const unsigned Num_VR_Regs  = array_lengthof( VR);
3362
3363   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3364
3365   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3366
3367   // In 32-bit non-varargs functions, the stack space for vectors is after the
3368   // stack space for non-vectors.  We do not use this space unless we have
3369   // too many vectors to fit in registers, something that only occurs in
3370   // constructed examples:), but we have to walk the arglist to figure
3371   // that out...for the pathological case, compute VecArgOffset as the
3372   // start of the vector parameter area.  Computing VecArgOffset is the
3373   // entire point of the following loop.
3374   unsigned VecArgOffset = ArgOffset;
3375   if (!isVarArg && !isPPC64) {
3376     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3377          ++ArgNo) {
3378       EVT ObjectVT = Ins[ArgNo].VT;
3379       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3380
3381       if (Flags.isByVal()) {
3382         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3383         unsigned ObjSize = Flags.getByValSize();
3384         unsigned ArgSize =
3385                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3386         VecArgOffset += ArgSize;
3387         continue;
3388       }
3389
3390       switch(ObjectVT.getSimpleVT().SimpleTy) {
3391       default: llvm_unreachable("Unhandled argument type!");
3392       case MVT::i1:
3393       case MVT::i32:
3394       case MVT::f32:
3395         VecArgOffset += 4;
3396         break;
3397       case MVT::i64:  // PPC64
3398       case MVT::f64:
3399         // FIXME: We are guaranteed to be !isPPC64 at this point.
3400         // Does MVT::i64 apply?
3401         VecArgOffset += 8;
3402         break;
3403       case MVT::v4f32:
3404       case MVT::v4i32:
3405       case MVT::v8i16:
3406       case MVT::v16i8:
3407         // Nothing to do, we're only looking at Nonvector args here.
3408         break;
3409       }
3410     }
3411   }
3412   // We've found where the vector parameter area in memory is.  Skip the
3413   // first 12 parameters; these don't use that memory.
3414   VecArgOffset = ((VecArgOffset+15)/16)*16;
3415   VecArgOffset += 12*16;
3416
3417   // Add DAG nodes to load the arguments or copy them out of registers.  On
3418   // entry to a function on PPC, the arguments start after the linkage area,
3419   // although the first ones are often in registers.
3420
3421   SmallVector<SDValue, 8> MemOps;
3422   unsigned nAltivecParamsAtEnd = 0;
3423   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3424   unsigned CurArgIdx = 0;
3425   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3426     SDValue ArgVal;
3427     bool needsLoad = false;
3428     EVT ObjectVT = Ins[ArgNo].VT;
3429     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3430     unsigned ArgSize = ObjSize;
3431     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3432     if (Ins[ArgNo].isOrigArg()) {
3433       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3434       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3435     }
3436     unsigned CurArgOffset = ArgOffset;
3437
3438     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3439     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3440         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3441       if (isVarArg || isPPC64) {
3442         MinReservedArea = ((MinReservedArea+15)/16)*16;
3443         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3444                                                   Flags,
3445                                                   PtrByteSize);
3446       } else  nAltivecParamsAtEnd++;
3447     } else
3448       // Calculate min reserved area.
3449       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3450                                                 Flags,
3451                                                 PtrByteSize);
3452
3453     // FIXME the codegen can be much improved in some cases.
3454     // We do not have to keep everything in memory.
3455     if (Flags.isByVal()) {
3456       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3457
3458       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3459       ObjSize = Flags.getByValSize();
3460       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3461       // Objects of size 1 and 2 are right justified, everything else is
3462       // left justified.  This means the memory address is adjusted forwards.
3463       if (ObjSize==1 || ObjSize==2) {
3464         CurArgOffset = CurArgOffset + (4 - ObjSize);
3465       }
3466       // The value of the object is its address.
3467       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3468       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3469       InVals.push_back(FIN);
3470       if (ObjSize==1 || ObjSize==2) {
3471         if (GPR_idx != Num_GPR_Regs) {
3472           unsigned VReg;
3473           if (isPPC64)
3474             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3475           else
3476             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3477           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3478           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3479           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3480                                             MachinePointerInfo(FuncArg),
3481                                             ObjType, false, false, 0);
3482           MemOps.push_back(Store);
3483           ++GPR_idx;
3484         }
3485
3486         ArgOffset += PtrByteSize;
3487
3488         continue;
3489       }
3490       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3491         // Store whatever pieces of the object are in registers
3492         // to memory.  ArgOffset will be the address of the beginning
3493         // of the object.
3494         if (GPR_idx != Num_GPR_Regs) {
3495           unsigned VReg;
3496           if (isPPC64)
3497             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3498           else
3499             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3500           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3501           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3502           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3503           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3504                                        MachinePointerInfo(FuncArg, j),
3505                                        false, false, 0);
3506           MemOps.push_back(Store);
3507           ++GPR_idx;
3508           ArgOffset += PtrByteSize;
3509         } else {
3510           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3511           break;
3512         }
3513       }
3514       continue;
3515     }
3516
3517     switch (ObjectVT.getSimpleVT().SimpleTy) {
3518     default: llvm_unreachable("Unhandled argument type!");
3519     case MVT::i1:
3520     case MVT::i32:
3521       if (!isPPC64) {
3522         if (GPR_idx != Num_GPR_Regs) {
3523           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3524           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3525
3526           if (ObjectVT == MVT::i1)
3527             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3528
3529           ++GPR_idx;
3530         } else {
3531           needsLoad = true;
3532           ArgSize = PtrByteSize;
3533         }
3534         // All int arguments reserve stack space in the Darwin ABI.
3535         ArgOffset += PtrByteSize;
3536         break;
3537       }
3538       // FALLTHROUGH
3539     case MVT::i64:  // PPC64
3540       if (GPR_idx != Num_GPR_Regs) {
3541         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3542         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3543
3544         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3545           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3546           // value to MVT::i64 and then truncate to the correct register size.
3547           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3548
3549         ++GPR_idx;
3550       } else {
3551         needsLoad = true;
3552         ArgSize = PtrByteSize;
3553       }
3554       // All int arguments reserve stack space in the Darwin ABI.
3555       ArgOffset += 8;
3556       break;
3557
3558     case MVT::f32:
3559     case MVT::f64:
3560       // Every 4 bytes of argument space consumes one of the GPRs available for
3561       // argument passing.
3562       if (GPR_idx != Num_GPR_Regs) {
3563         ++GPR_idx;
3564         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3565           ++GPR_idx;
3566       }
3567       if (FPR_idx != Num_FPR_Regs) {
3568         unsigned VReg;
3569
3570         if (ObjectVT == MVT::f32)
3571           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3572         else
3573           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3574
3575         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3576         ++FPR_idx;
3577       } else {
3578         needsLoad = true;
3579       }
3580
3581       // All FP arguments reserve stack space in the Darwin ABI.
3582       ArgOffset += isPPC64 ? 8 : ObjSize;
3583       break;
3584     case MVT::v4f32:
3585     case MVT::v4i32:
3586     case MVT::v8i16:
3587     case MVT::v16i8:
3588       // Note that vector arguments in registers don't reserve stack space,
3589       // except in varargs functions.
3590       if (VR_idx != Num_VR_Regs) {
3591         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3592         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3593         if (isVarArg) {
3594           while ((ArgOffset % 16) != 0) {
3595             ArgOffset += PtrByteSize;
3596             if (GPR_idx != Num_GPR_Regs)
3597               GPR_idx++;
3598           }
3599           ArgOffset += 16;
3600           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3601         }
3602         ++VR_idx;
3603       } else {
3604         if (!isVarArg && !isPPC64) {
3605           // Vectors go after all the nonvectors.
3606           CurArgOffset = VecArgOffset;
3607           VecArgOffset += 16;
3608         } else {
3609           // Vectors are aligned.
3610           ArgOffset = ((ArgOffset+15)/16)*16;
3611           CurArgOffset = ArgOffset;
3612           ArgOffset += 16;
3613         }
3614         needsLoad = true;
3615       }
3616       break;
3617     }
3618
3619     // We need to load the argument to a virtual register if we determined above
3620     // that we ran out of physical registers of the appropriate type.
3621     if (needsLoad) {
3622       int FI = MFI->CreateFixedObject(ObjSize,
3623                                       CurArgOffset + (ArgSize - ObjSize),
3624                                       isImmutable);
3625       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3626       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3627                            false, false, false, 0);
3628     }
3629
3630     InVals.push_back(ArgVal);
3631   }
3632
3633   // Allow for Altivec parameters at the end, if needed.
3634   if (nAltivecParamsAtEnd) {
3635     MinReservedArea = ((MinReservedArea+15)/16)*16;
3636     MinReservedArea += 16*nAltivecParamsAtEnd;
3637   }
3638
3639   // Area that is at least reserved in the caller of this function.
3640   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3641
3642   // Set the size that is at least reserved in caller of this function.  Tail
3643   // call optimized functions' reserved stack space needs to be aligned so that
3644   // taking the difference between two stack areas will result in an aligned
3645   // stack.
3646   MinReservedArea =
3647       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3648   FuncInfo->setMinReservedArea(MinReservedArea);
3649
3650   // If the function takes variable number of arguments, make a frame index for
3651   // the start of the first vararg value... for expansion of llvm.va_start.
3652   if (isVarArg) {
3653     int Depth = ArgOffset;
3654
3655     FuncInfo->setVarArgsFrameIndex(
3656       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3657                              Depth, true));
3658     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3659
3660     // If this function is vararg, store any remaining integer argument regs
3661     // to their spots on the stack so that they may be loaded by deferencing the
3662     // result of va_next.
3663     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3664       unsigned VReg;
3665
3666       if (isPPC64)
3667         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3668       else
3669         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3670
3671       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3672       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3673                                    MachinePointerInfo(), false, false, 0);
3674       MemOps.push_back(Store);
3675       // Increment the address by four for the next argument to store
3676       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3677       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3678     }
3679   }
3680
3681   if (!MemOps.empty())
3682     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3683
3684   return Chain;
3685 }
3686
3687 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3688 /// adjusted to accommodate the arguments for the tailcall.
3689 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3690                                    unsigned ParamSize) {
3691
3692   if (!isTailCall) return 0;
3693
3694   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3695   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3696   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3697   // Remember only if the new adjustement is bigger.
3698   if (SPDiff < FI->getTailCallSPDelta())
3699     FI->setTailCallSPDelta(SPDiff);
3700
3701   return SPDiff;
3702 }
3703
3704 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3705 /// for tail call optimization. Targets which want to do tail call
3706 /// optimization should implement this function.
3707 bool
3708 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3709                                                      CallingConv::ID CalleeCC,
3710                                                      bool isVarArg,
3711                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3712                                                      SelectionDAG& DAG) const {
3713   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3714     return false;
3715
3716   // Variable argument functions are not supported.
3717   if (isVarArg)
3718     return false;
3719
3720   MachineFunction &MF = DAG.getMachineFunction();
3721   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3722   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3723     // Functions containing by val parameters are not supported.
3724     for (unsigned i = 0; i != Ins.size(); i++) {
3725        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3726        if (Flags.isByVal()) return false;
3727     }
3728
3729     // Non-PIC/GOT tail calls are supported.
3730     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3731       return true;
3732
3733     // At the moment we can only do local tail calls (in same module, hidden
3734     // or protected) if we are generating PIC.
3735     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3736       return G->getGlobal()->hasHiddenVisibility()
3737           || G->getGlobal()->hasProtectedVisibility();
3738   }
3739
3740   return false;
3741 }
3742
3743 /// isCallCompatibleAddress - Return the immediate to use if the specified
3744 /// 32-bit value is representable in the immediate field of a BxA instruction.
3745 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3746   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3747   if (!C) return nullptr;
3748
3749   int Addr = C->getZExtValue();
3750   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3751       SignExtend32<26>(Addr) != Addr)
3752     return nullptr;  // Top 6 bits have to be sext of immediate.
3753
3754   return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op),
3755                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3756 }
3757
3758 namespace {
3759
3760 struct TailCallArgumentInfo {
3761   SDValue Arg;
3762   SDValue FrameIdxOp;
3763   int       FrameIdx;
3764
3765   TailCallArgumentInfo() : FrameIdx(0) {}
3766 };
3767
3768 }
3769
3770 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3771 static void
3772 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3773                                            SDValue Chain,
3774                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3775                    SmallVectorImpl<SDValue> &MemOpChains,
3776                    SDLoc dl) {
3777   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3778     SDValue Arg = TailCallArgs[i].Arg;
3779     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3780     int FI = TailCallArgs[i].FrameIdx;
3781     // Store relative to framepointer.
3782     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3783                                        MachinePointerInfo::getFixedStack(FI),
3784                                        false, false, 0));
3785   }
3786 }
3787
3788 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3789 /// the appropriate stack slot for the tail call optimized function call.
3790 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3791                                                MachineFunction &MF,
3792                                                SDValue Chain,
3793                                                SDValue OldRetAddr,
3794                                                SDValue OldFP,
3795                                                int SPDiff,
3796                                                bool isPPC64,
3797                                                bool isDarwinABI,
3798                                                SDLoc dl) {
3799   if (SPDiff) {
3800     // Calculate the new stack slot for the return address.
3801     int SlotSize = isPPC64 ? 8 : 4;
3802     const PPCFrameLowering *FL =
3803         MF.getSubtarget<PPCSubtarget>().getFrameLowering();
3804     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
3805     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3806                                                           NewRetAddrLoc, true);
3807     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3808     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3809     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3810                          MachinePointerInfo::getFixedStack(NewRetAddr),
3811                          false, false, 0);
3812
3813     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3814     // slot as the FP is never overwritten.
3815     if (isDarwinABI) {
3816       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
3817       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3818                                                           true);
3819       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3820       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3821                            MachinePointerInfo::getFixedStack(NewFPIdx),
3822                            false, false, 0);
3823     }
3824   }
3825   return Chain;
3826 }
3827
3828 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3829 /// the position of the argument.
3830 static void
3831 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3832                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3833                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3834   int Offset = ArgOffset + SPDiff;
3835   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3836   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3837   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3838   SDValue FIN = DAG.getFrameIndex(FI, VT);
3839   TailCallArgumentInfo Info;
3840   Info.Arg = Arg;
3841   Info.FrameIdxOp = FIN;
3842   Info.FrameIdx = FI;
3843   TailCallArguments.push_back(Info);
3844 }
3845
3846 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3847 /// stack slot. Returns the chain as result and the loaded frame pointers in
3848 /// LROpOut/FPOpout. Used when tail calling.
3849 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3850                                                         int SPDiff,
3851                                                         SDValue Chain,
3852                                                         SDValue &LROpOut,
3853                                                         SDValue &FPOpOut,
3854                                                         bool isDarwinABI,
3855                                                         SDLoc dl) const {
3856   if (SPDiff) {
3857     // Load the LR and FP stack slot for later adjusting.
3858     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3859     LROpOut = getReturnAddrFrameIndex(DAG);
3860     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3861                           false, false, false, 0);
3862     Chain = SDValue(LROpOut.getNode(), 1);
3863
3864     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3865     // slot as the FP is never overwritten.
3866     if (isDarwinABI) {
3867       FPOpOut = getFramePointerFrameIndex(DAG);
3868       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3869                             false, false, false, 0);
3870       Chain = SDValue(FPOpOut.getNode(), 1);
3871     }
3872   }
3873   return Chain;
3874 }
3875
3876 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3877 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3878 /// specified by the specific parameter attribute. The copy will be passed as
3879 /// a byval function parameter.
3880 /// Sometimes what we are copying is the end of a larger object, the part that
3881 /// does not fit in registers.
3882 static SDValue
3883 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3884                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3885                           SDLoc dl) {
3886   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
3887   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3888                        false, false, false, MachinePointerInfo(),
3889                        MachinePointerInfo());
3890 }
3891
3892 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3893 /// tail calls.
3894 static void
3895 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3896                  SDValue Arg, SDValue PtrOff, int SPDiff,
3897                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3898                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3899                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3900                  SDLoc dl) {
3901   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3902   if (!isTailCall) {
3903     if (isVector) {
3904       SDValue StackPtr;
3905       if (isPPC64)
3906         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3907       else
3908         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3909       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3910                            DAG.getConstant(ArgOffset, dl, PtrVT));
3911     }
3912     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3913                                        MachinePointerInfo(), false, false, 0));
3914   // Calculate and remember argument location.
3915   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3916                                   TailCallArguments);
3917 }
3918
3919 static
3920 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3921                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3922                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3923                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3924   MachineFunction &MF = DAG.getMachineFunction();
3925
3926   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3927   // might overwrite each other in case of tail call optimization.
3928   SmallVector<SDValue, 8> MemOpChains2;
3929   // Do not flag preceding copytoreg stuff together with the following stuff.
3930   InFlag = SDValue();
3931   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3932                                     MemOpChains2, dl);
3933   if (!MemOpChains2.empty())
3934     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3935
3936   // Store the return address to the appropriate stack slot.
3937   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3938                                         isPPC64, isDarwinABI, dl);
3939
3940   // Emit callseq_end just before tailcall node.
3941   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
3942                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3943   InFlag = Chain.getValue(1);
3944 }
3945
3946 // Is this global address that of a function that can be called by name? (as
3947 // opposed to something that must hold a descriptor for an indirect call).
3948 static bool isFunctionGlobalAddress(SDValue Callee) {
3949   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3950     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3951         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3952       return false;
3953
3954     return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3955   }
3956
3957   return false;
3958 }
3959
3960 static
3961 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3962                      SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff,
3963                      bool isTailCall, bool IsPatchPoint,
3964                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3965                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3966                      ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
3967
3968   bool isPPC64 = Subtarget.isPPC64();
3969   bool isSVR4ABI = Subtarget.isSVR4ABI();
3970   bool isELFv2ABI = Subtarget.isELFv2ABI();
3971
3972   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3973   NodeTys.push_back(MVT::Other);   // Returns a chain
3974   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3975
3976   unsigned CallOpc = PPCISD::CALL;
3977
3978   bool needIndirectCall = true;
3979   if (!isSVR4ABI || !isPPC64)
3980     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3981       // If this is an absolute destination address, use the munged value.
3982       Callee = SDValue(Dest, 0);
3983       needIndirectCall = false;
3984     }
3985
3986   if (isFunctionGlobalAddress(Callee)) {
3987     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3988     // A call to a TLS address is actually an indirect call to a
3989     // thread-specific pointer.
3990     unsigned OpFlags = 0;
3991     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3992          (Subtarget.getTargetTriple().isMacOSX() &&
3993           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3994          (G->getGlobal()->isDeclaration() ||
3995           G->getGlobal()->isWeakForLinker())) ||
3996         (Subtarget.isTargetELF() && !isPPC64 &&
3997          !G->getGlobal()->hasLocalLinkage() &&
3998          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3999       // PC-relative references to external symbols should go through $stub,
4000       // unless we're building with the leopard linker or later, which
4001       // automatically synthesizes these stubs.
4002       OpFlags = PPCII::MO_PLT_OR_STUB;
4003     }
4004
4005     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4006     // every direct call is) turn it into a TargetGlobalAddress /
4007     // TargetExternalSymbol node so that legalize doesn't hack it.
4008     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4009                                         Callee.getValueType(), 0, OpFlags);
4010     needIndirectCall = false;
4011   }
4012
4013   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4014     unsigned char OpFlags = 0;
4015
4016     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
4017          (Subtarget.getTargetTriple().isMacOSX() &&
4018           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
4019         (Subtarget.isTargetELF() && !isPPC64 &&
4020          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
4021       // PC-relative references to external symbols should go through $stub,
4022       // unless we're building with the leopard linker or later, which
4023       // automatically synthesizes these stubs.
4024       OpFlags = PPCII::MO_PLT_OR_STUB;
4025     }
4026
4027     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4028                                          OpFlags);
4029     needIndirectCall = false;
4030   }
4031
4032   if (IsPatchPoint) {
4033     // We'll form an invalid direct call when lowering a patchpoint; the full
4034     // sequence for an indirect call is complicated, and many of the
4035     // instructions introduced might have side effects (and, thus, can't be
4036     // removed later). The call itself will be removed as soon as the
4037     // argument/return lowering is complete, so the fact that it has the wrong
4038     // kind of operands should not really matter.
4039     needIndirectCall = false;
4040   }
4041
4042   if (needIndirectCall) {
4043     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4044     // to do the call, we can't use PPCISD::CALL.
4045     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4046
4047     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4048       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4049       // entry point, but to the function descriptor (the function entry point
4050       // address is part of the function descriptor though).
4051       // The function descriptor is a three doubleword structure with the
4052       // following fields: function entry point, TOC base address and
4053       // environment pointer.
4054       // Thus for a call through a function pointer, the following actions need
4055       // to be performed:
4056       //   1. Save the TOC of the caller in the TOC save area of its stack
4057       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4058       //   2. Load the address of the function entry point from the function
4059       //      descriptor.
4060       //   3. Load the TOC of the callee from the function descriptor into r2.
4061       //   4. Load the environment pointer from the function descriptor into
4062       //      r11.
4063       //   5. Branch to the function entry point address.
4064       //   6. On return of the callee, the TOC of the caller needs to be
4065       //      restored (this is done in FinishCall()).
4066       //
4067       // The loads are scheduled at the beginning of the call sequence, and the
4068       // register copies are flagged together to ensure that no other
4069       // operations can be scheduled in between. E.g. without flagging the
4070       // copies together, a TOC access in the caller could be scheduled between
4071       // the assignment of the callee TOC and the branch to the callee, which
4072       // results in the TOC access going through the TOC of the callee instead
4073       // of going through the TOC of the caller, which leads to incorrect code.
4074
4075       // Load the address of the function entry point from the function
4076       // descriptor.
4077       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4078       if (LDChain.getValueType() == MVT::Glue)
4079         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4080
4081       bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors();
4082
4083       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4084       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4085                                         false, false, LoadsInv, 8);
4086
4087       // Load environment pointer into r11.
4088       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4089       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4090       SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr,
4091                                        MPI.getWithOffset(16), false, false,
4092                                        LoadsInv, 8);
4093
4094       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4095       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4096       SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC,
4097                                    MPI.getWithOffset(8), false, false,
4098                                    LoadsInv, 8);
4099
4100       setUsesTOCBasePtr(DAG);
4101       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4102                                         InFlag);
4103       Chain = TOCVal.getValue(0);
4104       InFlag = TOCVal.getValue(1);
4105
4106       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4107                                         InFlag);
4108
4109       Chain = EnvVal.getValue(0);
4110       InFlag = EnvVal.getValue(1);
4111
4112       MTCTROps[0] = Chain;
4113       MTCTROps[1] = LoadFuncPtr;
4114       MTCTROps[2] = InFlag;
4115     }
4116
4117     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4118                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4119     InFlag = Chain.getValue(1);
4120
4121     NodeTys.clear();
4122     NodeTys.push_back(MVT::Other);
4123     NodeTys.push_back(MVT::Glue);
4124     Ops.push_back(Chain);
4125     CallOpc = PPCISD::BCTRL;
4126     Callee.setNode(nullptr);
4127     // Add use of X11 (holding environment pointer)
4128     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
4129       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4130     // Add CTR register as callee so a bctr can be emitted later.
4131     if (isTailCall)
4132       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4133   }
4134
4135   // If this is a direct call, pass the chain and the callee.
4136   if (Callee.getNode()) {
4137     Ops.push_back(Chain);
4138     Ops.push_back(Callee);
4139   }
4140   // If this is a tail call add stack pointer delta.
4141   if (isTailCall)
4142     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4143
4144   // Add argument registers to the end of the list so that they are known live
4145   // into the call.
4146   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4147     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4148                                   RegsToPass[i].second.getValueType()));
4149
4150   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4151   // into the call.
4152   if (isSVR4ABI && isPPC64 && !IsPatchPoint) {
4153     setUsesTOCBasePtr(DAG);
4154     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4155   }
4156
4157   return CallOpc;
4158 }
4159
4160 static
4161 bool isLocalCall(const SDValue &Callee)
4162 {
4163   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4164     return !G->getGlobal()->isDeclaration() &&
4165            !G->getGlobal()->isWeakForLinker();
4166   return false;
4167 }
4168
4169 SDValue
4170 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
4171                                    CallingConv::ID CallConv, bool isVarArg,
4172                                    const SmallVectorImpl<ISD::InputArg> &Ins,
4173                                    SDLoc dl, SelectionDAG &DAG,
4174                                    SmallVectorImpl<SDValue> &InVals) const {
4175
4176   SmallVector<CCValAssign, 16> RVLocs;
4177   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4178                     *DAG.getContext());
4179   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4180
4181   // Copy all of the result registers out of their specified physreg.
4182   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4183     CCValAssign &VA = RVLocs[i];
4184     assert(VA.isRegLoc() && "Can only return in registers!");
4185
4186     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4187                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4188     Chain = Val.getValue(1);
4189     InFlag = Val.getValue(2);
4190
4191     switch (VA.getLocInfo()) {
4192     default: llvm_unreachable("Unknown loc info!");
4193     case CCValAssign::Full: break;
4194     case CCValAssign::AExt:
4195       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4196       break;
4197     case CCValAssign::ZExt:
4198       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4199                         DAG.getValueType(VA.getValVT()));
4200       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4201       break;
4202     case CCValAssign::SExt:
4203       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4204                         DAG.getValueType(VA.getValVT()));
4205       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4206       break;
4207     }
4208
4209     InVals.push_back(Val);
4210   }
4211
4212   return Chain;
4213 }
4214
4215 SDValue
4216 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
4217                               bool isTailCall, bool isVarArg, bool IsPatchPoint,
4218                               SelectionDAG &DAG,
4219                               SmallVector<std::pair<unsigned, SDValue>, 8>
4220                                 &RegsToPass,
4221                               SDValue InFlag, SDValue Chain,
4222                               SDValue CallSeqStart, SDValue &Callee,
4223                               int SPDiff, unsigned NumBytes,
4224                               const SmallVectorImpl<ISD::InputArg> &Ins,
4225                               SmallVectorImpl<SDValue> &InVals,
4226                               ImmutableCallSite *CS) const {
4227
4228   std::vector<EVT> NodeTys;
4229   SmallVector<SDValue, 8> Ops;
4230   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4231                                  SPDiff, isTailCall, IsPatchPoint, RegsToPass,
4232                                  Ops, NodeTys, CS, Subtarget);
4233
4234   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4235   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4236     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4237
4238   // When performing tail call optimization the callee pops its arguments off
4239   // the stack. Account for this here so these bytes can be pushed back on in
4240   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4241   int BytesCalleePops =
4242     (CallConv == CallingConv::Fast &&
4243      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4244
4245   // Add a register mask operand representing the call-preserved registers.
4246   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4247   const uint32_t *Mask =
4248       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4249   assert(Mask && "Missing call preserved mask for calling convention");
4250   Ops.push_back(DAG.getRegisterMask(Mask));
4251
4252   if (InFlag.getNode())
4253     Ops.push_back(InFlag);
4254
4255   // Emit tail call.
4256   if (isTailCall) {
4257     assert(((Callee.getOpcode() == ISD::Register &&
4258              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4259             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4260             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4261             isa<ConstantSDNode>(Callee)) &&
4262     "Expecting an global address, external symbol, absolute value or register");
4263
4264     DAG.getMachineFunction().getFrameInfo()->setHasTailCall();
4265     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4266   }
4267
4268   // Add a NOP immediately after the branch instruction when using the 64-bit
4269   // SVR4 ABI. At link time, if caller and callee are in a different module and
4270   // thus have a different TOC, the call will be replaced with a call to a stub
4271   // function which saves the current TOC, loads the TOC of the callee and
4272   // branches to the callee. The NOP will be replaced with a load instruction
4273   // which restores the TOC of the caller from the TOC save slot of the current
4274   // stack frame. If caller and callee belong to the same module (and have the
4275   // same TOC), the NOP will remain unchanged.
4276
4277   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4278       !IsPatchPoint) {
4279     if (CallOpc == PPCISD::BCTRL) {
4280       // This is a call through a function pointer.
4281       // Restore the caller TOC from the save area into R2.
4282       // See PrepareCall() for more information about calls through function
4283       // pointers in the 64-bit SVR4 ABI.
4284       // We are using a target-specific load with r2 hard coded, because the
4285       // result of a target-independent load would never go directly into r2,
4286       // since r2 is a reserved register (which prevents the register allocator
4287       // from allocating it), resulting in an additional register being
4288       // allocated and an unnecessary move instruction being generated.
4289       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4290
4291       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4292       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4293       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4294       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4295       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4296
4297       // The address needs to go after the chain input but before the flag (or
4298       // any other variadic arguments).
4299       Ops.insert(std::next(Ops.begin()), AddTOC);
4300     } else if ((CallOpc == PPCISD::CALL) &&
4301                (!isLocalCall(Callee) ||
4302                 DAG.getTarget().getRelocationModel() == Reloc::PIC_))
4303       // Otherwise insert NOP for non-local calls.
4304       CallOpc = PPCISD::CALL_NOP;
4305   }
4306
4307   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4308   InFlag = Chain.getValue(1);
4309
4310   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4311                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4312                              InFlag, dl);
4313   if (!Ins.empty())
4314     InFlag = Chain.getValue(1);
4315
4316   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4317                          Ins, dl, DAG, InVals);
4318 }
4319
4320 SDValue
4321 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4322                              SmallVectorImpl<SDValue> &InVals) const {
4323   SelectionDAG &DAG                     = CLI.DAG;
4324   SDLoc &dl                             = CLI.DL;
4325   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4326   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4327   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4328   SDValue Chain                         = CLI.Chain;
4329   SDValue Callee                        = CLI.Callee;
4330   bool &isTailCall                      = CLI.IsTailCall;
4331   CallingConv::ID CallConv              = CLI.CallConv;
4332   bool isVarArg                         = CLI.IsVarArg;
4333   bool IsPatchPoint                     = CLI.IsPatchPoint;
4334   ImmutableCallSite *CS                 = CLI.CS;
4335
4336   if (isTailCall)
4337     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4338                                                    Ins, DAG);
4339
4340   if (!isTailCall && CS && CS->isMustTailCall())
4341     report_fatal_error("failed to perform tail call elimination on a call "
4342                        "site marked musttail");
4343
4344   if (Subtarget.isSVR4ABI()) {
4345     if (Subtarget.isPPC64())
4346       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4347                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4348                               dl, DAG, InVals, CS);
4349     else
4350       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4351                               isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4352                               dl, DAG, InVals, CS);
4353   }
4354
4355   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4356                           isTailCall, IsPatchPoint, Outs, OutVals, Ins,
4357                           dl, DAG, InVals, CS);
4358 }
4359
4360 SDValue
4361 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
4362                                     CallingConv::ID CallConv, bool isVarArg,
4363                                     bool isTailCall, bool IsPatchPoint,
4364                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4365                                     const SmallVectorImpl<SDValue> &OutVals,
4366                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4367                                     SDLoc dl, SelectionDAG &DAG,
4368                                     SmallVectorImpl<SDValue> &InVals,
4369                                     ImmutableCallSite *CS) const {
4370   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4371   // of the 32-bit SVR4 ABI stack frame layout.
4372
4373   assert((CallConv == CallingConv::C ||
4374           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4375
4376   unsigned PtrByteSize = 4;
4377
4378   MachineFunction &MF = DAG.getMachineFunction();
4379
4380   // Mark this function as potentially containing a function that contains a
4381   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4382   // and restoring the callers stack pointer in this functions epilog. This is
4383   // done because by tail calling the called function might overwrite the value
4384   // in this function's (MF) stack pointer stack slot 0(SP).
4385   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4386       CallConv == CallingConv::Fast)
4387     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4388
4389   // Count how many bytes are to be pushed on the stack, including the linkage
4390   // area, parameter list area and the part of the local variable space which
4391   // contains copies of aggregates which are passed by value.
4392
4393   // Assign locations to all of the outgoing arguments.
4394   SmallVector<CCValAssign, 16> ArgLocs;
4395   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4396                  *DAG.getContext());
4397
4398   // Reserve space for the linkage area on the stack.
4399   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4400                        PtrByteSize);
4401
4402   if (isVarArg) {
4403     // Handle fixed and variable vector arguments differently.
4404     // Fixed vector arguments go into registers as long as registers are
4405     // available. Variable vector arguments always go into memory.
4406     unsigned NumArgs = Outs.size();
4407
4408     for (unsigned i = 0; i != NumArgs; ++i) {
4409       MVT ArgVT = Outs[i].VT;
4410       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4411       bool Result;
4412
4413       if (Outs[i].IsFixed) {
4414         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4415                                CCInfo);
4416       } else {
4417         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4418                                       ArgFlags, CCInfo);
4419       }
4420
4421       if (Result) {
4422 #ifndef NDEBUG
4423         errs() << "Call operand #" << i << " has unhandled type "
4424              << EVT(ArgVT).getEVTString() << "\n";
4425 #endif
4426         llvm_unreachable(nullptr);
4427       }
4428     }
4429   } else {
4430     // All arguments are treated the same.
4431     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4432   }
4433
4434   // Assign locations to all of the outgoing aggregate by value arguments.
4435   SmallVector<CCValAssign, 16> ByValArgLocs;
4436   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4437                       ByValArgLocs, *DAG.getContext());
4438
4439   // Reserve stack space for the allocations in CCInfo.
4440   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4441
4442   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4443
4444   // Size of the linkage area, parameter list area and the part of the local
4445   // space variable where copies of aggregates which are passed by value are
4446   // stored.
4447   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4448
4449   // Calculate by how many bytes the stack has to be adjusted in case of tail
4450   // call optimization.
4451   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4452
4453   // Adjust the stack pointer for the new arguments...
4454   // These operations are automatically eliminated by the prolog/epilog pass
4455   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4456                                dl);
4457   SDValue CallSeqStart = Chain;
4458
4459   // Load the return address and frame pointer so it can be moved somewhere else
4460   // later.
4461   SDValue LROp, FPOp;
4462   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4463                                        dl);
4464
4465   // Set up a copy of the stack pointer for use loading and storing any
4466   // arguments that may not fit in the registers available for argument
4467   // passing.
4468   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4469
4470   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4471   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4472   SmallVector<SDValue, 8> MemOpChains;
4473
4474   bool seenFloatArg = false;
4475   // Walk the register/memloc assignments, inserting copies/loads.
4476   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4477        i != e;
4478        ++i) {
4479     CCValAssign &VA = ArgLocs[i];
4480     SDValue Arg = OutVals[i];
4481     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4482
4483     if (Flags.isByVal()) {
4484       // Argument is an aggregate which is passed by value, thus we need to
4485       // create a copy of it in the local variable space of the current stack
4486       // frame (which is the stack frame of the caller) and pass the address of
4487       // this copy to the callee.
4488       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4489       CCValAssign &ByValVA = ByValArgLocs[j++];
4490       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4491
4492       // Memory reserved in the local variable space of the callers stack frame.
4493       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4494
4495       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4496       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4497
4498       // Create a copy of the argument in the local area of the current
4499       // stack frame.
4500       SDValue MemcpyCall =
4501         CreateCopyOfByValArgument(Arg, PtrOff,
4502                                   CallSeqStart.getNode()->getOperand(0),
4503                                   Flags, DAG, dl);
4504
4505       // This must go outside the CALLSEQ_START..END.
4506       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4507                            CallSeqStart.getNode()->getOperand(1),
4508                            SDLoc(MemcpyCall));
4509       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4510                              NewCallSeqStart.getNode());
4511       Chain = CallSeqStart = NewCallSeqStart;
4512
4513       // Pass the address of the aggregate copy on the stack either in a
4514       // physical register or in the parameter list area of the current stack
4515       // frame to the callee.
4516       Arg = PtrOff;
4517     }
4518
4519     if (VA.isRegLoc()) {
4520       if (Arg.getValueType() == MVT::i1)
4521         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4522
4523       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4524       // Put argument in a physical register.
4525       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4526     } else {
4527       // Put argument in the parameter list area of the current stack frame.
4528       assert(VA.isMemLoc());
4529       unsigned LocMemOffset = VA.getLocMemOffset();
4530
4531       if (!isTailCall) {
4532         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4533         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4534
4535         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4536                                            MachinePointerInfo(),
4537                                            false, false, 0));
4538       } else {
4539         // Calculate and remember argument location.
4540         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4541                                  TailCallArguments);
4542       }
4543     }
4544   }
4545
4546   if (!MemOpChains.empty())
4547     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4548
4549   // Build a sequence of copy-to-reg nodes chained together with token chain
4550   // and flag operands which copy the outgoing args into the appropriate regs.
4551   SDValue InFlag;
4552   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4553     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4554                              RegsToPass[i].second, InFlag);
4555     InFlag = Chain.getValue(1);
4556   }
4557
4558   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4559   // registers.
4560   if (isVarArg) {
4561     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4562     SDValue Ops[] = { Chain, InFlag };
4563
4564     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4565                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4566
4567     InFlag = Chain.getValue(1);
4568   }
4569
4570   if (isTailCall)
4571     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4572                     false, TailCallArguments);
4573
4574   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4575                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
4576                     NumBytes, Ins, InVals, CS);
4577 }
4578
4579 // Copy an argument into memory, being careful to do this outside the
4580 // call sequence for the call to which the argument belongs.
4581 SDValue
4582 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4583                                               SDValue CallSeqStart,
4584                                               ISD::ArgFlagsTy Flags,
4585                                               SelectionDAG &DAG,
4586                                               SDLoc dl) const {
4587   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4588                         CallSeqStart.getNode()->getOperand(0),
4589                         Flags, DAG, dl);
4590   // The MEMCPY must go outside the CALLSEQ_START..END.
4591   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4592                              CallSeqStart.getNode()->getOperand(1),
4593                              SDLoc(MemcpyCall));
4594   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4595                          NewCallSeqStart.getNode());
4596   return NewCallSeqStart;
4597 }
4598
4599 SDValue
4600 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4601                                     CallingConv::ID CallConv, bool isVarArg,
4602                                     bool isTailCall, bool IsPatchPoint,
4603                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4604                                     const SmallVectorImpl<SDValue> &OutVals,
4605                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4606                                     SDLoc dl, SelectionDAG &DAG,
4607                                     SmallVectorImpl<SDValue> &InVals,
4608                                     ImmutableCallSite *CS) const {
4609
4610   bool isELFv2ABI = Subtarget.isELFv2ABI();
4611   bool isLittleEndian = Subtarget.isLittleEndian();
4612   unsigned NumOps = Outs.size();
4613
4614   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4615   unsigned PtrByteSize = 8;
4616
4617   MachineFunction &MF = DAG.getMachineFunction();
4618
4619   // Mark this function as potentially containing a function that contains a
4620   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4621   // and restoring the callers stack pointer in this functions epilog. This is
4622   // done because by tail calling the called function might overwrite the value
4623   // in this function's (MF) stack pointer stack slot 0(SP).
4624   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4625       CallConv == CallingConv::Fast)
4626     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4627
4628   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4629          "fastcc not supported on varargs functions");
4630
4631   // Count how many bytes are to be pushed on the stack, including the linkage
4632   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4633   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4634   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4635   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4636   unsigned NumBytes = LinkageSize;
4637   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4638   unsigned &QFPR_idx = FPR_idx;
4639
4640   static const MCPhysReg GPR[] = {
4641     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4642     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4643   };
4644   static const MCPhysReg VR[] = {
4645     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4646     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4647   };
4648   static const MCPhysReg VSRH[] = {
4649     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4650     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4651   };
4652
4653   const unsigned NumGPRs = array_lengthof(GPR);
4654   const unsigned NumFPRs = 13;
4655   const unsigned NumVRs  = array_lengthof(VR);
4656   const unsigned NumQFPRs = NumFPRs;
4657
4658   // When using the fast calling convention, we don't provide backing for
4659   // arguments that will be in registers.
4660   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
4661
4662   // Add up all the space actually used.
4663   for (unsigned i = 0; i != NumOps; ++i) {
4664     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4665     EVT ArgVT = Outs[i].VT;
4666     EVT OrigVT = Outs[i].ArgVT;
4667
4668     if (CallConv == CallingConv::Fast) {
4669       if (Flags.isByVal())
4670         NumGPRsUsed += (Flags.getByValSize()+7)/8;
4671       else
4672         switch (ArgVT.getSimpleVT().SimpleTy) {
4673         default: llvm_unreachable("Unexpected ValueType for argument!");
4674         case MVT::i1:
4675         case MVT::i32:
4676         case MVT::i64:
4677           if (++NumGPRsUsed <= NumGPRs)
4678             continue;
4679           break;
4680         case MVT::v4i32:
4681         case MVT::v8i16:
4682         case MVT::v16i8:
4683         case MVT::v2f64:
4684         case MVT::v2i64:
4685         case MVT::v1i128:
4686           if (++NumVRsUsed <= NumVRs)
4687             continue;
4688           break;
4689         case MVT::v4f32:
4690           // When using QPX, this is handled like a FP register, otherwise, it
4691           // is an Altivec register.
4692           if (Subtarget.hasQPX()) {
4693             if (++NumFPRsUsed <= NumFPRs)
4694               continue;
4695           } else {
4696             if (++NumVRsUsed <= NumVRs)
4697               continue;
4698           }
4699           break;
4700         case MVT::f32:
4701         case MVT::f64:
4702         case MVT::v4f64: // QPX
4703         case MVT::v4i1:  // QPX
4704           if (++NumFPRsUsed <= NumFPRs)
4705             continue;
4706           break;
4707         }
4708     }
4709
4710     /* Respect alignment of argument on the stack.  */
4711     unsigned Align =
4712       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4713     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4714
4715     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4716     if (Flags.isInConsecutiveRegsLast())
4717       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4718   }
4719
4720   unsigned NumBytesActuallyUsed = NumBytes;
4721
4722   // The prolog code of the callee may store up to 8 GPR argument registers to
4723   // the stack, allowing va_start to index over them in memory if its varargs.
4724   // Because we cannot tell if this is needed on the caller side, we have to
4725   // conservatively assume that it is needed.  As such, make sure we have at
4726   // least enough stack space for the caller to store the 8 GPRs.
4727   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4728   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4729
4730   // Tail call needs the stack to be aligned.
4731   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4732       CallConv == CallingConv::Fast)
4733     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
4734
4735   // Calculate by how many bytes the stack has to be adjusted in case of tail
4736   // call optimization.
4737   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4738
4739   // To protect arguments on the stack from being clobbered in a tail call,
4740   // force all the loads to happen before doing any other lowering.
4741   if (isTailCall)
4742     Chain = DAG.getStackArgumentTokenFactor(Chain);
4743
4744   // Adjust the stack pointer for the new arguments...
4745   // These operations are automatically eliminated by the prolog/epilog pass
4746   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4747                                dl);
4748   SDValue CallSeqStart = Chain;
4749
4750   // Load the return address and frame pointer so it can be move somewhere else
4751   // later.
4752   SDValue LROp, FPOp;
4753   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4754                                        dl);
4755
4756   // Set up a copy of the stack pointer for use loading and storing any
4757   // arguments that may not fit in the registers available for argument
4758   // passing.
4759   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4760
4761   // Figure out which arguments are going to go in registers, and which in
4762   // memory.  Also, if this is a vararg function, floating point operations
4763   // must be stored to our stack, and loaded into integer regs as well, if
4764   // any integer regs are available for argument passing.
4765   unsigned ArgOffset = LinkageSize;
4766
4767   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4768   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4769
4770   SmallVector<SDValue, 8> MemOpChains;
4771   for (unsigned i = 0; i != NumOps; ++i) {
4772     SDValue Arg = OutVals[i];
4773     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4774     EVT ArgVT = Outs[i].VT;
4775     EVT OrigVT = Outs[i].ArgVT;
4776
4777     // PtrOff will be used to store the current argument to the stack if a
4778     // register cannot be found for it.
4779     SDValue PtrOff;
4780
4781     // We re-align the argument offset for each argument, except when using the
4782     // fast calling convention, when we need to make sure we do that only when
4783     // we'll actually use a stack slot.
4784     auto ComputePtrOff = [&]() {
4785       /* Respect alignment of argument on the stack.  */
4786       unsigned Align =
4787         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4788       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4789
4790       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
4791
4792       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4793     };
4794
4795     if (CallConv != CallingConv::Fast) {
4796       ComputePtrOff();
4797
4798       /* Compute GPR index associated with argument offset.  */
4799       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4800       GPR_idx = std::min(GPR_idx, NumGPRs);
4801     }
4802
4803     // Promote integers to 64-bit values.
4804     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4805       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4806       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4807       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4808     }
4809
4810     // FIXME memcpy is used way more than necessary.  Correctness first.
4811     // Note: "by value" is code for passing a structure by value, not
4812     // basic types.
4813     if (Flags.isByVal()) {
4814       // Note: Size includes alignment padding, so
4815       //   struct x { short a; char b; }
4816       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4817       // These are the proper values we need for right-justifying the
4818       // aggregate in a parameter register.
4819       unsigned Size = Flags.getByValSize();
4820
4821       // An empty aggregate parameter takes up no storage and no
4822       // registers.
4823       if (Size == 0)
4824         continue;
4825
4826       if (CallConv == CallingConv::Fast)
4827         ComputePtrOff();
4828
4829       // All aggregates smaller than 8 bytes must be passed right-justified.
4830       if (Size==1 || Size==2 || Size==4) {
4831         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4832         if (GPR_idx != NumGPRs) {
4833           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4834                                         MachinePointerInfo(), VT,
4835                                         false, false, false, 0);
4836           MemOpChains.push_back(Load.getValue(1));
4837           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4838
4839           ArgOffset += PtrByteSize;
4840           continue;
4841         }
4842       }
4843
4844       if (GPR_idx == NumGPRs && Size < 8) {
4845         SDValue AddPtr = PtrOff;
4846         if (!isLittleEndian) {
4847           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
4848                                           PtrOff.getValueType());
4849           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4850         }
4851         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4852                                                           CallSeqStart,
4853                                                           Flags, DAG, dl);
4854         ArgOffset += PtrByteSize;
4855         continue;
4856       }
4857       // Copy entire object into memory.  There are cases where gcc-generated
4858       // code assumes it is there, even if it could be put entirely into
4859       // registers.  (This is not what the doc says.)
4860
4861       // FIXME: The above statement is likely due to a misunderstanding of the
4862       // documents.  All arguments must be copied into the parameter area BY
4863       // THE CALLEE in the event that the callee takes the address of any
4864       // formal argument.  That has not yet been implemented.  However, it is
4865       // reasonable to use the stack area as a staging area for the register
4866       // load.
4867
4868       // Skip this for small aggregates, as we will use the same slot for a
4869       // right-justified copy, below.
4870       if (Size >= 8)
4871         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4872                                                           CallSeqStart,
4873                                                           Flags, DAG, dl);
4874
4875       // When a register is available, pass a small aggregate right-justified.
4876       if (Size < 8 && GPR_idx != NumGPRs) {
4877         // The easiest way to get this right-justified in a register
4878         // is to copy the structure into the rightmost portion of a
4879         // local variable slot, then load the whole slot into the
4880         // register.
4881         // FIXME: The memcpy seems to produce pretty awful code for
4882         // small aggregates, particularly for packed ones.
4883         // FIXME: It would be preferable to use the slot in the
4884         // parameter save area instead of a new local variable.
4885         SDValue AddPtr = PtrOff;
4886         if (!isLittleEndian) {
4887           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
4888           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4889         }
4890         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4891                                                           CallSeqStart,
4892                                                           Flags, DAG, dl);
4893
4894         // Load the slot into the register.
4895         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4896                                    MachinePointerInfo(),
4897                                    false, false, false, 0);
4898         MemOpChains.push_back(Load.getValue(1));
4899         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4900
4901         // Done with this argument.
4902         ArgOffset += PtrByteSize;
4903         continue;
4904       }
4905
4906       // For aggregates larger than PtrByteSize, copy the pieces of the
4907       // object that fit into registers from the parameter save area.
4908       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4909         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
4910         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4911         if (GPR_idx != NumGPRs) {
4912           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4913                                      MachinePointerInfo(),
4914                                      false, false, false, 0);
4915           MemOpChains.push_back(Load.getValue(1));
4916           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4917           ArgOffset += PtrByteSize;
4918         } else {
4919           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4920           break;
4921         }
4922       }
4923       continue;
4924     }
4925
4926     switch (Arg.getSimpleValueType().SimpleTy) {
4927     default: llvm_unreachable("Unexpected ValueType for argument!");
4928     case MVT::i1:
4929     case MVT::i32:
4930     case MVT::i64:
4931       // These can be scalar arguments or elements of an integer array type
4932       // passed directly.  Clang may use those instead of "byval" aggregate
4933       // types to avoid forcing arguments to memory unnecessarily.
4934       if (GPR_idx != NumGPRs) {
4935         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4936       } else {
4937         if (CallConv == CallingConv::Fast)
4938           ComputePtrOff();
4939
4940         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4941                          true, isTailCall, false, MemOpChains,
4942                          TailCallArguments, dl);
4943         if (CallConv == CallingConv::Fast)
4944           ArgOffset += PtrByteSize;
4945       }
4946       if (CallConv != CallingConv::Fast)
4947         ArgOffset += PtrByteSize;
4948       break;
4949     case MVT::f32:
4950     case MVT::f64: {
4951       // These can be scalar arguments or elements of a float array type
4952       // passed directly.  The latter are used to implement ELFv2 homogenous
4953       // float aggregates.
4954
4955       // Named arguments go into FPRs first, and once they overflow, the
4956       // remaining arguments go into GPRs and then the parameter save area.
4957       // Unnamed arguments for vararg functions always go to GPRs and
4958       // then the parameter save area.  For now, put all arguments to vararg
4959       // routines always in both locations (FPR *and* GPR or stack slot).
4960       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4961       bool NeededLoad = false;
4962
4963       // First load the argument into the next available FPR.
4964       if (FPR_idx != NumFPRs)
4965         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4966
4967       // Next, load the argument into GPR or stack slot if needed.
4968       if (!NeedGPROrStack)
4969         ;
4970       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
4971         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4972         // once we support fp <-> gpr moves.
4973
4974         // In the non-vararg case, this can only ever happen in the
4975         // presence of f32 array types, since otherwise we never run
4976         // out of FPRs before running out of GPRs.
4977         SDValue ArgVal;
4978
4979         // Double values are always passed in a single GPR.
4980         if (Arg.getValueType() != MVT::f32) {
4981           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4982
4983         // Non-array float values are extended and passed in a GPR.
4984         } else if (!Flags.isInConsecutiveRegs()) {
4985           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4986           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4987
4988         // If we have an array of floats, we collect every odd element
4989         // together with its predecessor into one GPR.
4990         } else if (ArgOffset % PtrByteSize != 0) {
4991           SDValue Lo, Hi;
4992           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4993           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4994           if (!isLittleEndian)
4995             std::swap(Lo, Hi);
4996           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4997
4998         // The final element, if even, goes into the first half of a GPR.
4999         } else if (Flags.isInConsecutiveRegsLast()) {
5000           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5001           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5002           if (!isLittleEndian)
5003             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5004                                  DAG.getConstant(32, dl, MVT::i32));
5005
5006         // Non-final even elements are skipped; they will be handled
5007         // together the with subsequent argument on the next go-around.
5008         } else
5009           ArgVal = SDValue();
5010
5011         if (ArgVal.getNode())
5012           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5013       } else {
5014         if (CallConv == CallingConv::Fast)
5015           ComputePtrOff();
5016
5017         // Single-precision floating-point values are mapped to the
5018         // second (rightmost) word of the stack doubleword.
5019         if (Arg.getValueType() == MVT::f32 &&
5020             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5021           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5022           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5023         }
5024
5025         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5026                          true, isTailCall, false, MemOpChains,
5027                          TailCallArguments, dl);
5028
5029         NeededLoad = true;
5030       }
5031       // When passing an array of floats, the array occupies consecutive
5032       // space in the argument area; only round up to the next doubleword
5033       // at the end of the array.  Otherwise, each float takes 8 bytes.
5034       if (CallConv != CallingConv::Fast || NeededLoad) {
5035         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5036                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5037         if (Flags.isInConsecutiveRegsLast())
5038           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5039       }
5040       break;
5041     }
5042     case MVT::v4f32:
5043     case MVT::v4i32:
5044     case MVT::v8i16:
5045     case MVT::v16i8:
5046     case MVT::v2f64:
5047     case MVT::v2i64:
5048     case MVT::v1i128:
5049       if (!Subtarget.hasQPX()) {
5050       // These can be scalar arguments or elements of a vector array type
5051       // passed directly.  The latter are used to implement ELFv2 homogenous
5052       // vector aggregates.
5053
5054       // For a varargs call, named arguments go into VRs or on the stack as
5055       // usual; unnamed arguments always go to the stack or the corresponding
5056       // GPRs when within range.  For now, we always put the value in both
5057       // locations (or even all three).
5058       if (isVarArg) {
5059         // We could elide this store in the case where the object fits
5060         // entirely in R registers.  Maybe later.
5061         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5062                                      MachinePointerInfo(), false, false, 0);
5063         MemOpChains.push_back(Store);
5064         if (VR_idx != NumVRs) {
5065           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5066                                      MachinePointerInfo(),
5067                                      false, false, false, 0);
5068           MemOpChains.push_back(Load.getValue(1));
5069
5070           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5071                            Arg.getSimpleValueType() == MVT::v2i64) ?
5072                           VSRH[VR_idx] : VR[VR_idx];
5073           ++VR_idx;
5074
5075           RegsToPass.push_back(std::make_pair(VReg, Load));
5076         }
5077         ArgOffset += 16;
5078         for (unsigned i=0; i<16; i+=PtrByteSize) {
5079           if (GPR_idx == NumGPRs)
5080             break;
5081           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5082                                    DAG.getConstant(i, dl, PtrVT));
5083           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5084                                      false, false, false, 0);
5085           MemOpChains.push_back(Load.getValue(1));
5086           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5087         }
5088         break;
5089       }
5090
5091       // Non-varargs Altivec params go into VRs or on the stack.
5092       if (VR_idx != NumVRs) {
5093         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
5094                          Arg.getSimpleValueType() == MVT::v2i64) ?
5095                         VSRH[VR_idx] : VR[VR_idx];
5096         ++VR_idx;
5097
5098         RegsToPass.push_back(std::make_pair(VReg, Arg));
5099       } else {
5100         if (CallConv == CallingConv::Fast)
5101           ComputePtrOff();
5102
5103         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5104                          true, isTailCall, true, MemOpChains,
5105                          TailCallArguments, dl);
5106         if (CallConv == CallingConv::Fast)
5107           ArgOffset += 16;
5108       }
5109
5110       if (CallConv != CallingConv::Fast)
5111         ArgOffset += 16;
5112       break;
5113       } // not QPX
5114
5115       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5116              "Invalid QPX parameter type");
5117
5118       /* fall through */
5119     case MVT::v4f64:
5120     case MVT::v4i1: {
5121       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5122       if (isVarArg) {
5123         // We could elide this store in the case where the object fits
5124         // entirely in R registers.  Maybe later.
5125         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5126                                      MachinePointerInfo(), false, false, 0);
5127         MemOpChains.push_back(Store);
5128         if (QFPR_idx != NumQFPRs) {
5129           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl,
5130                                      Store, PtrOff, MachinePointerInfo(),
5131                                      false, false, false, 0);
5132           MemOpChains.push_back(Load.getValue(1));
5133           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5134         }
5135         ArgOffset += (IsF32 ? 16 : 32);
5136         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5137           if (GPR_idx == NumGPRs)
5138             break;
5139           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5140                                    DAG.getConstant(i, dl, PtrVT));
5141           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5142                                      false, false, false, 0);
5143           MemOpChains.push_back(Load.getValue(1));
5144           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5145         }
5146         break;
5147       }
5148
5149       // Non-varargs QPX params go into registers or on the stack.
5150       if (QFPR_idx != NumQFPRs) {
5151         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5152       } else {
5153         if (CallConv == CallingConv::Fast)
5154           ComputePtrOff();
5155
5156         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5157                          true, isTailCall, true, MemOpChains,
5158                          TailCallArguments, dl);
5159         if (CallConv == CallingConv::Fast)
5160           ArgOffset += (IsF32 ? 16 : 32);
5161       }
5162
5163       if (CallConv != CallingConv::Fast)
5164         ArgOffset += (IsF32 ? 16 : 32);
5165       break;
5166       }
5167     }
5168   }
5169
5170   assert(NumBytesActuallyUsed == ArgOffset);
5171   (void)NumBytesActuallyUsed;
5172
5173   if (!MemOpChains.empty())
5174     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5175
5176   // Check if this is an indirect call (MTCTR/BCTRL).
5177   // See PrepareCall() for more information about calls through function
5178   // pointers in the 64-bit SVR4 ABI.
5179   if (!isTailCall && !IsPatchPoint &&
5180       !isFunctionGlobalAddress(Callee) &&
5181       !isa<ExternalSymbolSDNode>(Callee)) {
5182     // Load r2 into a virtual register and store it to the TOC save area.
5183     setUsesTOCBasePtr(DAG);
5184     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5185     // TOC save area offset.
5186     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5187     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5188     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5189     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
5190                          MachinePointerInfo::getStack(TOCSaveOffset),
5191                          false, false, 0);
5192     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5193     // This does not mean the MTCTR instruction must use R12; it's easier
5194     // to model this as an extra parameter, so do that.
5195     if (isELFv2ABI && !IsPatchPoint)
5196       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5197   }
5198
5199   // Build a sequence of copy-to-reg nodes chained together with token chain
5200   // and flag operands which copy the outgoing args into the appropriate regs.
5201   SDValue InFlag;
5202   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5203     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5204                              RegsToPass[i].second, InFlag);
5205     InFlag = Chain.getValue(1);
5206   }
5207
5208   if (isTailCall)
5209     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
5210                     FPOp, true, TailCallArguments);
5211
5212   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5213                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5214                     NumBytes, Ins, InVals, CS);
5215 }
5216
5217 SDValue
5218 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
5219                                     CallingConv::ID CallConv, bool isVarArg,
5220                                     bool isTailCall, bool IsPatchPoint,
5221                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
5222                                     const SmallVectorImpl<SDValue> &OutVals,
5223                                     const SmallVectorImpl<ISD::InputArg> &Ins,
5224                                     SDLoc dl, SelectionDAG &DAG,
5225                                     SmallVectorImpl<SDValue> &InVals,
5226                                     ImmutableCallSite *CS) const {
5227
5228   unsigned NumOps = Outs.size();
5229
5230   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5231   bool isPPC64 = PtrVT == MVT::i64;
5232   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5233
5234   MachineFunction &MF = DAG.getMachineFunction();
5235
5236   // Mark this function as potentially containing a function that contains a
5237   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5238   // and restoring the callers stack pointer in this functions epilog. This is
5239   // done because by tail calling the called function might overwrite the value
5240   // in this function's (MF) stack pointer stack slot 0(SP).
5241   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5242       CallConv == CallingConv::Fast)
5243     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5244
5245   // Count how many bytes are to be pushed on the stack, including the linkage
5246   // area, and parameter passing area.  We start with 24/48 bytes, which is
5247   // prereserved space for [SP][CR][LR][3 x unused].
5248   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5249   unsigned NumBytes = LinkageSize;
5250
5251   // Add up all the space actually used.
5252   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5253   // they all go in registers, but we must reserve stack space for them for
5254   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5255   // assigned stack space in order, with padding so Altivec parameters are
5256   // 16-byte aligned.
5257   unsigned nAltivecParamsAtEnd = 0;
5258   for (unsigned i = 0; i != NumOps; ++i) {
5259     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5260     EVT ArgVT = Outs[i].VT;
5261     // Varargs Altivec parameters are padded to a 16 byte boundary.
5262     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5263         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5264         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5265       if (!isVarArg && !isPPC64) {
5266         // Non-varargs Altivec parameters go after all the non-Altivec
5267         // parameters; handle those later so we know how much padding we need.
5268         nAltivecParamsAtEnd++;
5269         continue;
5270       }
5271       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5272       NumBytes = ((NumBytes+15)/16)*16;
5273     }
5274     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5275   }
5276
5277   // Allow for Altivec parameters at the end, if needed.
5278   if (nAltivecParamsAtEnd) {
5279     NumBytes = ((NumBytes+15)/16)*16;
5280     NumBytes += 16*nAltivecParamsAtEnd;
5281   }
5282
5283   // The prolog code of the callee may store up to 8 GPR argument registers to
5284   // the stack, allowing va_start to index over them in memory if its varargs.
5285   // Because we cannot tell if this is needed on the caller side, we have to
5286   // conservatively assume that it is needed.  As such, make sure we have at
5287   // least enough stack space for the caller to store the 8 GPRs.
5288   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5289
5290   // Tail call needs the stack to be aligned.
5291   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5292       CallConv == CallingConv::Fast)
5293     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5294
5295   // Calculate by how many bytes the stack has to be adjusted in case of tail
5296   // call optimization.
5297   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5298
5299   // To protect arguments on the stack from being clobbered in a tail call,
5300   // force all the loads to happen before doing any other lowering.
5301   if (isTailCall)
5302     Chain = DAG.getStackArgumentTokenFactor(Chain);
5303
5304   // Adjust the stack pointer for the new arguments...
5305   // These operations are automatically eliminated by the prolog/epilog pass
5306   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5307                                dl);
5308   SDValue CallSeqStart = Chain;
5309
5310   // Load the return address and frame pointer so it can be move somewhere else
5311   // later.
5312   SDValue LROp, FPOp;
5313   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
5314                                        dl);
5315
5316   // Set up a copy of the stack pointer for use loading and storing any
5317   // arguments that may not fit in the registers available for argument
5318   // passing.
5319   SDValue StackPtr;
5320   if (isPPC64)
5321     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5322   else
5323     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5324
5325   // Figure out which arguments are going to go in registers, and which in
5326   // memory.  Also, if this is a vararg function, floating point operations
5327   // must be stored to our stack, and loaded into integer regs as well, if
5328   // any integer regs are available for argument passing.
5329   unsigned ArgOffset = LinkageSize;
5330   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5331
5332   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5333     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5334     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5335   };
5336   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5337     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5338     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5339   };
5340   static const MCPhysReg VR[] = {
5341     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5342     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5343   };
5344   const unsigned NumGPRs = array_lengthof(GPR_32);
5345   const unsigned NumFPRs = 13;
5346   const unsigned NumVRs  = array_lengthof(VR);
5347
5348   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5349
5350   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5351   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5352
5353   SmallVector<SDValue, 8> MemOpChains;
5354   for (unsigned i = 0; i != NumOps; ++i) {
5355     SDValue Arg = OutVals[i];
5356     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5357
5358     // PtrOff will be used to store the current argument to the stack if a
5359     // register cannot be found for it.
5360     SDValue PtrOff;
5361
5362     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5363
5364     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5365
5366     // On PPC64, promote integers to 64-bit values.
5367     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5368       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5369       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5370       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5371     }
5372
5373     // FIXME memcpy is used way more than necessary.  Correctness first.
5374     // Note: "by value" is code for passing a structure by value, not
5375     // basic types.
5376     if (Flags.isByVal()) {
5377       unsigned Size = Flags.getByValSize();
5378       // Very small objects are passed right-justified.  Everything else is
5379       // passed left-justified.
5380       if (Size==1 || Size==2) {
5381         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5382         if (GPR_idx != NumGPRs) {
5383           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5384                                         MachinePointerInfo(), VT,
5385                                         false, false, false, 0);
5386           MemOpChains.push_back(Load.getValue(1));
5387           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5388
5389           ArgOffset += PtrByteSize;
5390         } else {
5391           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5392                                           PtrOff.getValueType());
5393           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5394           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5395                                                             CallSeqStart,
5396                                                             Flags, DAG, dl);
5397           ArgOffset += PtrByteSize;
5398         }
5399         continue;
5400       }
5401       // Copy entire object into memory.  There are cases where gcc-generated
5402       // code assumes it is there, even if it could be put entirely into
5403       // registers.  (This is not what the doc says.)
5404       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5405                                                         CallSeqStart,
5406                                                         Flags, DAG, dl);
5407
5408       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5409       // copy the pieces of the object that fit into registers from the
5410       // parameter save area.
5411       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5412         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5413         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5414         if (GPR_idx != NumGPRs) {
5415           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
5416                                      MachinePointerInfo(),
5417                                      false, false, false, 0);
5418           MemOpChains.push_back(Load.getValue(1));
5419           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5420           ArgOffset += PtrByteSize;
5421         } else {
5422           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5423           break;
5424         }
5425       }
5426       continue;
5427     }
5428
5429     switch (Arg.getSimpleValueType().SimpleTy) {
5430     default: llvm_unreachable("Unexpected ValueType for argument!");
5431     case MVT::i1:
5432     case MVT::i32:
5433     case MVT::i64:
5434       if (GPR_idx != NumGPRs) {
5435         if (Arg.getValueType() == MVT::i1)
5436           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5437
5438         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5439       } else {
5440         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5441                          isPPC64, isTailCall, false, MemOpChains,
5442                          TailCallArguments, dl);
5443       }
5444       ArgOffset += PtrByteSize;
5445       break;
5446     case MVT::f32:
5447     case MVT::f64:
5448       if (FPR_idx != NumFPRs) {
5449         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5450
5451         if (isVarArg) {
5452           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5453                                        MachinePointerInfo(), false, false, 0);
5454           MemOpChains.push_back(Store);
5455
5456           // Float varargs are always shadowed in available integer registers
5457           if (GPR_idx != NumGPRs) {
5458             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5459                                        MachinePointerInfo(), false, false,
5460                                        false, 0);
5461             MemOpChains.push_back(Load.getValue(1));
5462             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5463           }
5464           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5465             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5466             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5467             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
5468                                        MachinePointerInfo(),
5469                                        false, false, false, 0);
5470             MemOpChains.push_back(Load.getValue(1));
5471             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5472           }
5473         } else {
5474           // If we have any FPRs remaining, we may also have GPRs remaining.
5475           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5476           // GPRs.
5477           if (GPR_idx != NumGPRs)
5478             ++GPR_idx;
5479           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5480               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
5481             ++GPR_idx;
5482         }
5483       } else
5484         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5485                          isPPC64, isTailCall, false, MemOpChains,
5486                          TailCallArguments, dl);
5487       if (isPPC64)
5488         ArgOffset += 8;
5489       else
5490         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
5491       break;
5492     case MVT::v4f32:
5493     case MVT::v4i32:
5494     case MVT::v8i16:
5495     case MVT::v16i8:
5496       if (isVarArg) {
5497         // These go aligned on the stack, or in the corresponding R registers
5498         // when within range.  The Darwin PPC ABI doc claims they also go in
5499         // V registers; in fact gcc does this only for arguments that are
5500         // prototyped, not for those that match the ...  We do it for all
5501         // arguments, seems to work.
5502         while (ArgOffset % 16 !=0) {
5503           ArgOffset += PtrByteSize;
5504           if (GPR_idx != NumGPRs)
5505             GPR_idx++;
5506         }
5507         // We could elide this store in the case where the object fits
5508         // entirely in R registers.  Maybe later.
5509         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5510                              DAG.getConstant(ArgOffset, dl, PtrVT));
5511         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5512                                      MachinePointerInfo(), false, false, 0);
5513         MemOpChains.push_back(Store);
5514         if (VR_idx != NumVRs) {
5515           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5516                                      MachinePointerInfo(),
5517                                      false, false, false, 0);
5518           MemOpChains.push_back(Load.getValue(1));
5519           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5520         }
5521         ArgOffset += 16;
5522         for (unsigned i=0; i<16; i+=PtrByteSize) {
5523           if (GPR_idx == NumGPRs)
5524             break;
5525           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5526                                    DAG.getConstant(i, dl, PtrVT));
5527           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5528                                      false, false, false, 0);
5529           MemOpChains.push_back(Load.getValue(1));
5530           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5531         }
5532         break;
5533       }
5534
5535       // Non-varargs Altivec params generally go in registers, but have
5536       // stack space allocated at the end.
5537       if (VR_idx != NumVRs) {
5538         // Doesn't have GPR space allocated.
5539         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5540       } else if (nAltivecParamsAtEnd==0) {
5541         // We are emitting Altivec params in order.
5542         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5543                          isPPC64, isTailCall, true, MemOpChains,
5544                          TailCallArguments, dl);
5545         ArgOffset += 16;
5546       }
5547       break;
5548     }
5549   }
5550   // If all Altivec parameters fit in registers, as they usually do,
5551   // they get stack space following the non-Altivec parameters.  We
5552   // don't track this here because nobody below needs it.
5553   // If there are more Altivec parameters than fit in registers emit
5554   // the stores here.
5555   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5556     unsigned j = 0;
5557     // Offset is aligned; skip 1st 12 params which go in V registers.
5558     ArgOffset = ((ArgOffset+15)/16)*16;
5559     ArgOffset += 12*16;
5560     for (unsigned i = 0; i != NumOps; ++i) {
5561       SDValue Arg = OutVals[i];
5562       EVT ArgType = Outs[i].VT;
5563       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5564           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5565         if (++j > NumVRs) {
5566           SDValue PtrOff;
5567           // We are emitting Altivec params in order.
5568           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5569                            isPPC64, isTailCall, true, MemOpChains,
5570                            TailCallArguments, dl);
5571           ArgOffset += 16;
5572         }
5573       }
5574     }
5575   }
5576
5577   if (!MemOpChains.empty())
5578     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5579
5580   // On Darwin, R12 must contain the address of an indirect callee.  This does
5581   // not mean the MTCTR instruction must use R12; it's easier to model this as
5582   // an extra parameter, so do that.
5583   if (!isTailCall &&
5584       !isFunctionGlobalAddress(Callee) &&
5585       !isa<ExternalSymbolSDNode>(Callee) &&
5586       !isBLACompatibleAddress(Callee, DAG))
5587     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5588                                                    PPC::R12), Callee));
5589
5590   // Build a sequence of copy-to-reg nodes chained together with token chain
5591   // and flag operands which copy the outgoing args into the appropriate regs.
5592   SDValue InFlag;
5593   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5594     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5595                              RegsToPass[i].second, InFlag);
5596     InFlag = Chain.getValue(1);
5597   }
5598
5599   if (isTailCall)
5600     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5601                     FPOp, true, TailCallArguments);
5602
5603   return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5604                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5605                     NumBytes, Ins, InVals, CS);
5606 }
5607
5608 bool
5609 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5610                                   MachineFunction &MF, bool isVarArg,
5611                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5612                                   LLVMContext &Context) const {
5613   SmallVector<CCValAssign, 16> RVLocs;
5614   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5615   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5616 }
5617
5618 SDValue
5619 PPCTargetLowering::LowerReturn(SDValue Chain,
5620                                CallingConv::ID CallConv, bool isVarArg,
5621                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5622                                const SmallVectorImpl<SDValue> &OutVals,
5623                                SDLoc dl, SelectionDAG &DAG) const {
5624
5625   SmallVector<CCValAssign, 16> RVLocs;
5626   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5627                  *DAG.getContext());
5628   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5629
5630   SDValue Flag;
5631   SmallVector<SDValue, 4> RetOps(1, Chain);
5632
5633   // Copy the result values into the output registers.
5634   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5635     CCValAssign &VA = RVLocs[i];
5636     assert(VA.isRegLoc() && "Can only return in registers!");
5637
5638     SDValue Arg = OutVals[i];
5639
5640     switch (VA.getLocInfo()) {
5641     default: llvm_unreachable("Unknown loc info!");
5642     case CCValAssign::Full: break;
5643     case CCValAssign::AExt:
5644       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5645       break;
5646     case CCValAssign::ZExt:
5647       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5648       break;
5649     case CCValAssign::SExt:
5650       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5651       break;
5652     }
5653
5654     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5655     Flag = Chain.getValue(1);
5656     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5657   }
5658
5659   RetOps[0] = Chain;  // Update chain.
5660
5661   // Add the flag if we have it.
5662   if (Flag.getNode())
5663     RetOps.push_back(Flag);
5664
5665   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5666 }
5667
5668 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5669                                    const PPCSubtarget &Subtarget) const {
5670   // When we pop the dynamic allocation we need to restore the SP link.
5671   SDLoc dl(Op);
5672
5673   // Get the corect type for pointers.
5674   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5675
5676   // Construct the stack pointer operand.
5677   bool isPPC64 = Subtarget.isPPC64();
5678   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5679   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5680
5681   // Get the operands for the STACKRESTORE.
5682   SDValue Chain = Op.getOperand(0);
5683   SDValue SaveSP = Op.getOperand(1);
5684
5685   // Load the old link SP.
5686   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5687                                    MachinePointerInfo(),
5688                                    false, false, false, 0);
5689
5690   // Restore the stack pointer.
5691   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5692
5693   // Store the old link SP.
5694   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5695                       false, false, 0);
5696 }
5697
5698
5699
5700 SDValue
5701 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5702   MachineFunction &MF = DAG.getMachineFunction();
5703   bool isPPC64 = Subtarget.isPPC64();
5704   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5705
5706   // Get current frame pointer save index.  The users of this index will be
5707   // primarily DYNALLOC instructions.
5708   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5709   int RASI = FI->getReturnAddrSaveIndex();
5710
5711   // If the frame pointer save index hasn't been defined yet.
5712   if (!RASI) {
5713     // Find out what the fix offset of the frame pointer save area.
5714     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
5715     // Allocate the frame index for frame pointer save area.
5716     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5717     // Save the result.
5718     FI->setReturnAddrSaveIndex(RASI);
5719   }
5720   return DAG.getFrameIndex(RASI, PtrVT);
5721 }
5722
5723 SDValue
5724 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5725   MachineFunction &MF = DAG.getMachineFunction();
5726   bool isPPC64 = Subtarget.isPPC64();
5727   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5728
5729   // Get current frame pointer save index.  The users of this index will be
5730   // primarily DYNALLOC instructions.
5731   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5732   int FPSI = FI->getFramePointerSaveIndex();
5733
5734   // If the frame pointer save index hasn't been defined yet.
5735   if (!FPSI) {
5736     // Find out what the fix offset of the frame pointer save area.
5737     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
5738     // Allocate the frame index for frame pointer save area.
5739     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5740     // Save the result.
5741     FI->setFramePointerSaveIndex(FPSI);
5742   }
5743   return DAG.getFrameIndex(FPSI, PtrVT);
5744 }
5745
5746 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5747                                          SelectionDAG &DAG,
5748                                          const PPCSubtarget &Subtarget) const {
5749   // Get the inputs.
5750   SDValue Chain = Op.getOperand(0);
5751   SDValue Size  = Op.getOperand(1);
5752   SDLoc dl(Op);
5753
5754   // Get the corect type for pointers.
5755   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5756   // Negate the size.
5757   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5758                                 DAG.getConstant(0, dl, PtrVT), Size);
5759   // Construct a node for the frame pointer save index.
5760   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5761   // Build a DYNALLOC node.
5762   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5763   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5764   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5765 }
5766
5767 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5768                                                SelectionDAG &DAG) const {
5769   SDLoc DL(Op);
5770   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5771                      DAG.getVTList(MVT::i32, MVT::Other),
5772                      Op.getOperand(0), Op.getOperand(1));
5773 }
5774
5775 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5776                                                 SelectionDAG &DAG) const {
5777   SDLoc DL(Op);
5778   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5779                      Op.getOperand(0), Op.getOperand(1));
5780 }
5781
5782 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5783   if (Op.getValueType().isVector())
5784     return LowerVectorLoad(Op, DAG);
5785
5786   assert(Op.getValueType() == MVT::i1 &&
5787          "Custom lowering only for i1 loads");
5788
5789   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5790
5791   SDLoc dl(Op);
5792   LoadSDNode *LD = cast<LoadSDNode>(Op);
5793
5794   SDValue Chain = LD->getChain();
5795   SDValue BasePtr = LD->getBasePtr();
5796   MachineMemOperand *MMO = LD->getMemOperand();
5797
5798   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5799                                  BasePtr, MVT::i8, MMO);
5800   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5801
5802   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5803   return DAG.getMergeValues(Ops, dl);
5804 }
5805
5806 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5807   if (Op.getOperand(1).getValueType().isVector())
5808     return LowerVectorStore(Op, DAG);
5809
5810   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5811          "Custom lowering only for i1 stores");
5812
5813   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5814
5815   SDLoc dl(Op);
5816   StoreSDNode *ST = cast<StoreSDNode>(Op);
5817
5818   SDValue Chain = ST->getChain();
5819   SDValue BasePtr = ST->getBasePtr();
5820   SDValue Value = ST->getValue();
5821   MachineMemOperand *MMO = ST->getMemOperand();
5822
5823   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5824   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5825 }
5826
5827 // FIXME: Remove this once the ANDI glue bug is fixed:
5828 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5829   assert(Op.getValueType() == MVT::i1 &&
5830          "Custom lowering only for i1 results");
5831
5832   SDLoc DL(Op);
5833   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5834                      Op.getOperand(0));
5835 }
5836
5837 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5838 /// possible.
5839 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5840   // Not FP? Not a fsel.
5841   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5842       !Op.getOperand(2).getValueType().isFloatingPoint())
5843     return Op;
5844
5845   // We might be able to do better than this under some circumstances, but in
5846   // general, fsel-based lowering of select is a finite-math-only optimization.
5847   // For more information, see section F.3 of the 2.06 ISA specification.
5848   if (!DAG.getTarget().Options.NoInfsFPMath ||
5849       !DAG.getTarget().Options.NoNaNsFPMath)
5850     return Op;
5851
5852   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5853
5854   EVT ResVT = Op.getValueType();
5855   EVT CmpVT = Op.getOperand(0).getValueType();
5856   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5857   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5858   SDLoc dl(Op);
5859
5860   // If the RHS of the comparison is a 0.0, we don't need to do the
5861   // subtraction at all.
5862   SDValue Sel1;
5863   if (isFloatingPointZero(RHS))
5864     switch (CC) {
5865     default: break;       // SETUO etc aren't handled by fsel.
5866     case ISD::SETNE:
5867       std::swap(TV, FV);
5868     case ISD::SETEQ:
5869       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5870         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5871       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5872       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5873         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5874       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5875                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5876     case ISD::SETULT:
5877     case ISD::SETLT:
5878       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5879     case ISD::SETOGE:
5880     case ISD::SETGE:
5881       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5882         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5883       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5884     case ISD::SETUGT:
5885     case ISD::SETGT:
5886       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5887     case ISD::SETOLE:
5888     case ISD::SETLE:
5889       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5890         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5891       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5892                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5893     }
5894
5895   SDValue Cmp;
5896   switch (CC) {
5897   default: break;       // SETUO etc aren't handled by fsel.
5898   case ISD::SETNE:
5899     std::swap(TV, FV);
5900   case ISD::SETEQ:
5901     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5902     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5903       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5904     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5905     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5906       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5907     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5908                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5909   case ISD::SETULT:
5910   case ISD::SETLT:
5911     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5912     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5913       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5914     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5915   case ISD::SETOGE:
5916   case ISD::SETGE:
5917     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5918     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5919       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5920     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5921   case ISD::SETUGT:
5922   case ISD::SETGT:
5923     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5924     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5925       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5926     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5927   case ISD::SETOLE:
5928   case ISD::SETLE:
5929     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5930     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5931       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5932     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5933   }
5934   return Op;
5935 }
5936
5937 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5938                                                SelectionDAG &DAG,
5939                                                SDLoc dl) const {
5940   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5941   SDValue Src = Op.getOperand(0);
5942   if (Src.getValueType() == MVT::f32)
5943     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5944
5945   SDValue Tmp;
5946   switch (Op.getSimpleValueType().SimpleTy) {
5947   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5948   case MVT::i32:
5949     Tmp = DAG.getNode(
5950         Op.getOpcode() == ISD::FP_TO_SINT
5951             ? PPCISD::FCTIWZ
5952             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
5953         dl, MVT::f64, Src);
5954     break;
5955   case MVT::i64:
5956     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5957            "i64 FP_TO_UINT is supported only with FPCVT");
5958     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5959                                                         PPCISD::FCTIDUZ,
5960                       dl, MVT::f64, Src);
5961     break;
5962   }
5963
5964   // Convert the FP value to an int value through memory.
5965   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5966     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5967   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5968   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5969   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5970
5971   // Emit a store to the stack slot.
5972   SDValue Chain;
5973   if (i32Stack) {
5974     MachineFunction &MF = DAG.getMachineFunction();
5975     MachineMemOperand *MMO =
5976       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5977     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5978     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5979               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5980   } else
5981     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5982                          MPI, false, false, 0);
5983
5984   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5985   // add in a bias.
5986   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5987     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5988                         DAG.getConstant(4, dl, FIPtr.getValueType()));
5989     MPI = MPI.getWithOffset(4);
5990   }
5991
5992   RLI.Chain = Chain;
5993   RLI.Ptr = FIPtr;
5994   RLI.MPI = MPI;
5995 }
5996
5997 /// \brief Custom lowers floating point to integer conversions to use
5998 /// the direct move instructions available in ISA 2.07 to avoid the
5999 /// need for load/store combinations.
6000 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6001                                                     SelectionDAG &DAG,
6002                                                     SDLoc dl) const {
6003   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6004   SDValue Src = Op.getOperand(0);
6005
6006   if (Src.getValueType() == MVT::f32)
6007     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6008
6009   SDValue Tmp;
6010   switch (Op.getSimpleValueType().SimpleTy) {
6011   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6012   case MVT::i32:
6013     Tmp = DAG.getNode(
6014         Op.getOpcode() == ISD::FP_TO_SINT
6015             ? PPCISD::FCTIWZ
6016             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6017         dl, MVT::f64, Src);
6018     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6019     break;
6020   case MVT::i64:
6021     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6022            "i64 FP_TO_UINT is supported only with FPCVT");
6023     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6024                                                         PPCISD::FCTIDUZ,
6025                       dl, MVT::f64, Src);
6026     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6027     break;
6028   }
6029   return Tmp;
6030 }
6031
6032 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6033                                           SDLoc dl) const {
6034   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6035     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6036
6037   ReuseLoadInfo RLI;
6038   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6039
6040   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6041                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6042                      RLI.Ranges);
6043 }
6044
6045 // We're trying to insert a regular store, S, and then a load, L. If the
6046 // incoming value, O, is a load, we might just be able to have our load use the
6047 // address used by O. However, we don't know if anything else will store to
6048 // that address before we can load from it. To prevent this situation, we need
6049 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6050 // the same chain operand as O, we create a token factor from the chain results
6051 // of O and L, and we replace all uses of O's chain result with that token
6052 // factor (see spliceIntoChain below for this last part).
6053 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6054                                             ReuseLoadInfo &RLI,
6055                                             SelectionDAG &DAG,
6056                                             ISD::LoadExtType ET) const {
6057   SDLoc dl(Op);
6058   if (ET == ISD::NON_EXTLOAD &&
6059       (Op.getOpcode() == ISD::FP_TO_UINT ||
6060        Op.getOpcode() == ISD::FP_TO_SINT) &&
6061       isOperationLegalOrCustom(Op.getOpcode(),
6062                                Op.getOperand(0).getValueType())) {
6063
6064     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6065     return true;
6066   }
6067
6068   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6069   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6070       LD->isNonTemporal())
6071     return false;
6072   if (LD->getMemoryVT() != MemVT)
6073     return false;
6074
6075   RLI.Ptr = LD->getBasePtr();
6076   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
6077     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6078            "Non-pre-inc AM on PPC?");
6079     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6080                           LD->getOffset());
6081   }
6082
6083   RLI.Chain = LD->getChain();
6084   RLI.MPI = LD->getPointerInfo();
6085   RLI.IsInvariant = LD->isInvariant();
6086   RLI.Alignment = LD->getAlignment();
6087   RLI.AAInfo = LD->getAAInfo();
6088   RLI.Ranges = LD->getRanges();
6089
6090   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6091   return true;
6092 }
6093
6094 // Given the head of the old chain, ResChain, insert a token factor containing
6095 // it and NewResChain, and make users of ResChain now be users of that token
6096 // factor.
6097 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6098                                         SDValue NewResChain,
6099                                         SelectionDAG &DAG) const {
6100   if (!ResChain)
6101     return;
6102
6103   SDLoc dl(NewResChain);
6104
6105   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6106                            NewResChain, DAG.getUNDEF(MVT::Other));
6107   assert(TF.getNode() != NewResChain.getNode() &&
6108          "A new TF really is required here");
6109
6110   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6111   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6112 }
6113
6114 /// \brief Custom lowers integer to floating point conversions to use
6115 /// the direct move instructions available in ISA 2.07 to avoid the
6116 /// need for load/store combinations.
6117 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6118                                                     SelectionDAG &DAG,
6119                                                     SDLoc dl) const {
6120   assert((Op.getValueType() == MVT::f32 ||
6121           Op.getValueType() == MVT::f64) &&
6122          "Invalid floating point type as target of conversion");
6123   assert(Subtarget.hasFPCVT() &&
6124          "Int to FP conversions with direct moves require FPCVT");
6125   SDValue FP;
6126   SDValue Src = Op.getOperand(0);
6127   bool SinglePrec = Op.getValueType() == MVT::f32;
6128   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6129   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6130   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6131                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6132
6133   if (WordInt) {
6134     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6135                      dl, MVT::f64, Src);
6136     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6137   }
6138   else {
6139     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6140     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6141   }
6142
6143   return FP;
6144 }
6145
6146 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6147                                           SelectionDAG &DAG) const {
6148   SDLoc dl(Op);
6149
6150   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6151     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6152       return SDValue();
6153
6154     SDValue Value = Op.getOperand(0);
6155     // The values are now known to be -1 (false) or 1 (true). To convert this
6156     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6157     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6158     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6159   
6160     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
6161     FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6162                           FPHalfs, FPHalfs, FPHalfs, FPHalfs);
6163   
6164     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6165
6166     if (Op.getValueType() != MVT::v4f64)
6167       Value = DAG.getNode(ISD::FP_ROUND, dl,
6168                           Op.getValueType(), Value,
6169                           DAG.getIntPtrConstant(1, dl));
6170     return Value;
6171   }
6172
6173   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6174   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6175     return SDValue();
6176
6177   if (Op.getOperand(0).getValueType() == MVT::i1)
6178     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6179                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6180                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6181
6182   // If we have direct moves, we can do all the conversion, skip the store/load
6183   // however, without FPCVT we can't do most conversions.
6184   if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT())
6185     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6186
6187   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6188          "UINT_TO_FP is supported only with FPCVT");
6189
6190   // If we have FCFIDS, then use it when converting to single-precision.
6191   // Otherwise, convert to double-precision and then round.
6192   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6193                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6194                                                             : PPCISD::FCFIDS)
6195                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6196                                                             : PPCISD::FCFID);
6197   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6198                   ? MVT::f32
6199                   : MVT::f64;
6200
6201   if (Op.getOperand(0).getValueType() == MVT::i64) {
6202     SDValue SINT = Op.getOperand(0);
6203     // When converting to single-precision, we actually need to convert
6204     // to double-precision first and then round to single-precision.
6205     // To avoid double-rounding effects during that operation, we have
6206     // to prepare the input operand.  Bits that might be truncated when
6207     // converting to double-precision are replaced by a bit that won't
6208     // be lost at this stage, but is below the single-precision rounding
6209     // position.
6210     //
6211     // However, if -enable-unsafe-fp-math is in effect, accept double
6212     // rounding to avoid the extra overhead.
6213     if (Op.getValueType() == MVT::f32 &&
6214         !Subtarget.hasFPCVT() &&
6215         !DAG.getTarget().Options.UnsafeFPMath) {
6216
6217       // Twiddle input to make sure the low 11 bits are zero.  (If this
6218       // is the case, we are guaranteed the value will fit into the 53 bit
6219       // mantissa of an IEEE double-precision value without rounding.)
6220       // If any of those low 11 bits were not zero originally, make sure
6221       // bit 12 (value 2048) is set instead, so that the final rounding
6222       // to single-precision gets the correct result.
6223       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6224                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6225       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6226                           Round, DAG.getConstant(2047, dl, MVT::i64));
6227       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6228       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6229                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6230
6231       // However, we cannot use that value unconditionally: if the magnitude
6232       // of the input value is small, the bit-twiddling we did above might
6233       // end up visibly changing the output.  Fortunately, in that case, we
6234       // don't need to twiddle bits since the original input will convert
6235       // exactly to double-precision floating-point already.  Therefore,
6236       // construct a conditional to use the original value if the top 11
6237       // bits are all sign-bit copies, and use the rounded value computed
6238       // above otherwise.
6239       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6240                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6241       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6242                          Cond, DAG.getConstant(1, dl, MVT::i64));
6243       Cond = DAG.getSetCC(dl, MVT::i32,
6244                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6245
6246       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6247     }
6248
6249     ReuseLoadInfo RLI;
6250     SDValue Bits;
6251
6252     MachineFunction &MF = DAG.getMachineFunction();
6253     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6254       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
6255                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
6256                          RLI.Ranges);
6257       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6258     } else if (Subtarget.hasLFIWAX() &&
6259                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6260       MachineMemOperand *MMO =
6261         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6262                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6263       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6264       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6265                                      DAG.getVTList(MVT::f64, MVT::Other),
6266                                      Ops, MVT::i32, MMO);
6267       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6268     } else if (Subtarget.hasFPCVT() &&
6269                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6270       MachineMemOperand *MMO =
6271         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6272                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6273       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6274       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6275                                      DAG.getVTList(MVT::f64, MVT::Other),
6276                                      Ops, MVT::i32, MMO);
6277       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6278     } else if (((Subtarget.hasLFIWAX() &&
6279                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6280                 (Subtarget.hasFPCVT() &&
6281                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6282                SINT.getOperand(0).getValueType() == MVT::i32) {
6283       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6284       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6285
6286       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6287       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6288
6289       SDValue Store =
6290         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6291                      MachinePointerInfo::getFixedStack(FrameIdx),
6292                      false, false, 0);
6293
6294       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6295              "Expected an i32 store");
6296
6297       RLI.Ptr = FIdx;
6298       RLI.Chain = Store;
6299       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6300       RLI.Alignment = 4;
6301
6302       MachineMemOperand *MMO =
6303         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6304                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6305       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6306       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6307                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6308                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6309                                      Ops, MVT::i32, MMO);
6310     } else
6311       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6312
6313     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6314
6315     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6316       FP = DAG.getNode(ISD::FP_ROUND, dl,
6317                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6318     return FP;
6319   }
6320
6321   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6322          "Unhandled INT_TO_FP type in custom expander!");
6323   // Since we only generate this in 64-bit mode, we can take advantage of
6324   // 64-bit registers.  In particular, sign extend the input value into the
6325   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6326   // then lfd it and fcfid it.
6327   MachineFunction &MF = DAG.getMachineFunction();
6328   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
6329   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6330
6331   SDValue Ld;
6332   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6333     ReuseLoadInfo RLI;
6334     bool ReusingLoad;
6335     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6336                                             DAG))) {
6337       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
6338       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6339
6340       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6341                                    MachinePointerInfo::getFixedStack(FrameIdx),
6342                                    false, false, 0);
6343
6344       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6345              "Expected an i32 store");
6346
6347       RLI.Ptr = FIdx;
6348       RLI.Chain = Store;
6349       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
6350       RLI.Alignment = 4;
6351     }
6352
6353     MachineMemOperand *MMO =
6354       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6355                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6356     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6357     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6358                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6359                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6360                                  Ops, MVT::i32, MMO);
6361     if (ReusingLoad)
6362       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6363   } else {
6364     assert(Subtarget.isPPC64() &&
6365            "i32->FP without LFIWAX supported only on PPC64");
6366
6367     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
6368     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6369
6370     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6371                                 Op.getOperand(0));
6372
6373     // STD the extended value into the stack slot.
6374     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
6375                                  MachinePointerInfo::getFixedStack(FrameIdx),
6376                                  false, false, 0);
6377
6378     // Load the value as a double.
6379     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
6380                      MachinePointerInfo::getFixedStack(FrameIdx),
6381                      false, false, false, 0);
6382   }
6383
6384   // FCFID it and return it.
6385   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6386   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6387     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6388                      DAG.getIntPtrConstant(0, dl));
6389   return FP;
6390 }
6391
6392 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6393                                             SelectionDAG &DAG) const {
6394   SDLoc dl(Op);
6395   /*
6396    The rounding mode is in bits 30:31 of FPSR, and has the following
6397    settings:
6398      00 Round to nearest
6399      01 Round to 0
6400      10 Round to +inf
6401      11 Round to -inf
6402
6403   FLT_ROUNDS, on the other hand, expects the following:
6404     -1 Undefined
6405      0 Round to 0
6406      1 Round to nearest
6407      2 Round to +inf
6408      3 Round to -inf
6409
6410   To perform the conversion, we do:
6411     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
6412   */
6413
6414   MachineFunction &MF = DAG.getMachineFunction();
6415   EVT VT = Op.getValueType();
6416   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6417
6418   // Save FP Control Word to register
6419   EVT NodeTys[] = {
6420     MVT::f64,    // return register
6421     MVT::Glue    // unused in this context
6422   };
6423   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
6424
6425   // Save FP register to stack slot
6426   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6427   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
6428   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
6429                                StackSlot, MachinePointerInfo(), false, false,0);
6430
6431   // Load FP Control Word from low 32 bits of stack slot.
6432   SDValue Four = DAG.getConstant(4, dl, PtrVT);
6433   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
6434   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
6435                             false, false, false, 0);
6436
6437   // Transform as necessary
6438   SDValue CWD1 =
6439     DAG.getNode(ISD::AND, dl, MVT::i32,
6440                 CWD, DAG.getConstant(3, dl, MVT::i32));
6441   SDValue CWD2 =
6442     DAG.getNode(ISD::SRL, dl, MVT::i32,
6443                 DAG.getNode(ISD::AND, dl, MVT::i32,
6444                             DAG.getNode(ISD::XOR, dl, MVT::i32,
6445                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
6446                             DAG.getConstant(3, dl, MVT::i32)),
6447                 DAG.getConstant(1, dl, MVT::i32));
6448
6449   SDValue RetVal =
6450     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
6451
6452   return DAG.getNode((VT.getSizeInBits() < 16 ?
6453                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6454 }
6455
6456 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6457   EVT VT = Op.getValueType();
6458   unsigned BitWidth = VT.getSizeInBits();
6459   SDLoc dl(Op);
6460   assert(Op.getNumOperands() == 3 &&
6461          VT == Op.getOperand(1).getValueType() &&
6462          "Unexpected SHL!");
6463
6464   // Expand into a bunch of logical ops.  Note that these ops
6465   // depend on the PPC behavior for oversized shift amounts.
6466   SDValue Lo = Op.getOperand(0);
6467   SDValue Hi = Op.getOperand(1);
6468   SDValue Amt = Op.getOperand(2);
6469   EVT AmtVT = Amt.getValueType();
6470
6471   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6472                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6473   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
6474   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
6475   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
6476   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6477                              DAG.getConstant(-BitWidth, dl, AmtVT));
6478   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
6479   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6480   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
6481   SDValue OutOps[] = { OutLo, OutHi };
6482   return DAG.getMergeValues(OutOps, dl);
6483 }
6484
6485 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
6486   EVT VT = Op.getValueType();
6487   SDLoc dl(Op);
6488   unsigned BitWidth = VT.getSizeInBits();
6489   assert(Op.getNumOperands() == 3 &&
6490          VT == Op.getOperand(1).getValueType() &&
6491          "Unexpected SRL!");
6492
6493   // Expand into a bunch of logical ops.  Note that these ops
6494   // depend on the PPC behavior for oversized shift amounts.
6495   SDValue Lo = Op.getOperand(0);
6496   SDValue Hi = Op.getOperand(1);
6497   SDValue Amt = Op.getOperand(2);
6498   EVT AmtVT = Amt.getValueType();
6499
6500   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6501                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6502   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6503   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6504   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6505   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6506                              DAG.getConstant(-BitWidth, dl, AmtVT));
6507   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
6508   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
6509   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
6510   SDValue OutOps[] = { OutLo, OutHi };
6511   return DAG.getMergeValues(OutOps, dl);
6512 }
6513
6514 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
6515   SDLoc dl(Op);
6516   EVT VT = Op.getValueType();
6517   unsigned BitWidth = VT.getSizeInBits();
6518   assert(Op.getNumOperands() == 3 &&
6519          VT == Op.getOperand(1).getValueType() &&
6520          "Unexpected SRA!");
6521
6522   // Expand into a bunch of logical ops, followed by a select_cc.
6523   SDValue Lo = Op.getOperand(0);
6524   SDValue Hi = Op.getOperand(1);
6525   SDValue Amt = Op.getOperand(2);
6526   EVT AmtVT = Amt.getValueType();
6527
6528   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
6529                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
6530   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
6531   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
6532   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
6533   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
6534                              DAG.getConstant(-BitWidth, dl, AmtVT));
6535   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
6536   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
6537   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
6538                                   Tmp4, Tmp6, ISD::SETLE);
6539   SDValue OutOps[] = { OutLo, OutHi };
6540   return DAG.getMergeValues(OutOps, dl);
6541 }
6542
6543 //===----------------------------------------------------------------------===//
6544 // Vector related lowering.
6545 //
6546
6547 /// BuildSplatI - Build a canonical splati of Val with an element size of
6548 /// SplatSize.  Cast the result to VT.
6549 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
6550                              SelectionDAG &DAG, SDLoc dl) {
6551   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
6552
6553   static const MVT VTys[] = { // canonical VT to use for each size.
6554     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
6555   };
6556
6557   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
6558
6559   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
6560   if (Val == -1)
6561     SplatSize = 1;
6562
6563   EVT CanonicalVT = VTys[SplatSize-1];
6564
6565   // Build a canonical splat for this value.
6566   SDValue Elt = DAG.getConstant(Val, dl, MVT::i32);
6567   SmallVector<SDValue, 8> Ops;
6568   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
6569   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
6570   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
6571 }
6572
6573 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
6574 /// specified intrinsic ID.
6575 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
6576                                 SelectionDAG &DAG, SDLoc dl,
6577                                 EVT DestVT = MVT::Other) {
6578   if (DestVT == MVT::Other) DestVT = Op.getValueType();
6579   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6580                      DAG.getConstant(IID, dl, MVT::i32), Op);
6581 }
6582
6583 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
6584 /// specified intrinsic ID.
6585 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
6586                                 SelectionDAG &DAG, SDLoc dl,
6587                                 EVT DestVT = MVT::Other) {
6588   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
6589   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6590                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
6591 }
6592
6593 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
6594 /// specified intrinsic ID.
6595 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
6596                                 SDValue Op2, SelectionDAG &DAG,
6597                                 SDLoc dl, EVT DestVT = MVT::Other) {
6598   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
6599   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
6600                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
6601 }
6602
6603
6604 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
6605 /// amount.  The result has the specified value type.
6606 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
6607                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
6608   // Force LHS/RHS to be the right type.
6609   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6610   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6611
6612   int Ops[16];
6613   for (unsigned i = 0; i != 16; ++i)
6614     Ops[i] = i + Amt;
6615   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6616   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6617 }
6618
6619 // If this is a case we can't handle, return null and let the default
6620 // expansion code take care of it.  If we CAN select this case, and if it
6621 // selects to a single instruction, return Op.  Otherwise, if we can codegen
6622 // this case more efficiently than a constant pool load, lower it to the
6623 // sequence of ops that should be used.
6624 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6625                                              SelectionDAG &DAG) const {
6626   SDLoc dl(Op);
6627   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6628   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6629
6630   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
6631     // We first build an i32 vector, load it into a QPX register,
6632     // then convert it to a floating-point vector and compare it
6633     // to a zero vector to get the boolean result.
6634     MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6635     int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6636     MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
6637     EVT PtrVT = getPointerTy();
6638     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6639
6640     assert(BVN->getNumOperands() == 4 &&
6641       "BUILD_VECTOR for v4i1 does not have 4 operands");
6642
6643     bool IsConst = true;
6644     for (unsigned i = 0; i < 4; ++i) {
6645       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6646       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
6647         IsConst = false;
6648         break;
6649       }
6650     }
6651
6652     if (IsConst) {
6653       Constant *One =
6654         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
6655       Constant *NegOne =
6656         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
6657
6658       SmallVector<Constant*, 4> CV(4, NegOne);
6659       for (unsigned i = 0; i < 4; ++i) {
6660         if (BVN->getOperand(i).getOpcode() == ISD::UNDEF)
6661           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
6662         else if (cast<ConstantSDNode>(BVN->getOperand(i))->
6663                    getConstantIntValue()->isZero())
6664           continue;
6665         else
6666           CV[i] = One;
6667       }
6668
6669       Constant *CP = ConstantVector::get(CV);
6670       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(),
6671                       16 /* alignment */);
6672  
6673       SmallVector<SDValue, 2> Ops;
6674       Ops.push_back(DAG.getEntryNode());
6675       Ops.push_back(CPIdx);
6676
6677       SmallVector<EVT, 2> ValueVTs;
6678       ValueVTs.push_back(MVT::v4i1);
6679       ValueVTs.push_back(MVT::Other); // chain
6680       SDVTList VTs = DAG.getVTList(ValueVTs);
6681
6682       return DAG.getMemIntrinsicNode(PPCISD::QVLFSb,
6683         dl, VTs, Ops, MVT::v4f32,
6684         MachinePointerInfo::getConstantPool());
6685     }
6686
6687     SmallVector<SDValue, 4> Stores;
6688     for (unsigned i = 0; i < 4; ++i) {
6689       if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6690
6691       unsigned Offset = 4*i;
6692       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
6693       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
6694
6695       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
6696       if (StoreSize > 4) {
6697         Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
6698                                            BVN->getOperand(i), Idx,
6699                                            PtrInfo.getWithOffset(Offset),
6700                                            MVT::i32, false, false, 0));
6701       } else {
6702         SDValue StoreValue = BVN->getOperand(i);
6703         if (StoreSize < 4)
6704           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
6705
6706         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
6707                                       StoreValue, Idx,
6708                                       PtrInfo.getWithOffset(Offset),
6709                                       false, false, 0));
6710       }
6711     }
6712
6713     SDValue StoreChain;
6714     if (!Stores.empty())
6715       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6716     else
6717       StoreChain = DAG.getEntryNode();
6718
6719     // Now load from v4i32 into the QPX register; this will extend it to
6720     // v4i64 but not yet convert it to a floating point. Nevertheless, this
6721     // is typed as v4f64 because the QPX register integer states are not
6722     // explicitly represented.
6723
6724     SmallVector<SDValue, 2> Ops;
6725     Ops.push_back(StoreChain);
6726     Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32));
6727     Ops.push_back(FIdx);
6728
6729     SmallVector<EVT, 2> ValueVTs;
6730     ValueVTs.push_back(MVT::v4f64);
6731     ValueVTs.push_back(MVT::Other); // chain
6732     SDVTList VTs = DAG.getVTList(ValueVTs);
6733
6734     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
6735       dl, VTs, Ops, MVT::v4i32, PtrInfo);
6736     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
6737       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
6738       LoadedVect);
6739
6740     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64);
6741     FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
6742                           FPZeros, FPZeros, FPZeros, FPZeros);
6743
6744     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
6745   }
6746
6747   // All other QPX vectors are handled by generic code.
6748   if (Subtarget.hasQPX())
6749     return SDValue();
6750
6751   // Check if this is a splat of a constant value.
6752   APInt APSplatBits, APSplatUndef;
6753   unsigned SplatBitSize;
6754   bool HasAnyUndefs;
6755   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6756                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
6757       SplatBitSize > 32)
6758     return SDValue();
6759
6760   unsigned SplatBits = APSplatBits.getZExtValue();
6761   unsigned SplatUndef = APSplatUndef.getZExtValue();
6762   unsigned SplatSize = SplatBitSize / 8;
6763
6764   // First, handle single instruction cases.
6765
6766   // All zeros?
6767   if (SplatBits == 0) {
6768     // Canonicalize all zero vectors to be v4i32.
6769     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6770       SDValue Z = DAG.getConstant(0, dl, MVT::i32);
6771       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6772       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6773     }
6774     return Op;
6775   }
6776
6777   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6778   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6779                     (32-SplatBitSize));
6780   if (SextVal >= -16 && SextVal <= 15)
6781     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6782
6783
6784   // Two instruction sequences.
6785
6786   // If this value is in the range [-32,30] and is even, use:
6787   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6788   // If this value is in the range [17,31] and is odd, use:
6789   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6790   // If this value is in the range [-31,-17] and is odd, use:
6791   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6792   // Note the last two are three-instruction sequences.
6793   if (SextVal >= -32 && SextVal <= 31) {
6794     // To avoid having these optimizations undone by constant folding,
6795     // we convert to a pseudo that will be expanded later into one of
6796     // the above forms.
6797     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
6798     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6799               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6800     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
6801     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6802     if (VT == Op.getValueType())
6803       return RetVal;
6804     else
6805       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6806   }
6807
6808   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6809   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6810   // for fneg/fabs.
6811   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6812     // Make -1 and vspltisw -1:
6813     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6814
6815     // Make the VSLW intrinsic, computing 0x8000_0000.
6816     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6817                                    OnesV, DAG, dl);
6818
6819     // xor by OnesV to invert it.
6820     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6821     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6822   }
6823
6824   // Check to see if this is a wide variety of vsplti*, binop self cases.
6825   static const signed char SplatCsts[] = {
6826     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6827     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6828   };
6829
6830   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6831     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6832     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6833     int i = SplatCsts[idx];
6834
6835     // Figure out what shift amount will be used by altivec if shifted by i in
6836     // this splat size.
6837     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6838
6839     // vsplti + shl self.
6840     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6841       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6842       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6843         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6844         Intrinsic::ppc_altivec_vslw
6845       };
6846       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6847       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6848     }
6849
6850     // vsplti + srl self.
6851     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6852       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6853       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6854         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6855         Intrinsic::ppc_altivec_vsrw
6856       };
6857       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6858       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6859     }
6860
6861     // vsplti + sra self.
6862     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6863       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6864       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6865         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6866         Intrinsic::ppc_altivec_vsraw
6867       };
6868       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6869       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6870     }
6871
6872     // vsplti + rol self.
6873     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6874                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6875       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6876       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6877         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6878         Intrinsic::ppc_altivec_vrlw
6879       };
6880       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6881       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6882     }
6883
6884     // t = vsplti c, result = vsldoi t, t, 1
6885     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6886       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6887       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6888     }
6889     // t = vsplti c, result = vsldoi t, t, 2
6890     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6891       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6892       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6893     }
6894     // t = vsplti c, result = vsldoi t, t, 3
6895     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6896       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6897       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6898     }
6899   }
6900
6901   return SDValue();
6902 }
6903
6904 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6905 /// the specified operations to build the shuffle.
6906 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6907                                       SDValue RHS, SelectionDAG &DAG,
6908                                       SDLoc dl) {
6909   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6910   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6911   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6912
6913   enum {
6914     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6915     OP_VMRGHW,
6916     OP_VMRGLW,
6917     OP_VSPLTISW0,
6918     OP_VSPLTISW1,
6919     OP_VSPLTISW2,
6920     OP_VSPLTISW3,
6921     OP_VSLDOI4,
6922     OP_VSLDOI8,
6923     OP_VSLDOI12
6924   };
6925
6926   if (OpNum == OP_COPY) {
6927     if (LHSID == (1*9+2)*9+3) return LHS;
6928     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6929     return RHS;
6930   }
6931
6932   SDValue OpLHS, OpRHS;
6933   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6934   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6935
6936   int ShufIdxs[16];
6937   switch (OpNum) {
6938   default: llvm_unreachable("Unknown i32 permute!");
6939   case OP_VMRGHW:
6940     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6941     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6942     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6943     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6944     break;
6945   case OP_VMRGLW:
6946     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6947     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6948     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6949     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6950     break;
6951   case OP_VSPLTISW0:
6952     for (unsigned i = 0; i != 16; ++i)
6953       ShufIdxs[i] = (i&3)+0;
6954     break;
6955   case OP_VSPLTISW1:
6956     for (unsigned i = 0; i != 16; ++i)
6957       ShufIdxs[i] = (i&3)+4;
6958     break;
6959   case OP_VSPLTISW2:
6960     for (unsigned i = 0; i != 16; ++i)
6961       ShufIdxs[i] = (i&3)+8;
6962     break;
6963   case OP_VSPLTISW3:
6964     for (unsigned i = 0; i != 16; ++i)
6965       ShufIdxs[i] = (i&3)+12;
6966     break;
6967   case OP_VSLDOI4:
6968     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6969   case OP_VSLDOI8:
6970     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6971   case OP_VSLDOI12:
6972     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6973   }
6974   EVT VT = OpLHS.getValueType();
6975   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6976   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6977   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6978   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6979 }
6980
6981 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6982 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6983 /// return the code it can be lowered into.  Worst case, it can always be
6984 /// lowered into a vperm.
6985 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6986                                                SelectionDAG &DAG) const {
6987   SDLoc dl(Op);
6988   SDValue V1 = Op.getOperand(0);
6989   SDValue V2 = Op.getOperand(1);
6990   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6991   EVT VT = Op.getValueType();
6992   bool isLittleEndian = Subtarget.isLittleEndian();
6993
6994   if (Subtarget.hasQPX()) {
6995     if (VT.getVectorNumElements() != 4)
6996       return SDValue();
6997
6998     if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6999
7000     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7001     if (AlignIdx != -1) {
7002       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7003                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7004     } else if (SVOp->isSplat()) {
7005       int SplatIdx = SVOp->getSplatIndex();
7006       if (SplatIdx >= 4) {
7007         std::swap(V1, V2);
7008         SplatIdx -= 4;
7009       }
7010
7011       // FIXME: If SplatIdx == 0 and the input came from a load, then there is
7012       // nothing to do.
7013
7014       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7015                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7016     }
7017
7018     // Lower this into a qvgpci/qvfperm pair.
7019
7020     // Compute the qvgpci literal
7021     unsigned idx = 0;
7022     for (unsigned i = 0; i < 4; ++i) {
7023       int m = SVOp->getMaskElt(i);
7024       unsigned mm = m >= 0 ? (unsigned) m : i;
7025       idx |= mm << (3-i)*3;
7026     }
7027
7028     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7029                              DAG.getConstant(idx, dl, MVT::i32));
7030     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7031   }
7032
7033   // Cases that are handled by instructions that take permute immediates
7034   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7035   // selected by the instruction selector.
7036   if (V2.getOpcode() == ISD::UNDEF) {
7037     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7038         PPC::isSplatShuffleMask(SVOp, 2) ||
7039         PPC::isSplatShuffleMask(SVOp, 4) ||
7040         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7041         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7042         PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7043         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7044         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7045         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7046         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7047         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7048         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7049         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
7050       return Op;
7051     }
7052   }
7053
7054   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7055   // and produce a fixed permutation.  If any of these match, do not lower to
7056   // VPERM.
7057   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7058   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7059       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7060       PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7061       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7062       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7063       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7064       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7065       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7066       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7067       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
7068     return Op;
7069
7070   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7071   // perfect shuffle table to emit an optimal matching sequence.
7072   ArrayRef<int> PermMask = SVOp->getMask();
7073
7074   unsigned PFIndexes[4];
7075   bool isFourElementShuffle = true;
7076   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7077     unsigned EltNo = 8;   // Start out undef.
7078     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7079       if (PermMask[i*4+j] < 0)
7080         continue;   // Undef, ignore it.
7081
7082       unsigned ByteSource = PermMask[i*4+j];
7083       if ((ByteSource & 3) != j) {
7084         isFourElementShuffle = false;
7085         break;
7086       }
7087
7088       if (EltNo == 8) {
7089         EltNo = ByteSource/4;
7090       } else if (EltNo != ByteSource/4) {
7091         isFourElementShuffle = false;
7092         break;
7093       }
7094     }
7095     PFIndexes[i] = EltNo;
7096   }
7097
7098   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7099   // perfect shuffle vector to determine if it is cost effective to do this as
7100   // discrete instructions, or whether we should use a vperm.
7101   // For now, we skip this for little endian until such time as we have a
7102   // little-endian perfect shuffle table.
7103   if (isFourElementShuffle && !isLittleEndian) {
7104     // Compute the index in the perfect shuffle table.
7105     unsigned PFTableIndex =
7106       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7107
7108     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7109     unsigned Cost  = (PFEntry >> 30);
7110
7111     // Determining when to avoid vperm is tricky.  Many things affect the cost
7112     // of vperm, particularly how many times the perm mask needs to be computed.
7113     // For example, if the perm mask can be hoisted out of a loop or is already
7114     // used (perhaps because there are multiple permutes with the same shuffle
7115     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7116     // the loop requires an extra register.
7117     //
7118     // As a compromise, we only emit discrete instructions if the shuffle can be
7119     // generated in 3 or fewer operations.  When we have loop information
7120     // available, if this block is within a loop, we should avoid using vperm
7121     // for 3-operation perms and use a constant pool load instead.
7122     if (Cost < 3)
7123       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7124   }
7125
7126   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7127   // vector that will get spilled to the constant pool.
7128   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
7129
7130   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7131   // that it is in input element units, not in bytes.  Convert now.
7132
7133   // For little endian, the order of the input vectors is reversed, and
7134   // the permutation mask is complemented with respect to 31.  This is
7135   // necessary to produce proper semantics with the big-endian-biased vperm
7136   // instruction.
7137   EVT EltVT = V1.getValueType().getVectorElementType();
7138   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7139
7140   SmallVector<SDValue, 16> ResultMask;
7141   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7142     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7143
7144     for (unsigned j = 0; j != BytesPerElement; ++j)
7145       if (isLittleEndian)
7146         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7147                                              dl, MVT::i32));
7148       else
7149         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7150                                              MVT::i32));
7151   }
7152
7153   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
7154                                   ResultMask);
7155   if (isLittleEndian)
7156     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7157                        V2, V1, VPermMask);
7158   else
7159     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7160                        V1, V2, VPermMask);
7161 }
7162
7163 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
7164 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
7165 /// information about the intrinsic.
7166 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
7167                                   bool &isDot, const PPCSubtarget &Subtarget) {
7168   unsigned IntrinsicID =
7169     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7170   CompareOpc = -1;
7171   isDot = false;
7172   switch (IntrinsicID) {
7173   default: return false;
7174     // Comparison predicates.
7175   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
7176   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
7177   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
7178   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
7179   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
7180   case Intrinsic::ppc_altivec_vcmpequd_p: 
7181     if (Subtarget.hasP8Altivec()) {
7182       CompareOpc = 199; 
7183       isDot = 1; 
7184     }
7185     else 
7186       return false;
7187
7188     break;
7189   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
7190   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
7191   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
7192   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
7193   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
7194   case Intrinsic::ppc_altivec_vcmpgtsd_p: 
7195     if (Subtarget.hasP8Altivec()) {
7196       CompareOpc = 967; 
7197       isDot = 1; 
7198     }
7199     else 
7200       return false;
7201
7202     break;
7203   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
7204   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
7205   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
7206   case Intrinsic::ppc_altivec_vcmpgtud_p: 
7207     if (Subtarget.hasP8Altivec()) {
7208       CompareOpc = 711; 
7209       isDot = 1; 
7210     }
7211     else 
7212       return false;
7213
7214     break;
7215       
7216     // Normal Comparisons.
7217   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
7218   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
7219   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
7220   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
7221   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
7222   case Intrinsic::ppc_altivec_vcmpequd:
7223     if (Subtarget.hasP8Altivec()) {
7224       CompareOpc = 199; 
7225       isDot = 0; 
7226     }
7227     else
7228       return false;
7229
7230     break;
7231   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
7232   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
7233   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
7234   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
7235   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
7236   case Intrinsic::ppc_altivec_vcmpgtsd:   
7237     if (Subtarget.hasP8Altivec()) {
7238       CompareOpc = 967; 
7239       isDot = 0; 
7240     }
7241     else
7242       return false;
7243
7244     break;
7245   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
7246   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
7247   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
7248   case Intrinsic::ppc_altivec_vcmpgtud:   
7249     if (Subtarget.hasP8Altivec()) {
7250       CompareOpc = 711; 
7251       isDot = 0; 
7252     }
7253     else
7254       return false;
7255
7256     break;
7257   }
7258   return true;
7259 }
7260
7261 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
7262 /// lower, do it, otherwise return null.
7263 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7264                                                    SelectionDAG &DAG) const {
7265   // If this is a lowered altivec predicate compare, CompareOpc is set to the
7266   // opcode number of the comparison.
7267   SDLoc dl(Op);
7268   int CompareOpc;
7269   bool isDot;
7270   if (!getAltivecCompareInfo(Op, CompareOpc, isDot, Subtarget))
7271     return SDValue();    // Don't custom lower most intrinsics.
7272
7273   // If this is a non-dot comparison, make the VCMP node and we are done.
7274   if (!isDot) {
7275     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
7276                               Op.getOperand(1), Op.getOperand(2),
7277                               DAG.getConstant(CompareOpc, dl, MVT::i32));
7278     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
7279   }
7280
7281   // Create the PPCISD altivec 'dot' comparison node.
7282   SDValue Ops[] = {
7283     Op.getOperand(2),  // LHS
7284     Op.getOperand(3),  // RHS
7285     DAG.getConstant(CompareOpc, dl, MVT::i32)
7286   };
7287   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
7288   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
7289
7290   // Now that we have the comparison, emit a copy from the CR to a GPR.
7291   // This is flagged to the above dot comparison.
7292   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
7293                                 DAG.getRegister(PPC::CR6, MVT::i32),
7294                                 CompNode.getValue(1));
7295
7296   // Unpack the result based on how the target uses it.
7297   unsigned BitNo;   // Bit # of CR6.
7298   bool InvertBit;   // Invert result?
7299   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
7300   default:  // Can't happen, don't crash on invalid number though.
7301   case 0:   // Return the value of the EQ bit of CR6.
7302     BitNo = 0; InvertBit = false;
7303     break;
7304   case 1:   // Return the inverted value of the EQ bit of CR6.
7305     BitNo = 0; InvertBit = true;
7306     break;
7307   case 2:   // Return the value of the LT bit of CR6.
7308     BitNo = 2; InvertBit = false;
7309     break;
7310   case 3:   // Return the inverted value of the LT bit of CR6.
7311     BitNo = 2; InvertBit = true;
7312     break;
7313   }
7314
7315   // Shift the bit into the low position.
7316   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
7317                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
7318   // Isolate the bit.
7319   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
7320                       DAG.getConstant(1, dl, MVT::i32));
7321
7322   // If we are supposed to, toggle the bit.
7323   if (InvertBit)
7324     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
7325                         DAG.getConstant(1, dl, MVT::i32));
7326   return Flags;
7327 }
7328
7329 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
7330                                                   SelectionDAG &DAG) const {
7331   SDLoc dl(Op);
7332   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
7333   // instructions), but for smaller types, we need to first extend up to v2i32
7334   // before doing going farther.
7335   if (Op.getValueType() == MVT::v2i64) {
7336     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
7337     if (ExtVT != MVT::v2i32) {
7338       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
7339       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
7340                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
7341                                         ExtVT.getVectorElementType(), 4)));
7342       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
7343       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
7344                        DAG.getValueType(MVT::v2i32));
7345     }
7346
7347     return Op;
7348   }
7349
7350   return SDValue();
7351 }
7352
7353 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
7354                                                    SelectionDAG &DAG) const {
7355   SDLoc dl(Op);
7356   // Create a stack slot that is 16-byte aligned.
7357   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7358   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7359   EVT PtrVT = getPointerTy();
7360   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7361
7362   // Store the input value into Value#0 of the stack slot.
7363   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
7364                                Op.getOperand(0), FIdx, MachinePointerInfo(),
7365                                false, false, 0);
7366   // Load it out.
7367   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
7368                      false, false, false, 0);
7369 }
7370
7371 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7372                                                    SelectionDAG &DAG) const {
7373   SDLoc dl(Op);
7374   SDNode *N = Op.getNode();
7375
7376   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
7377          "Unknown extract_vector_elt type");
7378
7379   SDValue Value = N->getOperand(0);
7380
7381   // The first part of this is like the store lowering except that we don't
7382   // need to track the chain.
7383
7384   // The values are now known to be -1 (false) or 1 (true). To convert this
7385   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7386   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7387   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7388
7389   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7390   // understand how to form the extending load.
7391   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7392   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7393                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7394
7395   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7396
7397   // Now convert to an integer and store.
7398   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7399     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7400     Value);
7401
7402   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7403   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7404   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7405   EVT PtrVT = getPointerTy();
7406   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7407
7408   SDValue StoreChain = DAG.getEntryNode();
7409   SmallVector<SDValue, 2> Ops;
7410   Ops.push_back(StoreChain);
7411   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7412   Ops.push_back(Value);
7413   Ops.push_back(FIdx);
7414
7415   SmallVector<EVT, 2> ValueVTs;
7416   ValueVTs.push_back(MVT::Other); // chain
7417   SDVTList VTs = DAG.getVTList(ValueVTs);
7418
7419   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7420     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7421
7422   // Extract the value requested.
7423   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7424   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7425   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7426
7427   SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7428                                PtrInfo.getWithOffset(Offset),
7429                                false, false, false, 0);
7430
7431   if (!Subtarget.useCRBits())
7432     return IntVal;
7433
7434   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
7435 }
7436
7437 /// Lowering for QPX v4i1 loads
7438 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
7439                                            SelectionDAG &DAG) const {
7440   SDLoc dl(Op);
7441   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
7442   SDValue LoadChain = LN->getChain();
7443   SDValue BasePtr = LN->getBasePtr();
7444
7445   if (Op.getValueType() == MVT::v4f64 ||
7446       Op.getValueType() == MVT::v4f32) {
7447     EVT MemVT = LN->getMemoryVT();
7448     unsigned Alignment = LN->getAlignment();
7449
7450     // If this load is properly aligned, then it is legal.
7451     if (Alignment >= MemVT.getStoreSize())
7452       return Op;
7453
7454     EVT ScalarVT = Op.getValueType().getScalarType(),
7455         ScalarMemVT = MemVT.getScalarType();
7456     unsigned Stride = ScalarMemVT.getStoreSize();
7457
7458     SmallVector<SDValue, 8> Vals, LoadChains;
7459     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7460       SDValue Load;
7461       if (ScalarVT != ScalarMemVT)
7462         Load =
7463           DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
7464                          BasePtr,
7465                          LN->getPointerInfo().getWithOffset(Idx*Stride),
7466                          ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(),
7467                          LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7468                          LN->getAAInfo());
7469       else
7470         Load =
7471           DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
7472                        LN->getPointerInfo().getWithOffset(Idx*Stride),
7473                        LN->isVolatile(), LN->isNonTemporal(),
7474                        LN->isInvariant(), MinAlign(Alignment, Idx*Stride),
7475                        LN->getAAInfo());
7476
7477       if (Idx == 0 && LN->isIndexed()) {
7478         assert(LN->getAddressingMode() == ISD::PRE_INC &&
7479                "Unknown addressing mode on vector load");
7480         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
7481                                   LN->getAddressingMode());
7482       }
7483
7484       Vals.push_back(Load);
7485       LoadChains.push_back(Load.getValue(1));
7486
7487       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7488                             DAG.getConstant(Stride, dl,
7489                                             BasePtr.getValueType()));
7490     }
7491
7492     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7493     SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
7494                                 Op.getValueType(), Vals);
7495
7496     if (LN->isIndexed()) {
7497       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
7498       return DAG.getMergeValues(RetOps, dl);
7499     }
7500
7501     SDValue RetOps[] = { Value, TF };
7502     return DAG.getMergeValues(RetOps, dl);
7503   }
7504
7505   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
7506   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
7507
7508   // To lower v4i1 from a byte array, we load the byte elements of the
7509   // vector and then reuse the BUILD_VECTOR logic.
7510
7511   SmallVector<SDValue, 4> VectElmts, VectElmtChains;
7512   for (unsigned i = 0; i < 4; ++i) {
7513     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7514     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7515
7516     VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD,
7517                         dl, MVT::i32, LoadChain, Idx,
7518                         LN->getPointerInfo().getWithOffset(i),
7519                         MVT::i8 /* memory type */,
7520                         LN->isVolatile(), LN->isNonTemporal(),
7521                         LN->isInvariant(),
7522                         1 /* alignment */, LN->getAAInfo()));
7523     VectElmtChains.push_back(VectElmts[i].getValue(1));
7524   }
7525
7526   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
7527   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts);
7528
7529   SDValue RVals[] = { Value, LoadChain };
7530   return DAG.getMergeValues(RVals, dl);
7531 }
7532
7533 /// Lowering for QPX v4i1 stores
7534 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
7535                                             SelectionDAG &DAG) const {
7536   SDLoc dl(Op);
7537   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
7538   SDValue StoreChain = SN->getChain();
7539   SDValue BasePtr = SN->getBasePtr();
7540   SDValue Value = SN->getValue();
7541
7542   if (Value.getValueType() == MVT::v4f64 ||
7543       Value.getValueType() == MVT::v4f32) {
7544     EVT MemVT = SN->getMemoryVT();
7545     unsigned Alignment = SN->getAlignment();
7546
7547     // If this store is properly aligned, then it is legal.
7548     if (Alignment >= MemVT.getStoreSize())
7549       return Op;
7550
7551     EVT ScalarVT = Value.getValueType().getScalarType(),
7552         ScalarMemVT = MemVT.getScalarType();
7553     unsigned Stride = ScalarMemVT.getStoreSize();
7554
7555     SmallVector<SDValue, 8> Stores;
7556     for (unsigned Idx = 0; Idx < 4; ++Idx) {
7557       SDValue Ex =
7558         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
7559                     DAG.getConstant(Idx, dl, getVectorIdxTy()));
7560       SDValue Store;
7561       if (ScalarVT != ScalarMemVT)
7562         Store =
7563           DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
7564                             SN->getPointerInfo().getWithOffset(Idx*Stride),
7565                             ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(),
7566                             MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7567       else
7568         Store =
7569           DAG.getStore(StoreChain, dl, Ex, BasePtr,
7570                        SN->getPointerInfo().getWithOffset(Idx*Stride),
7571                        SN->isVolatile(), SN->isNonTemporal(),
7572                        MinAlign(Alignment, Idx*Stride), SN->getAAInfo());
7573
7574       if (Idx == 0 && SN->isIndexed()) {
7575         assert(SN->getAddressingMode() == ISD::PRE_INC &&
7576                "Unknown addressing mode on vector store");
7577         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
7578                                     SN->getAddressingMode());
7579       }
7580
7581       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
7582                             DAG.getConstant(Stride, dl,
7583                                             BasePtr.getValueType()));
7584       Stores.push_back(Store);
7585     }
7586
7587     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7588
7589     if (SN->isIndexed()) {
7590       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
7591       return DAG.getMergeValues(RetOps, dl);
7592     }
7593
7594     return TF;
7595   }
7596
7597   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
7598   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
7599
7600   // The values are now known to be -1 (false) or 1 (true). To convert this
7601   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7602   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7603   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7604
7605   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
7606   // understand how to form the extending load.
7607   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64);
7608   FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64,
7609                         FPHalfs, FPHalfs, FPHalfs, FPHalfs);
7610
7611   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); 
7612
7613   // Now convert to an integer and store.
7614   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7615     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
7616     Value);
7617
7618   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
7619   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
7620   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FrameIdx);
7621   EVT PtrVT = getPointerTy();
7622   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7623
7624   SmallVector<SDValue, 2> Ops;
7625   Ops.push_back(StoreChain);
7626   Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32));
7627   Ops.push_back(Value);
7628   Ops.push_back(FIdx);
7629
7630   SmallVector<EVT, 2> ValueVTs;
7631   ValueVTs.push_back(MVT::Other); // chain
7632   SDVTList VTs = DAG.getVTList(ValueVTs);
7633
7634   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
7635     dl, VTs, Ops, MVT::v4i32, PtrInfo);
7636
7637   // Move data into the byte array.
7638   SmallVector<SDValue, 4> Loads, LoadChains;
7639   for (unsigned i = 0; i < 4; ++i) {
7640     unsigned Offset = 4*i;
7641     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7642     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7643
7644     Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
7645                                    PtrInfo.getWithOffset(Offset),
7646                                    false, false, false, 0));
7647     LoadChains.push_back(Loads[i].getValue(1));
7648   }
7649
7650   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7651
7652   SmallVector<SDValue, 4> Stores;
7653   for (unsigned i = 0; i < 4; ++i) {
7654     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
7655     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
7656
7657     Stores.push_back(DAG.getTruncStore(StoreChain, dl, Loads[i], Idx,
7658                                        SN->getPointerInfo().getWithOffset(i),
7659                                        MVT::i8 /* memory type */,
7660                                        SN->isNonTemporal(), SN->isVolatile(), 
7661                                        1 /* alignment */, SN->getAAInfo()));
7662   }
7663
7664   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7665
7666   return StoreChain;
7667 }
7668
7669 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
7670   SDLoc dl(Op);
7671   if (Op.getValueType() == MVT::v4i32) {
7672     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7673
7674     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
7675     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
7676
7677     SDValue RHSSwap =   // = vrlw RHS, 16
7678       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
7679
7680     // Shrinkify inputs to v8i16.
7681     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
7682     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
7683     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
7684
7685     // Low parts multiplied together, generating 32-bit results (we ignore the
7686     // top parts).
7687     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
7688                                         LHS, RHS, DAG, dl, MVT::v4i32);
7689
7690     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
7691                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
7692     // Shift the high parts up 16 bits.
7693     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
7694                               Neg16, DAG, dl);
7695     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
7696   } else if (Op.getValueType() == MVT::v8i16) {
7697     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7698
7699     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
7700
7701     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
7702                             LHS, RHS, Zero, DAG, dl);
7703   } else if (Op.getValueType() == MVT::v16i8) {
7704     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7705     bool isLittleEndian = Subtarget.isLittleEndian();
7706
7707     // Multiply the even 8-bit parts, producing 16-bit sums.
7708     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
7709                                            LHS, RHS, DAG, dl, MVT::v8i16);
7710     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
7711
7712     // Multiply the odd 8-bit parts, producing 16-bit sums.
7713     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
7714                                           LHS, RHS, DAG, dl, MVT::v8i16);
7715     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
7716
7717     // Merge the results together.  Because vmuleub and vmuloub are
7718     // instructions with a big-endian bias, we must reverse the
7719     // element numbering and reverse the meaning of "odd" and "even"
7720     // when generating little endian code.
7721     int Ops[16];
7722     for (unsigned i = 0; i != 8; ++i) {
7723       if (isLittleEndian) {
7724         Ops[i*2  ] = 2*i;
7725         Ops[i*2+1] = 2*i+16;
7726       } else {
7727         Ops[i*2  ] = 2*i+1;
7728         Ops[i*2+1] = 2*i+1+16;
7729       }
7730     }
7731     if (isLittleEndian)
7732       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
7733     else
7734       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
7735   } else {
7736     llvm_unreachable("Unknown mul to lower!");
7737   }
7738 }
7739
7740 /// LowerOperation - Provide custom lowering hooks for some operations.
7741 ///
7742 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7743   switch (Op.getOpcode()) {
7744   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
7745   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7746   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7747   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7748   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7749   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7750   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7751   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
7752   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
7753   case ISD::VASTART:
7754     return LowerVASTART(Op, DAG, Subtarget);
7755
7756   case ISD::VAARG:
7757     return LowerVAARG(Op, DAG, Subtarget);
7758
7759   case ISD::VACOPY:
7760     return LowerVACOPY(Op, DAG, Subtarget);
7761
7762   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
7763   case ISD::DYNAMIC_STACKALLOC:
7764     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
7765
7766   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
7767   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
7768
7769   case ISD::LOAD:               return LowerLOAD(Op, DAG);
7770   case ISD::STORE:              return LowerSTORE(Op, DAG);
7771   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
7772   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
7773   case ISD::FP_TO_UINT:
7774   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
7775                                                       SDLoc(Op));
7776   case ISD::UINT_TO_FP:
7777   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
7778   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7779
7780   // Lower 64-bit shifts.
7781   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
7782   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
7783   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
7784
7785   // Vector-related lowering.
7786   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7787   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7788   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7789   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7790   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
7791   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7792   case ISD::MUL:                return LowerMUL(Op, DAG);
7793
7794   // For counter-based loop handling.
7795   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
7796
7797   // Frame & Return address.
7798   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7799   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7800   }
7801 }
7802
7803 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
7804                                            SmallVectorImpl<SDValue>&Results,
7805                                            SelectionDAG &DAG) const {
7806   SDLoc dl(N);
7807   switch (N->getOpcode()) {
7808   default:
7809     llvm_unreachable("Do not know how to custom type legalize this operation!");
7810   case ISD::READCYCLECOUNTER: {
7811     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7812     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
7813
7814     Results.push_back(RTB);
7815     Results.push_back(RTB.getValue(1));
7816     Results.push_back(RTB.getValue(2));
7817     break;
7818   }
7819   case ISD::INTRINSIC_W_CHAIN: {
7820     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
7821         Intrinsic::ppc_is_decremented_ctr_nonzero)
7822       break;
7823
7824     assert(N->getValueType(0) == MVT::i1 &&
7825            "Unexpected result type for CTR decrement intrinsic");
7826     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
7827     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
7828     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
7829                                  N->getOperand(1)); 
7830
7831     Results.push_back(NewInt);
7832     Results.push_back(NewInt.getValue(1));
7833     break;
7834   }
7835   case ISD::VAARG: {
7836     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
7837       return;
7838
7839     EVT VT = N->getValueType(0);
7840
7841     if (VT == MVT::i64) {
7842       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
7843
7844       Results.push_back(NewNode);
7845       Results.push_back(NewNode.getValue(1));
7846     }
7847     return;
7848   }
7849   case ISD::FP_ROUND_INREG: {
7850     assert(N->getValueType(0) == MVT::ppcf128);
7851     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
7852     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7853                              MVT::f64, N->getOperand(0),
7854                              DAG.getIntPtrConstant(0, dl));
7855     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7856                              MVT::f64, N->getOperand(0),
7857                              DAG.getIntPtrConstant(1, dl));
7858
7859     // Add the two halves of the long double in round-to-zero mode.
7860     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7861
7862     // We know the low half is about to be thrown away, so just use something
7863     // convenient.
7864     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
7865                                 FPreg, FPreg));
7866     return;
7867   }
7868   case ISD::FP_TO_SINT:
7869   case ISD::FP_TO_UINT:
7870     // LowerFP_TO_INT() can only handle f32 and f64.
7871     if (N->getOperand(0).getValueType() == MVT::ppcf128)
7872       return;
7873     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
7874     return;
7875   }
7876 }
7877
7878
7879 //===----------------------------------------------------------------------===//
7880 //  Other Lowering Code
7881 //===----------------------------------------------------------------------===//
7882
7883 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
7884   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7885   Function *Func = Intrinsic::getDeclaration(M, Id);
7886   return Builder.CreateCall(Func, {});
7887 }
7888
7889 // The mappings for emitLeading/TrailingFence is taken from
7890 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
7891 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
7892                                          AtomicOrdering Ord, bool IsStore,
7893                                          bool IsLoad) const {
7894   if (Ord == SequentiallyConsistent)
7895     return callIntrinsic(Builder, Intrinsic::ppc_sync);
7896   if (isAtLeastRelease(Ord))
7897     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7898   return nullptr;
7899 }
7900
7901 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
7902                                           AtomicOrdering Ord, bool IsStore,
7903                                           bool IsLoad) const {
7904   if (IsLoad && isAtLeastAcquire(Ord))
7905     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
7906   // FIXME: this is too conservative, a dependent branch + isync is enough.
7907   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
7908   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
7909   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
7910   return nullptr;
7911 }
7912
7913 MachineBasicBlock *
7914 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
7915                                     unsigned AtomicSize,
7916                                     unsigned BinOpcode) const {
7917   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
7918   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7919
7920   auto LoadMnemonic = PPC::LDARX;
7921   auto StoreMnemonic = PPC::STDCX;
7922   switch (AtomicSize) {
7923   default:
7924     llvm_unreachable("Unexpected size of atomic entity");
7925   case 1:
7926     LoadMnemonic = PPC::LBARX;
7927     StoreMnemonic = PPC::STBCX;
7928     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7929     break;
7930   case 2:
7931     LoadMnemonic = PPC::LHARX;
7932     StoreMnemonic = PPC::STHCX;
7933     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
7934     break;
7935   case 4:
7936     LoadMnemonic = PPC::LWARX;
7937     StoreMnemonic = PPC::STWCX;
7938     break;
7939   case 8:
7940     LoadMnemonic = PPC::LDARX;
7941     StoreMnemonic = PPC::STDCX;
7942     break;
7943   }
7944
7945   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7946   MachineFunction *F = BB->getParent();
7947   MachineFunction::iterator It = BB;
7948   ++It;
7949
7950   unsigned dest = MI->getOperand(0).getReg();
7951   unsigned ptrA = MI->getOperand(1).getReg();
7952   unsigned ptrB = MI->getOperand(2).getReg();
7953   unsigned incr = MI->getOperand(3).getReg();
7954   DebugLoc dl = MI->getDebugLoc();
7955
7956   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
7957   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7958   F->insert(It, loopMBB);
7959   F->insert(It, exitMBB);
7960   exitMBB->splice(exitMBB->begin(), BB,
7961                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7962   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7963
7964   MachineRegisterInfo &RegInfo = F->getRegInfo();
7965   unsigned TmpReg = (!BinOpcode) ? incr :
7966     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
7967                                            : &PPC::GPRCRegClass);
7968
7969   //  thisMBB:
7970   //   ...
7971   //   fallthrough --> loopMBB
7972   BB->addSuccessor(loopMBB);
7973
7974   //  loopMBB:
7975   //   l[wd]arx dest, ptr
7976   //   add r0, dest, incr
7977   //   st[wd]cx. r0, ptr
7978   //   bne- loopMBB
7979   //   fallthrough --> exitMBB
7980   BB = loopMBB;
7981   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
7982     .addReg(ptrA).addReg(ptrB);
7983   if (BinOpcode)
7984     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
7985   BuildMI(BB, dl, TII->get(StoreMnemonic))
7986     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
7987   BuildMI(BB, dl, TII->get(PPC::BCC))
7988     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
7989   BB->addSuccessor(loopMBB);
7990   BB->addSuccessor(exitMBB);
7991
7992   //  exitMBB:
7993   //   ...
7994   BB = exitMBB;
7995   return BB;
7996 }
7997
7998 MachineBasicBlock *
7999 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
8000                                             MachineBasicBlock *BB,
8001                                             bool is8bit,    // operation
8002                                             unsigned BinOpcode) const {
8003   // If we support part-word atomic mnemonics, just use them
8004   if (Subtarget.hasPartwordAtomics())
8005     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode);
8006
8007   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8008   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8009   // In 64 bit mode we have to use 64 bits for addresses, even though the
8010   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8011   // registers without caring whether they're 32 or 64, but here we're
8012   // doing actual arithmetic on the addresses.
8013   bool is64bit = Subtarget.isPPC64();
8014   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8015
8016   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8017   MachineFunction *F = BB->getParent();
8018   MachineFunction::iterator It = BB;
8019   ++It;
8020
8021   unsigned dest = MI->getOperand(0).getReg();
8022   unsigned ptrA = MI->getOperand(1).getReg();
8023   unsigned ptrB = MI->getOperand(2).getReg();
8024   unsigned incr = MI->getOperand(3).getReg();
8025   DebugLoc dl = MI->getDebugLoc();
8026
8027   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8028   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8029   F->insert(It, loopMBB);
8030   F->insert(It, exitMBB);
8031   exitMBB->splice(exitMBB->begin(), BB,
8032                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8033   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8034
8035   MachineRegisterInfo &RegInfo = F->getRegInfo();
8036   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8037                                           : &PPC::GPRCRegClass;
8038   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8039   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8040   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8041   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8042   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8043   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8044   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8045   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8046   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8047   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8048   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8049   unsigned Ptr1Reg;
8050   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8051
8052   //  thisMBB:
8053   //   ...
8054   //   fallthrough --> loopMBB
8055   BB->addSuccessor(loopMBB);
8056
8057   // The 4-byte load must be aligned, while a char or short may be
8058   // anywhere in the word.  Hence all this nasty bookkeeping code.
8059   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8060   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8061   //   xori shift, shift1, 24 [16]
8062   //   rlwinm ptr, ptr1, 0, 0, 29
8063   //   slw incr2, incr, shift
8064   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8065   //   slw mask, mask2, shift
8066   //  loopMBB:
8067   //   lwarx tmpDest, ptr
8068   //   add tmp, tmpDest, incr2
8069   //   andc tmp2, tmpDest, mask
8070   //   and tmp3, tmp, mask
8071   //   or tmp4, tmp3, tmp2
8072   //   stwcx. tmp4, ptr
8073   //   bne- loopMBB
8074   //   fallthrough --> exitMBB
8075   //   srw dest, tmpDest, shift
8076   if (ptrA != ZeroReg) {
8077     Ptr1Reg = RegInfo.createVirtualRegister(RC);
8078     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8079       .addReg(ptrA).addReg(ptrB);
8080   } else {
8081     Ptr1Reg = ptrB;
8082   }
8083   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8084       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8085   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8086       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8087   if (is64bit)
8088     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8089       .addReg(Ptr1Reg).addImm(0).addImm(61);
8090   else
8091     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8092       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8093   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8094       .addReg(incr).addReg(ShiftReg);
8095   if (is8bit)
8096     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8097   else {
8098     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8099     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8100   }
8101   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8102       .addReg(Mask2Reg).addReg(ShiftReg);
8103
8104   BB = loopMBB;
8105   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8106     .addReg(ZeroReg).addReg(PtrReg);
8107   if (BinOpcode)
8108     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
8109       .addReg(Incr2Reg).addReg(TmpDestReg);
8110   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
8111     .addReg(TmpDestReg).addReg(MaskReg);
8112   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
8113     .addReg(TmpReg).addReg(MaskReg);
8114   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
8115     .addReg(Tmp3Reg).addReg(Tmp2Reg);
8116   BuildMI(BB, dl, TII->get(PPC::STWCX))
8117     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
8118   BuildMI(BB, dl, TII->get(PPC::BCC))
8119     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8120   BB->addSuccessor(loopMBB);
8121   BB->addSuccessor(exitMBB);
8122
8123   //  exitMBB:
8124   //   ...
8125   BB = exitMBB;
8126   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
8127     .addReg(ShiftReg);
8128   return BB;
8129 }
8130
8131 llvm::MachineBasicBlock*
8132 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
8133                                     MachineBasicBlock *MBB) const {
8134   DebugLoc DL = MI->getDebugLoc();
8135   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8136
8137   MachineFunction *MF = MBB->getParent();
8138   MachineRegisterInfo &MRI = MF->getRegInfo();
8139
8140   const BasicBlock *BB = MBB->getBasicBlock();
8141   MachineFunction::iterator I = MBB;
8142   ++I;
8143
8144   // Memory Reference
8145   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8146   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8147
8148   unsigned DstReg = MI->getOperand(0).getReg();
8149   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
8150   assert(RC->hasType(MVT::i32) && "Invalid destination!");
8151   unsigned mainDstReg = MRI.createVirtualRegister(RC);
8152   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
8153
8154   MVT PVT = getPointerTy();
8155   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8156          "Invalid Pointer Size!");
8157   // For v = setjmp(buf), we generate
8158   //
8159   // thisMBB:
8160   //  SjLjSetup mainMBB
8161   //  bl mainMBB
8162   //  v_restore = 1
8163   //  b sinkMBB
8164   //
8165   // mainMBB:
8166   //  buf[LabelOffset] = LR
8167   //  v_main = 0
8168   //
8169   // sinkMBB:
8170   //  v = phi(main, restore)
8171   //
8172
8173   MachineBasicBlock *thisMBB = MBB;
8174   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
8175   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
8176   MF->insert(I, mainMBB);
8177   MF->insert(I, sinkMBB);
8178
8179   MachineInstrBuilder MIB;
8180
8181   // Transfer the remainder of BB and its successor edges to sinkMBB.
8182   sinkMBB->splice(sinkMBB->begin(), MBB,
8183                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8184   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
8185
8186   // Note that the structure of the jmp_buf used here is not compatible
8187   // with that used by libc, and is not designed to be. Specifically, it
8188   // stores only those 'reserved' registers that LLVM does not otherwise
8189   // understand how to spill. Also, by convention, by the time this
8190   // intrinsic is called, Clang has already stored the frame address in the
8191   // first slot of the buffer and stack address in the third. Following the
8192   // X86 target code, we'll store the jump address in the second slot. We also
8193   // need to save the TOC pointer (R2) to handle jumps between shared
8194   // libraries, and that will be stored in the fourth slot. The thread
8195   // identifier (R13) is not affected.
8196
8197   // thisMBB:
8198   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8199   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8200   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8201
8202   // Prepare IP either in reg.
8203   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
8204   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
8205   unsigned BufReg = MI->getOperand(1).getReg();
8206
8207   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
8208     setUsesTOCBasePtr(*MBB->getParent());
8209     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
8210             .addReg(PPC::X2)
8211             .addImm(TOCOffset)
8212             .addReg(BufReg);
8213     MIB.setMemRefs(MMOBegin, MMOEnd);
8214   }
8215
8216   // Naked functions never have a base pointer, and so we use r1. For all
8217   // other functions, this decision must be delayed until during PEI.
8218   unsigned BaseReg;
8219   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
8220     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
8221   else
8222     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
8223
8224   MIB = BuildMI(*thisMBB, MI, DL,
8225                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
8226             .addReg(BaseReg)
8227             .addImm(BPOffset)
8228             .addReg(BufReg);
8229   MIB.setMemRefs(MMOBegin, MMOEnd);
8230
8231   // Setup
8232   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
8233   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
8234   MIB.addRegMask(TRI->getNoPreservedMask());
8235
8236   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
8237
8238   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
8239           .addMBB(mainMBB);
8240   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
8241
8242   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
8243   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
8244
8245   // mainMBB:
8246   //  mainDstReg = 0
8247   MIB =
8248       BuildMI(mainMBB, DL,
8249               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
8250
8251   // Store IP
8252   if (Subtarget.isPPC64()) {
8253     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
8254             .addReg(LabelReg)
8255             .addImm(LabelOffset)
8256             .addReg(BufReg);
8257   } else {
8258     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
8259             .addReg(LabelReg)
8260             .addImm(LabelOffset)
8261             .addReg(BufReg);
8262   }
8263
8264   MIB.setMemRefs(MMOBegin, MMOEnd);
8265
8266   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
8267   mainMBB->addSuccessor(sinkMBB);
8268
8269   // sinkMBB:
8270   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8271           TII->get(PPC::PHI), DstReg)
8272     .addReg(mainDstReg).addMBB(mainMBB)
8273     .addReg(restoreDstReg).addMBB(thisMBB);
8274
8275   MI->eraseFromParent();
8276   return sinkMBB;
8277 }
8278
8279 MachineBasicBlock *
8280 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
8281                                      MachineBasicBlock *MBB) const {
8282   DebugLoc DL = MI->getDebugLoc();
8283   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8284
8285   MachineFunction *MF = MBB->getParent();
8286   MachineRegisterInfo &MRI = MF->getRegInfo();
8287
8288   // Memory Reference
8289   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
8290   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
8291
8292   MVT PVT = getPointerTy();
8293   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
8294          "Invalid Pointer Size!");
8295
8296   const TargetRegisterClass *RC =
8297     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
8298   unsigned Tmp = MRI.createVirtualRegister(RC);
8299   // Since FP is only updated here but NOT referenced, it's treated as GPR.
8300   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
8301   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
8302   unsigned BP =
8303       (PVT == MVT::i64)
8304           ? PPC::X30
8305           : (Subtarget.isSVR4ABI() &&
8306                      MF->getTarget().getRelocationModel() == Reloc::PIC_
8307                  ? PPC::R29
8308                  : PPC::R30);
8309
8310   MachineInstrBuilder MIB;
8311
8312   const int64_t LabelOffset = 1 * PVT.getStoreSize();
8313   const int64_t SPOffset    = 2 * PVT.getStoreSize();
8314   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
8315   const int64_t BPOffset    = 4 * PVT.getStoreSize();
8316
8317   unsigned BufReg = MI->getOperand(0).getReg();
8318
8319   // Reload FP (the jumped-to function may not have had a
8320   // frame pointer, and if so, then its r31 will be restored
8321   // as necessary).
8322   if (PVT == MVT::i64) {
8323     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
8324             .addImm(0)
8325             .addReg(BufReg);
8326   } else {
8327     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
8328             .addImm(0)
8329             .addReg(BufReg);
8330   }
8331   MIB.setMemRefs(MMOBegin, MMOEnd);
8332
8333   // Reload IP
8334   if (PVT == MVT::i64) {
8335     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
8336             .addImm(LabelOffset)
8337             .addReg(BufReg);
8338   } else {
8339     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
8340             .addImm(LabelOffset)
8341             .addReg(BufReg);
8342   }
8343   MIB.setMemRefs(MMOBegin, MMOEnd);
8344
8345   // Reload SP
8346   if (PVT == MVT::i64) {
8347     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
8348             .addImm(SPOffset)
8349             .addReg(BufReg);
8350   } else {
8351     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
8352             .addImm(SPOffset)
8353             .addReg(BufReg);
8354   }
8355   MIB.setMemRefs(MMOBegin, MMOEnd);
8356
8357   // Reload BP
8358   if (PVT == MVT::i64) {
8359     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
8360             .addImm(BPOffset)
8361             .addReg(BufReg);
8362   } else {
8363     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
8364             .addImm(BPOffset)
8365             .addReg(BufReg);
8366   }
8367   MIB.setMemRefs(MMOBegin, MMOEnd);
8368
8369   // Reload TOC
8370   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
8371     setUsesTOCBasePtr(*MBB->getParent());
8372     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
8373             .addImm(TOCOffset)
8374             .addReg(BufReg);
8375
8376     MIB.setMemRefs(MMOBegin, MMOEnd);
8377   }
8378
8379   // Jump
8380   BuildMI(*MBB, MI, DL,
8381           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
8382   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
8383
8384   MI->eraseFromParent();
8385   return MBB;
8386 }
8387
8388 MachineBasicBlock *
8389 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8390                                                MachineBasicBlock *BB) const {
8391   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
8392       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8393     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
8394         MI->getOpcode() == TargetOpcode::PATCHPOINT) {
8395       // Call lowering should have added an r2 operand to indicate a dependence
8396       // on the TOC base pointer value. It can't however, because there is no
8397       // way to mark the dependence as implicit there, and so the stackmap code
8398       // will confuse it with a regular operand. Instead, add the dependence
8399       // here.
8400       setUsesTOCBasePtr(*BB->getParent());
8401       MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
8402     }
8403
8404     return emitPatchPoint(MI, BB);
8405   }
8406
8407   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
8408       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
8409     return emitEHSjLjSetJmp(MI, BB);
8410   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
8411              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
8412     return emitEHSjLjLongJmp(MI, BB);
8413   }
8414
8415   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8416
8417   // To "insert" these instructions we actually have to insert their
8418   // control-flow patterns.
8419   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8420   MachineFunction::iterator It = BB;
8421   ++It;
8422
8423   MachineFunction *F = BB->getParent();
8424
8425   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8426                               MI->getOpcode() == PPC::SELECT_CC_I8 ||
8427                               MI->getOpcode() == PPC::SELECT_I4 ||
8428                               MI->getOpcode() == PPC::SELECT_I8)) {
8429     SmallVector<MachineOperand, 2> Cond;
8430     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8431         MI->getOpcode() == PPC::SELECT_CC_I8)
8432       Cond.push_back(MI->getOperand(4));
8433     else
8434       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
8435     Cond.push_back(MI->getOperand(1));
8436
8437     DebugLoc dl = MI->getDebugLoc();
8438     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
8439                       Cond, MI->getOperand(2).getReg(),
8440                       MI->getOperand(3).getReg());
8441   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
8442              MI->getOpcode() == PPC::SELECT_CC_I8 ||
8443              MI->getOpcode() == PPC::SELECT_CC_F4 ||
8444              MI->getOpcode() == PPC::SELECT_CC_F8 ||
8445              MI->getOpcode() == PPC::SELECT_CC_QFRC ||
8446              MI->getOpcode() == PPC::SELECT_CC_QSRC ||
8447              MI->getOpcode() == PPC::SELECT_CC_QBRC ||
8448              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
8449              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
8450              MI->getOpcode() == PPC::SELECT_CC_VSSRC ||
8451              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
8452              MI->getOpcode() == PPC::SELECT_I4 ||
8453              MI->getOpcode() == PPC::SELECT_I8 ||
8454              MI->getOpcode() == PPC::SELECT_F4 ||
8455              MI->getOpcode() == PPC::SELECT_F8 ||
8456              MI->getOpcode() == PPC::SELECT_QFRC ||
8457              MI->getOpcode() == PPC::SELECT_QSRC ||
8458              MI->getOpcode() == PPC::SELECT_QBRC ||
8459              MI->getOpcode() == PPC::SELECT_VRRC ||
8460              MI->getOpcode() == PPC::SELECT_VSFRC ||
8461              MI->getOpcode() == PPC::SELECT_VSSRC ||
8462              MI->getOpcode() == PPC::SELECT_VSRC) {
8463     // The incoming instruction knows the destination vreg to set, the
8464     // condition code register to branch on, the true/false values to
8465     // select between, and a branch opcode to use.
8466
8467     //  thisMBB:
8468     //  ...
8469     //   TrueVal = ...
8470     //   cmpTY ccX, r1, r2
8471     //   bCC copy1MBB
8472     //   fallthrough --> copy0MBB
8473     MachineBasicBlock *thisMBB = BB;
8474     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8475     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8476     DebugLoc dl = MI->getDebugLoc();
8477     F->insert(It, copy0MBB);
8478     F->insert(It, sinkMBB);
8479
8480     // Transfer the remainder of BB and its successor edges to sinkMBB.
8481     sinkMBB->splice(sinkMBB->begin(), BB,
8482                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8483     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8484
8485     // Next, add the true and fallthrough blocks as its successors.
8486     BB->addSuccessor(copy0MBB);
8487     BB->addSuccessor(sinkMBB);
8488
8489     if (MI->getOpcode() == PPC::SELECT_I4 ||
8490         MI->getOpcode() == PPC::SELECT_I8 ||
8491         MI->getOpcode() == PPC::SELECT_F4 ||
8492         MI->getOpcode() == PPC::SELECT_F8 ||
8493         MI->getOpcode() == PPC::SELECT_QFRC ||
8494         MI->getOpcode() == PPC::SELECT_QSRC ||
8495         MI->getOpcode() == PPC::SELECT_QBRC ||
8496         MI->getOpcode() == PPC::SELECT_VRRC ||
8497         MI->getOpcode() == PPC::SELECT_VSFRC ||
8498         MI->getOpcode() == PPC::SELECT_VSSRC ||
8499         MI->getOpcode() == PPC::SELECT_VSRC) {
8500       BuildMI(BB, dl, TII->get(PPC::BC))
8501         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8502     } else {
8503       unsigned SelectPred = MI->getOperand(4).getImm();
8504       BuildMI(BB, dl, TII->get(PPC::BCC))
8505         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
8506     }
8507
8508     //  copy0MBB:
8509     //   %FalseValue = ...
8510     //   # fallthrough to sinkMBB
8511     BB = copy0MBB;
8512
8513     // Update machine-CFG edges
8514     BB->addSuccessor(sinkMBB);
8515
8516     //  sinkMBB:
8517     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8518     //  ...
8519     BB = sinkMBB;
8520     BuildMI(*BB, BB->begin(), dl,
8521             TII->get(PPC::PHI), MI->getOperand(0).getReg())
8522       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
8523       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8524   } else if (MI->getOpcode() == PPC::ReadTB) {
8525     // To read the 64-bit time-base register on a 32-bit target, we read the
8526     // two halves. Should the counter have wrapped while it was being read, we
8527     // need to try again.
8528     // ...
8529     // readLoop:
8530     // mfspr Rx,TBU # load from TBU
8531     // mfspr Ry,TB  # load from TB
8532     // mfspr Rz,TBU # load from TBU
8533     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
8534     // bne readLoop   # branch if they're not equal
8535     // ...
8536
8537     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
8538     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8539     DebugLoc dl = MI->getDebugLoc();
8540     F->insert(It, readMBB);
8541     F->insert(It, sinkMBB);
8542
8543     // Transfer the remainder of BB and its successor edges to sinkMBB.
8544     sinkMBB->splice(sinkMBB->begin(), BB,
8545                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8546     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8547
8548     BB->addSuccessor(readMBB);
8549     BB = readMBB;
8550
8551     MachineRegisterInfo &RegInfo = F->getRegInfo();
8552     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8553     unsigned LoReg = MI->getOperand(0).getReg();
8554     unsigned HiReg = MI->getOperand(1).getReg();
8555
8556     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
8557     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
8558     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
8559
8560     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8561
8562     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
8563       .addReg(HiReg).addReg(ReadAgainReg);
8564     BuildMI(BB, dl, TII->get(PPC::BCC))
8565       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
8566
8567     BB->addSuccessor(readMBB);
8568     BB->addSuccessor(sinkMBB);
8569   }
8570   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
8571     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
8572   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
8573     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
8574   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
8575     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
8576   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
8577     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
8578
8579   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
8580     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
8581   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
8582     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
8583   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
8584     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
8585   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
8586     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
8587
8588   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
8589     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
8590   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
8591     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
8592   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
8593     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
8594   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
8595     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
8596
8597   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
8598     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
8599   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
8600     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
8601   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
8602     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
8603   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
8604     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
8605
8606   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
8607     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
8608   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
8609     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
8610   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
8611     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
8612   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
8613     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
8614
8615   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
8616     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
8617   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
8618     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
8619   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
8620     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
8621   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
8622     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
8623
8624   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
8625     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
8626   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
8627     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
8628   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
8629     BB = EmitAtomicBinary(MI, BB, 4, 0);
8630   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
8631     BB = EmitAtomicBinary(MI, BB, 8, 0);
8632
8633   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
8634            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
8635            (Subtarget.hasPartwordAtomics() &&
8636             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
8637            (Subtarget.hasPartwordAtomics() &&
8638             MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
8639     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
8640
8641     auto LoadMnemonic = PPC::LDARX;
8642     auto StoreMnemonic = PPC::STDCX;
8643     switch(MI->getOpcode()) {
8644     default:
8645       llvm_unreachable("Compare and swap of unknown size");
8646     case PPC::ATOMIC_CMP_SWAP_I8:
8647       LoadMnemonic = PPC::LBARX;
8648       StoreMnemonic = PPC::STBCX;
8649       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8650       break;
8651     case PPC::ATOMIC_CMP_SWAP_I16:
8652       LoadMnemonic = PPC::LHARX;
8653       StoreMnemonic = PPC::STHCX;
8654       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
8655       break;
8656     case PPC::ATOMIC_CMP_SWAP_I32:
8657       LoadMnemonic = PPC::LWARX;
8658       StoreMnemonic = PPC::STWCX;
8659       break;
8660     case PPC::ATOMIC_CMP_SWAP_I64:
8661       LoadMnemonic = PPC::LDARX;
8662       StoreMnemonic = PPC::STDCX;
8663       break;
8664     }
8665     unsigned dest   = MI->getOperand(0).getReg();
8666     unsigned ptrA   = MI->getOperand(1).getReg();
8667     unsigned ptrB   = MI->getOperand(2).getReg();
8668     unsigned oldval = MI->getOperand(3).getReg();
8669     unsigned newval = MI->getOperand(4).getReg();
8670     DebugLoc dl     = MI->getDebugLoc();
8671
8672     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8673     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8674     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8675     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8676     F->insert(It, loop1MBB);
8677     F->insert(It, loop2MBB);
8678     F->insert(It, midMBB);
8679     F->insert(It, exitMBB);
8680     exitMBB->splice(exitMBB->begin(), BB,
8681                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8682     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8683
8684     //  thisMBB:
8685     //   ...
8686     //   fallthrough --> loopMBB
8687     BB->addSuccessor(loop1MBB);
8688
8689     // loop1MBB:
8690     //   l[bhwd]arx dest, ptr
8691     //   cmp[wd] dest, oldval
8692     //   bne- midMBB
8693     // loop2MBB:
8694     //   st[bhwd]cx. newval, ptr
8695     //   bne- loopMBB
8696     //   b exitBB
8697     // midMBB:
8698     //   st[bhwd]cx. dest, ptr
8699     // exitBB:
8700     BB = loop1MBB;
8701     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8702       .addReg(ptrA).addReg(ptrB);
8703     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
8704       .addReg(oldval).addReg(dest);
8705     BuildMI(BB, dl, TII->get(PPC::BCC))
8706       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8707     BB->addSuccessor(loop2MBB);
8708     BB->addSuccessor(midMBB);
8709
8710     BB = loop2MBB;
8711     BuildMI(BB, dl, TII->get(StoreMnemonic))
8712       .addReg(newval).addReg(ptrA).addReg(ptrB);
8713     BuildMI(BB, dl, TII->get(PPC::BCC))
8714       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8715     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8716     BB->addSuccessor(loop1MBB);
8717     BB->addSuccessor(exitMBB);
8718
8719     BB = midMBB;
8720     BuildMI(BB, dl, TII->get(StoreMnemonic))
8721       .addReg(dest).addReg(ptrA).addReg(ptrB);
8722     BB->addSuccessor(exitMBB);
8723
8724     //  exitMBB:
8725     //   ...
8726     BB = exitMBB;
8727   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
8728              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
8729     // We must use 64-bit registers for addresses when targeting 64-bit,
8730     // since we're actually doing arithmetic on them.  Other registers
8731     // can be 32-bit.
8732     bool is64bit = Subtarget.isPPC64();
8733     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
8734
8735     unsigned dest   = MI->getOperand(0).getReg();
8736     unsigned ptrA   = MI->getOperand(1).getReg();
8737     unsigned ptrB   = MI->getOperand(2).getReg();
8738     unsigned oldval = MI->getOperand(3).getReg();
8739     unsigned newval = MI->getOperand(4).getReg();
8740     DebugLoc dl     = MI->getDebugLoc();
8741
8742     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
8743     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
8744     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
8745     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8746     F->insert(It, loop1MBB);
8747     F->insert(It, loop2MBB);
8748     F->insert(It, midMBB);
8749     F->insert(It, exitMBB);
8750     exitMBB->splice(exitMBB->begin(), BB,
8751                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8752     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8753
8754     MachineRegisterInfo &RegInfo = F->getRegInfo();
8755     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8756                                             : &PPC::GPRCRegClass;
8757     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8758     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8759     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
8760     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
8761     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
8762     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
8763     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
8764     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8765     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8766     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8767     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8768     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8769     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8770     unsigned Ptr1Reg;
8771     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
8772     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8773     //  thisMBB:
8774     //   ...
8775     //   fallthrough --> loopMBB
8776     BB->addSuccessor(loop1MBB);
8777
8778     // The 4-byte load must be aligned, while a char or short may be
8779     // anywhere in the word.  Hence all this nasty bookkeeping code.
8780     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
8781     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8782     //   xori shift, shift1, 24 [16]
8783     //   rlwinm ptr, ptr1, 0, 0, 29
8784     //   slw newval2, newval, shift
8785     //   slw oldval2, oldval,shift
8786     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8787     //   slw mask, mask2, shift
8788     //   and newval3, newval2, mask
8789     //   and oldval3, oldval2, mask
8790     // loop1MBB:
8791     //   lwarx tmpDest, ptr
8792     //   and tmp, tmpDest, mask
8793     //   cmpw tmp, oldval3
8794     //   bne- midMBB
8795     // loop2MBB:
8796     //   andc tmp2, tmpDest, mask
8797     //   or tmp4, tmp2, newval3
8798     //   stwcx. tmp4, ptr
8799     //   bne- loop1MBB
8800     //   b exitBB
8801     // midMBB:
8802     //   stwcx. tmpDest, ptr
8803     // exitBB:
8804     //   srw dest, tmpDest, shift
8805     if (ptrA != ZeroReg) {
8806       Ptr1Reg = RegInfo.createVirtualRegister(RC);
8807       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8808         .addReg(ptrA).addReg(ptrB);
8809     } else {
8810       Ptr1Reg = ptrB;
8811     }
8812     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8813         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8814     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8815         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8816     if (is64bit)
8817       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8818         .addReg(Ptr1Reg).addImm(0).addImm(61);
8819     else
8820       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8821         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8822     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
8823         .addReg(newval).addReg(ShiftReg);
8824     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
8825         .addReg(oldval).addReg(ShiftReg);
8826     if (is8bit)
8827       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8828     else {
8829       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8830       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
8831         .addReg(Mask3Reg).addImm(65535);
8832     }
8833     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8834         .addReg(Mask2Reg).addReg(ShiftReg);
8835     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
8836         .addReg(NewVal2Reg).addReg(MaskReg);
8837     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
8838         .addReg(OldVal2Reg).addReg(MaskReg);
8839
8840     BB = loop1MBB;
8841     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
8842         .addReg(ZeroReg).addReg(PtrReg);
8843     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
8844         .addReg(TmpDestReg).addReg(MaskReg);
8845     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
8846         .addReg(TmpReg).addReg(OldVal3Reg);
8847     BuildMI(BB, dl, TII->get(PPC::BCC))
8848         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
8849     BB->addSuccessor(loop2MBB);
8850     BB->addSuccessor(midMBB);
8851
8852     BB = loop2MBB;
8853     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
8854         .addReg(TmpDestReg).addReg(MaskReg);
8855     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
8856         .addReg(Tmp2Reg).addReg(NewVal3Reg);
8857     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
8858         .addReg(ZeroReg).addReg(PtrReg);
8859     BuildMI(BB, dl, TII->get(PPC::BCC))
8860       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
8861     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
8862     BB->addSuccessor(loop1MBB);
8863     BB->addSuccessor(exitMBB);
8864
8865     BB = midMBB;
8866     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
8867       .addReg(ZeroReg).addReg(PtrReg);
8868     BB->addSuccessor(exitMBB);
8869
8870     //  exitMBB:
8871     //   ...
8872     BB = exitMBB;
8873     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
8874       .addReg(ShiftReg);
8875   } else if (MI->getOpcode() == PPC::FADDrtz) {
8876     // This pseudo performs an FADD with rounding mode temporarily forced
8877     // to round-to-zero.  We emit this via custom inserter since the FPSCR
8878     // is not modeled at the SelectionDAG level.
8879     unsigned Dest = MI->getOperand(0).getReg();
8880     unsigned Src1 = MI->getOperand(1).getReg();
8881     unsigned Src2 = MI->getOperand(2).getReg();
8882     DebugLoc dl   = MI->getDebugLoc();
8883
8884     MachineRegisterInfo &RegInfo = F->getRegInfo();
8885     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
8886
8887     // Save FPSCR value.
8888     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
8889
8890     // Set rounding mode to round-to-zero.
8891     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
8892     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
8893
8894     // Perform addition.
8895     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
8896
8897     // Restore FPSCR value.
8898     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
8899   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8900              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
8901              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8902              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
8903     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
8904                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
8905                       PPC::ANDIo8 : PPC::ANDIo;
8906     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
8907                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
8908
8909     MachineRegisterInfo &RegInfo = F->getRegInfo();
8910     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
8911                                                   &PPC::GPRCRegClass :
8912                                                   &PPC::G8RCRegClass);
8913
8914     DebugLoc dl   = MI->getDebugLoc();
8915     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
8916       .addReg(MI->getOperand(1).getReg()).addImm(1);
8917     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
8918             MI->getOperand(0).getReg())
8919       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
8920   } else if (MI->getOpcode() == PPC::TCHECK_RET) {
8921     DebugLoc Dl = MI->getDebugLoc();
8922     MachineRegisterInfo &RegInfo = F->getRegInfo();
8923     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
8924     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
8925     return BB;
8926   } else {
8927     llvm_unreachable("Unexpected instr type to insert");
8928   }
8929
8930   MI->eraseFromParent();   // The pseudo instruction is gone now.
8931   return BB;
8932 }
8933
8934 //===----------------------------------------------------------------------===//
8935 // Target Optimization Hooks
8936 //===----------------------------------------------------------------------===//
8937
8938 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
8939                                             DAGCombinerInfo &DCI,
8940                                             unsigned &RefinementSteps,
8941                                             bool &UseOneConstNR) const {
8942   EVT VT = Operand.getValueType();
8943   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
8944       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
8945       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8946       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8947       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8948       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8949     // Convergence is quadratic, so we essentially double the number of digits
8950     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8951     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8952     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8953     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8954     if (VT.getScalarType() == MVT::f64)
8955       ++RefinementSteps;
8956     UseOneConstNR = true;
8957     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
8958   }
8959   return SDValue();
8960 }
8961
8962 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
8963                                             DAGCombinerInfo &DCI,
8964                                             unsigned &RefinementSteps) const {
8965   EVT VT = Operand.getValueType();
8966   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
8967       (VT == MVT::f64 && Subtarget.hasFRE()) ||
8968       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
8969       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
8970       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
8971       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
8972     // Convergence is quadratic, so we essentially double the number of digits
8973     // correct after every iteration. For both FRE and FRSQRTE, the minimum
8974     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
8975     // 2^-14. IEEE float has 23 digits and double has 52 digits.
8976     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
8977     if (VT.getScalarType() == MVT::f64)
8978       ++RefinementSteps;
8979     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
8980   }
8981   return SDValue();
8982 }
8983
8984 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8985   // Note: This functionality is used only when unsafe-fp-math is enabled, and
8986   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
8987   // enabled for division), this functionality is redundant with the default
8988   // combiner logic (once the division -> reciprocal/multiply transformation
8989   // has taken place). As a result, this matters more for older cores than for
8990   // newer ones.
8991
8992   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8993   // reciprocal if there are two or more FDIVs (for embedded cores with only
8994   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
8995   switch (Subtarget.getDarwinDirective()) {
8996   default:
8997     return NumUsers > 2;
8998   case PPC::DIR_440:
8999   case PPC::DIR_A2:
9000   case PPC::DIR_E500mc:
9001   case PPC::DIR_E5500:
9002     return NumUsers > 1;
9003   }
9004 }
9005
9006 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9007                             unsigned Bytes, int Dist,
9008                             SelectionDAG &DAG) {
9009   if (VT.getSizeInBits() / 8 != Bytes)
9010     return false;
9011
9012   SDValue BaseLoc = Base->getBasePtr();
9013   if (Loc.getOpcode() == ISD::FrameIndex) {
9014     if (BaseLoc.getOpcode() != ISD::FrameIndex)
9015       return false;
9016     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9017     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
9018     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9019     int FS  = MFI->getObjectSize(FI);
9020     int BFS = MFI->getObjectSize(BFI);
9021     if (FS != BFS || FS != (int)Bytes) return false;
9022     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
9023   }
9024
9025   // Handle X+C
9026   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
9027       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
9028     return true;
9029
9030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9031   const GlobalValue *GV1 = nullptr;
9032   const GlobalValue *GV2 = nullptr;
9033   int64_t Offset1 = 0;
9034   int64_t Offset2 = 0;
9035   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
9036   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
9037   if (isGA1 && isGA2 && GV1 == GV2)
9038     return Offset1 == (Offset2 + Dist*Bytes);
9039   return false;
9040 }
9041
9042 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
9043 // not enforce equality of the chain operands.
9044 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
9045                             unsigned Bytes, int Dist,
9046                             SelectionDAG &DAG) {
9047   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
9048     EVT VT = LS->getMemoryVT();
9049     SDValue Loc = LS->getBasePtr();
9050     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
9051   }
9052
9053   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
9054     EVT VT;
9055     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9056     default: return false;
9057     case Intrinsic::ppc_qpx_qvlfd:
9058     case Intrinsic::ppc_qpx_qvlfda:
9059       VT = MVT::v4f64;
9060       break;
9061     case Intrinsic::ppc_qpx_qvlfs:
9062     case Intrinsic::ppc_qpx_qvlfsa:
9063       VT = MVT::v4f32;
9064       break;
9065     case Intrinsic::ppc_qpx_qvlfcd:
9066     case Intrinsic::ppc_qpx_qvlfcda:
9067       VT = MVT::v2f64;
9068       break;
9069     case Intrinsic::ppc_qpx_qvlfcs:
9070     case Intrinsic::ppc_qpx_qvlfcsa:
9071       VT = MVT::v2f32;
9072       break;
9073     case Intrinsic::ppc_qpx_qvlfiwa:
9074     case Intrinsic::ppc_qpx_qvlfiwz:
9075     case Intrinsic::ppc_altivec_lvx:
9076     case Intrinsic::ppc_altivec_lvxl:
9077     case Intrinsic::ppc_vsx_lxvw4x:
9078       VT = MVT::v4i32;
9079       break;
9080     case Intrinsic::ppc_vsx_lxvd2x:
9081       VT = MVT::v2f64;
9082       break;
9083     case Intrinsic::ppc_altivec_lvebx:
9084       VT = MVT::i8;
9085       break;
9086     case Intrinsic::ppc_altivec_lvehx:
9087       VT = MVT::i16;
9088       break;
9089     case Intrinsic::ppc_altivec_lvewx:
9090       VT = MVT::i32;
9091       break;
9092     }
9093
9094     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
9095   }
9096
9097   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
9098     EVT VT;
9099     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9100     default: return false;
9101     case Intrinsic::ppc_qpx_qvstfd:
9102     case Intrinsic::ppc_qpx_qvstfda:
9103       VT = MVT::v4f64;
9104       break;
9105     case Intrinsic::ppc_qpx_qvstfs:
9106     case Intrinsic::ppc_qpx_qvstfsa:
9107       VT = MVT::v4f32;
9108       break;
9109     case Intrinsic::ppc_qpx_qvstfcd:
9110     case Intrinsic::ppc_qpx_qvstfcda:
9111       VT = MVT::v2f64;
9112       break;
9113     case Intrinsic::ppc_qpx_qvstfcs:
9114     case Intrinsic::ppc_qpx_qvstfcsa:
9115       VT = MVT::v2f32;
9116       break;
9117     case Intrinsic::ppc_qpx_qvstfiw:
9118     case Intrinsic::ppc_qpx_qvstfiwa:
9119     case Intrinsic::ppc_altivec_stvx:
9120     case Intrinsic::ppc_altivec_stvxl:
9121     case Intrinsic::ppc_vsx_stxvw4x:
9122       VT = MVT::v4i32;
9123       break;
9124     case Intrinsic::ppc_vsx_stxvd2x:
9125       VT = MVT::v2f64;
9126       break;
9127     case Intrinsic::ppc_altivec_stvebx:
9128       VT = MVT::i8;
9129       break;
9130     case Intrinsic::ppc_altivec_stvehx:
9131       VT = MVT::i16;
9132       break;
9133     case Intrinsic::ppc_altivec_stvewx:
9134       VT = MVT::i32;
9135       break;
9136     }
9137
9138     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
9139   }
9140
9141   return false;
9142 }
9143
9144 // Return true is there is a nearyby consecutive load to the one provided
9145 // (regardless of alignment). We search up and down the chain, looking though
9146 // token factors and other loads (but nothing else). As a result, a true result
9147 // indicates that it is safe to create a new consecutive load adjacent to the
9148 // load provided.
9149 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
9150   SDValue Chain = LD->getChain();
9151   EVT VT = LD->getMemoryVT();
9152
9153   SmallSet<SDNode *, 16> LoadRoots;
9154   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
9155   SmallSet<SDNode *, 16> Visited;
9156
9157   // First, search up the chain, branching to follow all token-factor operands.
9158   // If we find a consecutive load, then we're done, otherwise, record all
9159   // nodes just above the top-level loads and token factors.
9160   while (!Queue.empty()) {
9161     SDNode *ChainNext = Queue.pop_back_val();
9162     if (!Visited.insert(ChainNext).second)
9163       continue;
9164
9165     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
9166       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9167         return true;
9168
9169       if (!Visited.count(ChainLD->getChain().getNode()))
9170         Queue.push_back(ChainLD->getChain().getNode());
9171     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
9172       for (const SDUse &O : ChainNext->ops())
9173         if (!Visited.count(O.getNode()))
9174           Queue.push_back(O.getNode());
9175     } else
9176       LoadRoots.insert(ChainNext);
9177   }
9178
9179   // Second, search down the chain, starting from the top-level nodes recorded
9180   // in the first phase. These top-level nodes are the nodes just above all
9181   // loads and token factors. Starting with their uses, recursively look though
9182   // all loads (just the chain uses) and token factors to find a consecutive
9183   // load.
9184   Visited.clear();
9185   Queue.clear();
9186
9187   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
9188        IE = LoadRoots.end(); I != IE; ++I) {
9189     Queue.push_back(*I);
9190        
9191     while (!Queue.empty()) {
9192       SDNode *LoadRoot = Queue.pop_back_val();
9193       if (!Visited.insert(LoadRoot).second)
9194         continue;
9195
9196       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
9197         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
9198           return true;
9199
9200       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
9201            UE = LoadRoot->use_end(); UI != UE; ++UI)
9202         if (((isa<MemSDNode>(*UI) &&
9203             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
9204             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
9205           Queue.push_back(*UI);
9206     }
9207   }
9208
9209   return false;
9210 }
9211
9212 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
9213                                                   DAGCombinerInfo &DCI) const {
9214   SelectionDAG &DAG = DCI.DAG;
9215   SDLoc dl(N);
9216
9217   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
9218   // If we're tracking CR bits, we need to be careful that we don't have:
9219   //   trunc(binary-ops(zext(x), zext(y)))
9220   // or
9221   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
9222   // such that we're unnecessarily moving things into GPRs when it would be
9223   // better to keep them in CR bits.
9224
9225   // Note that trunc here can be an actual i1 trunc, or can be the effective
9226   // truncation that comes from a setcc or select_cc.
9227   if (N->getOpcode() == ISD::TRUNCATE &&
9228       N->getValueType(0) != MVT::i1)
9229     return SDValue();
9230
9231   if (N->getOperand(0).getValueType() != MVT::i32 &&
9232       N->getOperand(0).getValueType() != MVT::i64)
9233     return SDValue();
9234
9235   if (N->getOpcode() == ISD::SETCC ||
9236       N->getOpcode() == ISD::SELECT_CC) {
9237     // If we're looking at a comparison, then we need to make sure that the
9238     // high bits (all except for the first) don't matter the result.
9239     ISD::CondCode CC =
9240       cast<CondCodeSDNode>(N->getOperand(
9241         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
9242     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
9243
9244     if (ISD::isSignedIntSetCC(CC)) {
9245       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
9246           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
9247         return SDValue();
9248     } else if (ISD::isUnsignedIntSetCC(CC)) {
9249       if (!DAG.MaskedValueIsZero(N->getOperand(0),
9250                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
9251           !DAG.MaskedValueIsZero(N->getOperand(1),
9252                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
9253         return SDValue();
9254     } else {
9255       // This is neither a signed nor an unsigned comparison, just make sure
9256       // that the high bits are equal.
9257       APInt Op1Zero, Op1One;
9258       APInt Op2Zero, Op2One;
9259       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
9260       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
9261
9262       // We don't really care about what is known about the first bit (if
9263       // anything), so clear it in all masks prior to comparing them.
9264       Op1Zero.clearBit(0); Op1One.clearBit(0);
9265       Op2Zero.clearBit(0); Op2One.clearBit(0);
9266
9267       if (Op1Zero != Op2Zero || Op1One != Op2One)
9268         return SDValue();
9269     }
9270   }
9271
9272   // We now know that the higher-order bits are irrelevant, we just need to
9273   // make sure that all of the intermediate operations are bit operations, and
9274   // all inputs are extensions.
9275   if (N->getOperand(0).getOpcode() != ISD::AND &&
9276       N->getOperand(0).getOpcode() != ISD::OR  &&
9277       N->getOperand(0).getOpcode() != ISD::XOR &&
9278       N->getOperand(0).getOpcode() != ISD::SELECT &&
9279       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
9280       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
9281       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
9282       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
9283       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
9284     return SDValue();
9285
9286   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
9287       N->getOperand(1).getOpcode() != ISD::AND &&
9288       N->getOperand(1).getOpcode() != ISD::OR  &&
9289       N->getOperand(1).getOpcode() != ISD::XOR &&
9290       N->getOperand(1).getOpcode() != ISD::SELECT &&
9291       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
9292       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
9293       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
9294       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
9295       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
9296     return SDValue();
9297
9298   SmallVector<SDValue, 4> Inputs;
9299   SmallVector<SDValue, 8> BinOps, PromOps;
9300   SmallPtrSet<SDNode *, 16> Visited;
9301
9302   for (unsigned i = 0; i < 2; ++i) {
9303     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9304           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9305           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9306           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9307         isa<ConstantSDNode>(N->getOperand(i)))
9308       Inputs.push_back(N->getOperand(i));
9309     else
9310       BinOps.push_back(N->getOperand(i));
9311
9312     if (N->getOpcode() == ISD::TRUNCATE)
9313       break;
9314   }
9315
9316   // Visit all inputs, collect all binary operations (and, or, xor and
9317   // select) that are all fed by extensions. 
9318   while (!BinOps.empty()) {
9319     SDValue BinOp = BinOps.back();
9320     BinOps.pop_back();
9321
9322     if (!Visited.insert(BinOp.getNode()).second)
9323       continue;
9324
9325     PromOps.push_back(BinOp);
9326
9327     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9328       // The condition of the select is not promoted.
9329       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9330         continue;
9331       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9332         continue;
9333
9334       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9335             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9336             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
9337            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
9338           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9339         Inputs.push_back(BinOp.getOperand(i)); 
9340       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9341                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9342                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9343                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9344                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
9345                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9346                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
9347                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
9348                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
9349         BinOps.push_back(BinOp.getOperand(i));
9350       } else {
9351         // We have an input that is not an extension or another binary
9352         // operation; we'll abort this transformation.
9353         return SDValue();
9354       }
9355     }
9356   }
9357
9358   // Make sure that this is a self-contained cluster of operations (which
9359   // is not quite the same thing as saying that everything has only one
9360   // use).
9361   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9362     if (isa<ConstantSDNode>(Inputs[i]))
9363       continue;
9364
9365     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9366                               UE = Inputs[i].getNode()->use_end();
9367          UI != UE; ++UI) {
9368       SDNode *User = *UI;
9369       if (User != N && !Visited.count(User))
9370         return SDValue();
9371
9372       // Make sure that we're not going to promote the non-output-value
9373       // operand(s) or SELECT or SELECT_CC.
9374       // FIXME: Although we could sometimes handle this, and it does occur in
9375       // practice that one of the condition inputs to the select is also one of
9376       // the outputs, we currently can't deal with this.
9377       if (User->getOpcode() == ISD::SELECT) {
9378         if (User->getOperand(0) == Inputs[i])
9379           return SDValue();
9380       } else if (User->getOpcode() == ISD::SELECT_CC) {
9381         if (User->getOperand(0) == Inputs[i] ||
9382             User->getOperand(1) == Inputs[i])
9383           return SDValue();
9384       }
9385     }
9386   }
9387
9388   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9389     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9390                               UE = PromOps[i].getNode()->use_end();
9391          UI != UE; ++UI) {
9392       SDNode *User = *UI;
9393       if (User != N && !Visited.count(User))
9394         return SDValue();
9395
9396       // Make sure that we're not going to promote the non-output-value
9397       // operand(s) or SELECT or SELECT_CC.
9398       // FIXME: Although we could sometimes handle this, and it does occur in
9399       // practice that one of the condition inputs to the select is also one of
9400       // the outputs, we currently can't deal with this.
9401       if (User->getOpcode() == ISD::SELECT) {
9402         if (User->getOperand(0) == PromOps[i])
9403           return SDValue();
9404       } else if (User->getOpcode() == ISD::SELECT_CC) {
9405         if (User->getOperand(0) == PromOps[i] ||
9406             User->getOperand(1) == PromOps[i])
9407           return SDValue();
9408       }
9409     }
9410   }
9411
9412   // Replace all inputs with the extension operand.
9413   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9414     // Constants may have users outside the cluster of to-be-promoted nodes,
9415     // and so we need to replace those as we do the promotions.
9416     if (isa<ConstantSDNode>(Inputs[i]))
9417       continue;
9418     else
9419       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
9420   }
9421
9422   // Replace all operations (these are all the same, but have a different
9423   // (i1) return type). DAG.getNode will validate that the types of
9424   // a binary operator match, so go through the list in reverse so that
9425   // we've likely promoted both operands first. Any intermediate truncations or
9426   // extensions disappear.
9427   while (!PromOps.empty()) {
9428     SDValue PromOp = PromOps.back();
9429     PromOps.pop_back();
9430
9431     if (PromOp.getOpcode() == ISD::TRUNCATE ||
9432         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
9433         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
9434         PromOp.getOpcode() == ISD::ANY_EXTEND) {
9435       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
9436           PromOp.getOperand(0).getValueType() != MVT::i1) {
9437         // The operand is not yet ready (see comment below).
9438         PromOps.insert(PromOps.begin(), PromOp);
9439         continue;
9440       }
9441
9442       SDValue RepValue = PromOp.getOperand(0);
9443       if (isa<ConstantSDNode>(RepValue))
9444         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
9445
9446       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
9447       continue;
9448     }
9449
9450     unsigned C;
9451     switch (PromOp.getOpcode()) {
9452     default:             C = 0; break;
9453     case ISD::SELECT:    C = 1; break;
9454     case ISD::SELECT_CC: C = 2; break;
9455     }
9456
9457     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9458          PromOp.getOperand(C).getValueType() != MVT::i1) ||
9459         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9460          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
9461       // The to-be-promoted operands of this node have not yet been
9462       // promoted (this should be rare because we're going through the
9463       // list backward, but if one of the operands has several users in
9464       // this cluster of to-be-promoted nodes, it is possible).
9465       PromOps.insert(PromOps.begin(), PromOp);
9466       continue;
9467     }
9468
9469     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9470                                 PromOp.getNode()->op_end());
9471
9472     // If there are any constant inputs, make sure they're replaced now.
9473     for (unsigned i = 0; i < 2; ++i)
9474       if (isa<ConstantSDNode>(Ops[C+i]))
9475         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
9476
9477     DAG.ReplaceAllUsesOfValueWith(PromOp,
9478       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
9479   }
9480
9481   // Now we're left with the initial truncation itself.
9482   if (N->getOpcode() == ISD::TRUNCATE)
9483     return N->getOperand(0);
9484
9485   // Otherwise, this is a comparison. The operands to be compared have just
9486   // changed type (to i1), but everything else is the same.
9487   return SDValue(N, 0);
9488 }
9489
9490 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
9491                                                   DAGCombinerInfo &DCI) const {
9492   SelectionDAG &DAG = DCI.DAG;
9493   SDLoc dl(N);
9494
9495   // If we're tracking CR bits, we need to be careful that we don't have:
9496   //   zext(binary-ops(trunc(x), trunc(y)))
9497   // or
9498   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
9499   // such that we're unnecessarily moving things into CR bits that can more
9500   // efficiently stay in GPRs. Note that if we're not certain that the high
9501   // bits are set as required by the final extension, we still may need to do
9502   // some masking to get the proper behavior.
9503
9504   // This same functionality is important on PPC64 when dealing with
9505   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
9506   // the return values of functions. Because it is so similar, it is handled
9507   // here as well.
9508
9509   if (N->getValueType(0) != MVT::i32 &&
9510       N->getValueType(0) != MVT::i64)
9511     return SDValue();
9512
9513   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
9514         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
9515     return SDValue();
9516
9517   if (N->getOperand(0).getOpcode() != ISD::AND &&
9518       N->getOperand(0).getOpcode() != ISD::OR  &&
9519       N->getOperand(0).getOpcode() != ISD::XOR &&
9520       N->getOperand(0).getOpcode() != ISD::SELECT &&
9521       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
9522     return SDValue();
9523
9524   SmallVector<SDValue, 4> Inputs;
9525   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
9526   SmallPtrSet<SDNode *, 16> Visited;
9527
9528   // Visit all inputs, collect all binary operations (and, or, xor and
9529   // select) that are all fed by truncations. 
9530   while (!BinOps.empty()) {
9531     SDValue BinOp = BinOps.back();
9532     BinOps.pop_back();
9533
9534     if (!Visited.insert(BinOp.getNode()).second)
9535       continue;
9536
9537     PromOps.push_back(BinOp);
9538
9539     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
9540       // The condition of the select is not promoted.
9541       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
9542         continue;
9543       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
9544         continue;
9545
9546       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
9547           isa<ConstantSDNode>(BinOp.getOperand(i))) {
9548         Inputs.push_back(BinOp.getOperand(i)); 
9549       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
9550                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
9551                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
9552                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
9553                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
9554         BinOps.push_back(BinOp.getOperand(i));
9555       } else {
9556         // We have an input that is not a truncation or another binary
9557         // operation; we'll abort this transformation.
9558         return SDValue();
9559       }
9560     }
9561   }
9562
9563   // The operands of a select that must be truncated when the select is
9564   // promoted because the operand is actually part of the to-be-promoted set.
9565   DenseMap<SDNode *, EVT> SelectTruncOp[2];
9566
9567   // Make sure that this is a self-contained cluster of operations (which
9568   // is not quite the same thing as saying that everything has only one
9569   // use).
9570   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9571     if (isa<ConstantSDNode>(Inputs[i]))
9572       continue;
9573
9574     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
9575                               UE = Inputs[i].getNode()->use_end();
9576          UI != UE; ++UI) {
9577       SDNode *User = *UI;
9578       if (User != N && !Visited.count(User))
9579         return SDValue();
9580
9581       // If we're going to promote the non-output-value operand(s) or SELECT or
9582       // SELECT_CC, record them for truncation.
9583       if (User->getOpcode() == ISD::SELECT) {
9584         if (User->getOperand(0) == Inputs[i])
9585           SelectTruncOp[0].insert(std::make_pair(User,
9586                                     User->getOperand(0).getValueType()));
9587       } else if (User->getOpcode() == ISD::SELECT_CC) {
9588         if (User->getOperand(0) == Inputs[i])
9589           SelectTruncOp[0].insert(std::make_pair(User,
9590                                     User->getOperand(0).getValueType()));
9591         if (User->getOperand(1) == Inputs[i])
9592           SelectTruncOp[1].insert(std::make_pair(User,
9593                                     User->getOperand(1).getValueType()));
9594       }
9595     }
9596   }
9597
9598   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
9599     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
9600                               UE = PromOps[i].getNode()->use_end();
9601          UI != UE; ++UI) {
9602       SDNode *User = *UI;
9603       if (User != N && !Visited.count(User))
9604         return SDValue();
9605
9606       // If we're going to promote the non-output-value operand(s) or SELECT or
9607       // SELECT_CC, record them for truncation.
9608       if (User->getOpcode() == ISD::SELECT) {
9609         if (User->getOperand(0) == PromOps[i])
9610           SelectTruncOp[0].insert(std::make_pair(User,
9611                                     User->getOperand(0).getValueType()));
9612       } else if (User->getOpcode() == ISD::SELECT_CC) {
9613         if (User->getOperand(0) == PromOps[i])
9614           SelectTruncOp[0].insert(std::make_pair(User,
9615                                     User->getOperand(0).getValueType()));
9616         if (User->getOperand(1) == PromOps[i])
9617           SelectTruncOp[1].insert(std::make_pair(User,
9618                                     User->getOperand(1).getValueType()));
9619       }
9620     }
9621   }
9622
9623   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
9624   bool ReallyNeedsExt = false;
9625   if (N->getOpcode() != ISD::ANY_EXTEND) {
9626     // If all of the inputs are not already sign/zero extended, then
9627     // we'll still need to do that at the end.
9628     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9629       if (isa<ConstantSDNode>(Inputs[i]))
9630         continue;
9631
9632       unsigned OpBits =
9633         Inputs[i].getOperand(0).getValueSizeInBits();
9634       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
9635
9636       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
9637            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
9638                                   APInt::getHighBitsSet(OpBits,
9639                                                         OpBits-PromBits))) ||
9640           (N->getOpcode() == ISD::SIGN_EXTEND &&
9641            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
9642              (OpBits-(PromBits-1)))) {
9643         ReallyNeedsExt = true;
9644         break;
9645       }
9646     }
9647   }
9648
9649   // Replace all inputs, either with the truncation operand, or a
9650   // truncation or extension to the final output type.
9651   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
9652     // Constant inputs need to be replaced with the to-be-promoted nodes that
9653     // use them because they might have users outside of the cluster of
9654     // promoted nodes.
9655     if (isa<ConstantSDNode>(Inputs[i]))
9656       continue;
9657
9658     SDValue InSrc = Inputs[i].getOperand(0);
9659     if (Inputs[i].getValueType() == N->getValueType(0))
9660       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
9661     else if (N->getOpcode() == ISD::SIGN_EXTEND)
9662       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9663         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
9664     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9665       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9666         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
9667     else
9668       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
9669         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
9670   }
9671
9672   // Replace all operations (these are all the same, but have a different
9673   // (promoted) return type). DAG.getNode will validate that the types of
9674   // a binary operator match, so go through the list in reverse so that
9675   // we've likely promoted both operands first.
9676   while (!PromOps.empty()) {
9677     SDValue PromOp = PromOps.back();
9678     PromOps.pop_back();
9679
9680     unsigned C;
9681     switch (PromOp.getOpcode()) {
9682     default:             C = 0; break;
9683     case ISD::SELECT:    C = 1; break;
9684     case ISD::SELECT_CC: C = 2; break;
9685     }
9686
9687     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
9688          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
9689         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
9690          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
9691       // The to-be-promoted operands of this node have not yet been
9692       // promoted (this should be rare because we're going through the
9693       // list backward, but if one of the operands has several users in
9694       // this cluster of to-be-promoted nodes, it is possible).
9695       PromOps.insert(PromOps.begin(), PromOp);
9696       continue;
9697     }
9698
9699     // For SELECT and SELECT_CC nodes, we do a similar check for any
9700     // to-be-promoted comparison inputs.
9701     if (PromOp.getOpcode() == ISD::SELECT ||
9702         PromOp.getOpcode() == ISD::SELECT_CC) {
9703       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
9704            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
9705           (SelectTruncOp[1].count(PromOp.getNode()) &&
9706            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
9707         PromOps.insert(PromOps.begin(), PromOp);
9708         continue;
9709       }
9710     }
9711
9712     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
9713                                 PromOp.getNode()->op_end());
9714
9715     // If this node has constant inputs, then they'll need to be promoted here.
9716     for (unsigned i = 0; i < 2; ++i) {
9717       if (!isa<ConstantSDNode>(Ops[C+i]))
9718         continue;
9719       if (Ops[C+i].getValueType() == N->getValueType(0))
9720         continue;
9721
9722       if (N->getOpcode() == ISD::SIGN_EXTEND)
9723         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9724       else if (N->getOpcode() == ISD::ZERO_EXTEND)
9725         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9726       else
9727         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
9728     }
9729
9730     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
9731     // truncate them again to the original value type.
9732     if (PromOp.getOpcode() == ISD::SELECT ||
9733         PromOp.getOpcode() == ISD::SELECT_CC) {
9734       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
9735       if (SI0 != SelectTruncOp[0].end())
9736         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
9737       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
9738       if (SI1 != SelectTruncOp[1].end())
9739         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
9740     }
9741
9742     DAG.ReplaceAllUsesOfValueWith(PromOp,
9743       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
9744   }
9745
9746   // Now we're left with the initial extension itself.
9747   if (!ReallyNeedsExt)
9748     return N->getOperand(0);
9749
9750   // To zero extend, just mask off everything except for the first bit (in the
9751   // i1 case).
9752   if (N->getOpcode() == ISD::ZERO_EXTEND)
9753     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
9754                        DAG.getConstant(APInt::getLowBitsSet(
9755                                          N->getValueSizeInBits(0), PromBits),
9756                                        dl, N->getValueType(0)));
9757
9758   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
9759          "Invalid extension type");
9760   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
9761   SDValue ShiftCst =
9762     DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
9763   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
9764                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
9765                                  N->getOperand(0), ShiftCst), ShiftCst);
9766 }
9767
9768 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
9769                                               DAGCombinerInfo &DCI) const {
9770   assert((N->getOpcode() == ISD::SINT_TO_FP ||
9771           N->getOpcode() == ISD::UINT_TO_FP) &&
9772          "Need an int -> FP conversion node here");
9773
9774   if (!Subtarget.has64BitSupport())
9775     return SDValue();
9776
9777   SelectionDAG &DAG = DCI.DAG;
9778   SDLoc dl(N);
9779   SDValue Op(N, 0);
9780
9781   // Don't handle ppc_fp128 here or i1 conversions.
9782   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
9783     return SDValue();
9784   if (Op.getOperand(0).getValueType() == MVT::i1)
9785     return SDValue();
9786
9787   // For i32 intermediate values, unfortunately, the conversion functions
9788   // leave the upper 32 bits of the value are undefined. Within the set of
9789   // scalar instructions, we have no method for zero- or sign-extending the
9790   // value. Thus, we cannot handle i32 intermediate values here.
9791   if (Op.getOperand(0).getValueType() == MVT::i32)
9792     return SDValue();
9793
9794   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
9795          "UINT_TO_FP is supported only with FPCVT");
9796
9797   // If we have FCFIDS, then use it when converting to single-precision.
9798   // Otherwise, convert to double-precision and then round.
9799   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9800                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
9801                                                             : PPCISD::FCFIDS)
9802                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
9803                                                             : PPCISD::FCFID);
9804   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
9805                   ? MVT::f32
9806                   : MVT::f64;
9807
9808   // If we're converting from a float, to an int, and back to a float again,
9809   // then we don't need the store/load pair at all.
9810   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
9811        Subtarget.hasFPCVT()) ||
9812       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
9813     SDValue Src = Op.getOperand(0).getOperand(0);
9814     if (Src.getValueType() == MVT::f32) {
9815       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
9816       DCI.AddToWorklist(Src.getNode());
9817     }
9818
9819     unsigned FCTOp =
9820       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
9821                                                         PPCISD::FCTIDUZ;
9822
9823     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
9824     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
9825
9826     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9827       FP = DAG.getNode(ISD::FP_ROUND, dl,
9828                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
9829       DCI.AddToWorklist(FP.getNode());
9830     }
9831
9832     return FP;
9833   }
9834
9835   return SDValue();
9836 }
9837
9838 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
9839 // builtins) into loads with swaps.
9840 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
9841                                               DAGCombinerInfo &DCI) const {
9842   SelectionDAG &DAG = DCI.DAG;
9843   SDLoc dl(N);
9844   SDValue Chain;
9845   SDValue Base;
9846   MachineMemOperand *MMO;
9847
9848   switch (N->getOpcode()) {
9849   default:
9850     llvm_unreachable("Unexpected opcode for little endian VSX load");
9851   case ISD::LOAD: {
9852     LoadSDNode *LD = cast<LoadSDNode>(N);
9853     Chain = LD->getChain();
9854     Base = LD->getBasePtr();
9855     MMO = LD->getMemOperand();
9856     // If the MMO suggests this isn't a load of a full vector, leave
9857     // things alone.  For a built-in, we have to make the change for
9858     // correctness, so if there is a size problem that will be a bug.
9859     if (MMO->getSize() < 16)
9860       return SDValue();
9861     break;
9862   }
9863   case ISD::INTRINSIC_W_CHAIN: {
9864     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9865     Chain = Intrin->getChain();
9866     Base = Intrin->getBasePtr();
9867     MMO = Intrin->getMemOperand();
9868     break;
9869   }
9870   }
9871
9872   MVT VecTy = N->getValueType(0).getSimpleVT();
9873   SDValue LoadOps[] = { Chain, Base };
9874   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
9875                                          DAG.getVTList(VecTy, MVT::Other),
9876                                          LoadOps, VecTy, MMO);
9877   DCI.AddToWorklist(Load.getNode());
9878   Chain = Load.getValue(1);
9879   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9880                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
9881   DCI.AddToWorklist(Swap.getNode());
9882   return Swap;
9883 }
9884
9885 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
9886 // builtins) into stores with swaps.
9887 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
9888                                                DAGCombinerInfo &DCI) const {
9889   SelectionDAG &DAG = DCI.DAG;
9890   SDLoc dl(N);
9891   SDValue Chain;
9892   SDValue Base;
9893   unsigned SrcOpnd;
9894   MachineMemOperand *MMO;
9895
9896   switch (N->getOpcode()) {
9897   default:
9898     llvm_unreachable("Unexpected opcode for little endian VSX store");
9899   case ISD::STORE: {
9900     StoreSDNode *ST = cast<StoreSDNode>(N);
9901     Chain = ST->getChain();
9902     Base = ST->getBasePtr();
9903     MMO = ST->getMemOperand();
9904     SrcOpnd = 1;
9905     // If the MMO suggests this isn't a store of a full vector, leave
9906     // things alone.  For a built-in, we have to make the change for
9907     // correctness, so if there is a size problem that will be a bug.
9908     if (MMO->getSize() < 16)
9909       return SDValue();
9910     break;
9911   }
9912   case ISD::INTRINSIC_VOID: {
9913     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
9914     Chain = Intrin->getChain();
9915     // Intrin->getBasePtr() oddly does not get what we want.
9916     Base = Intrin->getOperand(3);
9917     MMO = Intrin->getMemOperand();
9918     SrcOpnd = 2;
9919     break;
9920   }
9921   }
9922
9923   SDValue Src = N->getOperand(SrcOpnd);
9924   MVT VecTy = Src.getValueType().getSimpleVT();
9925   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
9926                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
9927   DCI.AddToWorklist(Swap.getNode());
9928   Chain = Swap.getValue(1);
9929   SDValue StoreOps[] = { Chain, Swap, Base };
9930   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
9931                                           DAG.getVTList(MVT::Other),
9932                                           StoreOps, VecTy, MMO);
9933   DCI.AddToWorklist(Store.getNode());
9934   return Store;
9935 }
9936
9937 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
9938                                              DAGCombinerInfo &DCI) const {
9939   SelectionDAG &DAG = DCI.DAG;
9940   SDLoc dl(N);
9941   switch (N->getOpcode()) {
9942   default: break;
9943   case PPCISD::SHL:
9944     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9945       if (C->isNullValue())   // 0 << V -> 0.
9946         return N->getOperand(0);
9947     }
9948     break;
9949   case PPCISD::SRL:
9950     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9951       if (C->isNullValue())   // 0 >>u V -> 0.
9952         return N->getOperand(0);
9953     }
9954     break;
9955   case PPCISD::SRA:
9956     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9957       if (C->isNullValue() ||   //  0 >>s V -> 0.
9958           C->isAllOnesValue())    // -1 >>s V -> -1.
9959         return N->getOperand(0);
9960     }
9961     break;
9962   case ISD::SIGN_EXTEND:
9963   case ISD::ZERO_EXTEND:
9964   case ISD::ANY_EXTEND: 
9965     return DAGCombineExtBoolTrunc(N, DCI);
9966   case ISD::TRUNCATE:
9967   case ISD::SETCC:
9968   case ISD::SELECT_CC:
9969     return DAGCombineTruncBoolExt(N, DCI);
9970   case ISD::SINT_TO_FP:
9971   case ISD::UINT_TO_FP:
9972     return combineFPToIntToFP(N, DCI);
9973   case ISD::STORE: {
9974     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
9975     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
9976         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
9977         N->getOperand(1).getValueType() == MVT::i32 &&
9978         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
9979       SDValue Val = N->getOperand(1).getOperand(0);
9980       if (Val.getValueType() == MVT::f32) {
9981         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
9982         DCI.AddToWorklist(Val.getNode());
9983       }
9984       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
9985       DCI.AddToWorklist(Val.getNode());
9986
9987       SDValue Ops[] = {
9988         N->getOperand(0), Val, N->getOperand(2),
9989         DAG.getValueType(N->getOperand(1).getValueType())
9990       };
9991
9992       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
9993               DAG.getVTList(MVT::Other), Ops,
9994               cast<StoreSDNode>(N)->getMemoryVT(),
9995               cast<StoreSDNode>(N)->getMemOperand());
9996       DCI.AddToWorklist(Val.getNode());
9997       return Val;
9998     }
9999
10000     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
10001     if (cast<StoreSDNode>(N)->isUnindexed() &&
10002         N->getOperand(1).getOpcode() == ISD::BSWAP &&
10003         N->getOperand(1).getNode()->hasOneUse() &&
10004         (N->getOperand(1).getValueType() == MVT::i32 ||
10005          N->getOperand(1).getValueType() == MVT::i16 ||
10006          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10007           N->getOperand(1).getValueType() == MVT::i64))) {
10008       SDValue BSwapOp = N->getOperand(1).getOperand(0);
10009       // Do an any-extend to 32-bits if this is a half-word input.
10010       if (BSwapOp.getValueType() == MVT::i16)
10011         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
10012
10013       SDValue Ops[] = {
10014         N->getOperand(0), BSwapOp, N->getOperand(2),
10015         DAG.getValueType(N->getOperand(1).getValueType())
10016       };
10017       return
10018         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
10019                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
10020                                 cast<StoreSDNode>(N)->getMemOperand());
10021     }
10022
10023     // For little endian, VSX stores require generating xxswapd/lxvd2x.
10024     EVT VT = N->getOperand(1).getValueType();
10025     if (VT.isSimple()) {
10026       MVT StoreVT = VT.getSimpleVT();
10027       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10028           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
10029            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
10030         return expandVSXStoreForLE(N, DCI);
10031     }
10032     break;
10033   }
10034   case ISD::LOAD: {
10035     LoadSDNode *LD = cast<LoadSDNode>(N);
10036     EVT VT = LD->getValueType(0);
10037
10038     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10039     if (VT.isSimple()) {
10040       MVT LoadVT = VT.getSimpleVT();
10041       if (Subtarget.hasVSX() && Subtarget.isLittleEndian() &&
10042           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
10043            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
10044         return expandVSXLoadForLE(N, DCI);
10045     }
10046
10047     EVT MemVT = LD->getMemoryVT();
10048     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
10049     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
10050     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
10051     unsigned ScalarABIAlignment = getDataLayout()->getABITypeAlignment(STy);
10052     if (LD->isUnindexed() && VT.isVector() &&
10053         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
10054           // P8 and later hardware should just use LOAD.
10055           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
10056                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
10057          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
10058           LD->getAlignment() >= ScalarABIAlignment)) &&
10059         LD->getAlignment() < ABIAlignment) {
10060       // This is a type-legal unaligned Altivec or QPX load.
10061       SDValue Chain = LD->getChain();
10062       SDValue Ptr = LD->getBasePtr();
10063       bool isLittleEndian = Subtarget.isLittleEndian();
10064
10065       // This implements the loading of unaligned vectors as described in
10066       // the venerable Apple Velocity Engine overview. Specifically:
10067       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
10068       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
10069       //
10070       // The general idea is to expand a sequence of one or more unaligned
10071       // loads into an alignment-based permutation-control instruction (lvsl
10072       // or lvsr), a series of regular vector loads (which always truncate
10073       // their input address to an aligned address), and a series of
10074       // permutations.  The results of these permutations are the requested
10075       // loaded values.  The trick is that the last "extra" load is not taken
10076       // from the address you might suspect (sizeof(vector) bytes after the
10077       // last requested load), but rather sizeof(vector) - 1 bytes after the
10078       // last requested vector. The point of this is to avoid a page fault if
10079       // the base address happened to be aligned. This works because if the
10080       // base address is aligned, then adding less than a full vector length
10081       // will cause the last vector in the sequence to be (re)loaded.
10082       // Otherwise, the next vector will be fetched as you might suspect was
10083       // necessary.
10084
10085       // We might be able to reuse the permutation generation from
10086       // a different base address offset from this one by an aligned amount.
10087       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
10088       // optimization later.
10089       Intrinsic::ID Intr, IntrLD, IntrPerm;
10090       MVT PermCntlTy, PermTy, LDTy;
10091       if (Subtarget.hasAltivec()) {
10092         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
10093                                  Intrinsic::ppc_altivec_lvsl;
10094         IntrLD = Intrinsic::ppc_altivec_lvx;
10095         IntrPerm = Intrinsic::ppc_altivec_vperm;
10096         PermCntlTy = MVT::v16i8;
10097         PermTy = MVT::v4i32;
10098         LDTy = MVT::v4i32;
10099       } else {
10100         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
10101                                        Intrinsic::ppc_qpx_qvlpcls;
10102         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
10103                                        Intrinsic::ppc_qpx_qvlfs;
10104         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
10105         PermCntlTy = MVT::v4f64;
10106         PermTy = MVT::v4f64;
10107         LDTy = MemVT.getSimpleVT();
10108       }
10109
10110       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
10111
10112       // Create the new MMO for the new base load. It is like the original MMO,
10113       // but represents an area in memory almost twice the vector size centered
10114       // on the original address. If the address is unaligned, we might start
10115       // reading up to (sizeof(vector)-1) bytes below the address of the
10116       // original unaligned load.
10117       MachineFunction &MF = DAG.getMachineFunction();
10118       MachineMemOperand *BaseMMO =
10119         MF.getMachineMemOperand(LD->getMemOperand(), -MemVT.getStoreSize()+1,
10120                                 2*MemVT.getStoreSize()-1);
10121
10122       // Create the new base load.
10123       SDValue LDXIntID = DAG.getTargetConstant(IntrLD, dl, getPointerTy());
10124       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
10125       SDValue BaseLoad =
10126         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10127                                 DAG.getVTList(PermTy, MVT::Other),
10128                                 BaseLoadOps, LDTy, BaseMMO);
10129
10130       // Note that the value of IncOffset (which is provided to the next
10131       // load's pointer info offset value, and thus used to calculate the
10132       // alignment), and the value of IncValue (which is actually used to
10133       // increment the pointer value) are different! This is because we
10134       // require the next load to appear to be aligned, even though it
10135       // is actually offset from the base pointer by a lesser amount.
10136       int IncOffset = VT.getSizeInBits() / 8;
10137       int IncValue = IncOffset;
10138
10139       // Walk (both up and down) the chain looking for another load at the real
10140       // (aligned) offset (the alignment of the other load does not matter in
10141       // this case). If found, then do not use the offset reduction trick, as
10142       // that will prevent the loads from being later combined (as they would
10143       // otherwise be duplicates).
10144       if (!findConsecutiveLoad(LD, DAG))
10145         --IncValue;
10146
10147       SDValue Increment = DAG.getConstant(IncValue, dl, getPointerTy());
10148       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
10149
10150       MachineMemOperand *ExtraMMO =
10151         MF.getMachineMemOperand(LD->getMemOperand(),
10152                                 1, 2*MemVT.getStoreSize()-1);
10153       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
10154       SDValue ExtraLoad =
10155         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
10156                                 DAG.getVTList(PermTy, MVT::Other),
10157                                 ExtraLoadOps, LDTy, ExtraMMO);
10158
10159       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
10160         BaseLoad.getValue(1), ExtraLoad.getValue(1));
10161
10162       // Because vperm has a big-endian bias, we must reverse the order
10163       // of the input vectors and complement the permute control vector
10164       // when generating little endian code.  We have already handled the
10165       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
10166       // and ExtraLoad here.
10167       SDValue Perm;
10168       if (isLittleEndian)
10169         Perm = BuildIntrinsicOp(IntrPerm,
10170                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
10171       else
10172         Perm = BuildIntrinsicOp(IntrPerm,
10173                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
10174
10175       if (VT != PermTy)
10176         Perm = Subtarget.hasAltivec() ?
10177                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
10178                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
10179                                DAG.getTargetConstant(1, dl, MVT::i64));
10180                                // second argument is 1 because this rounding
10181                                // is always exact.
10182
10183       // The output of the permutation is our loaded result, the TokenFactor is
10184       // our new chain.
10185       DCI.CombineTo(N, Perm, TF);
10186       return SDValue(N, 0);
10187     }
10188     }
10189     break;
10190     case ISD::INTRINSIC_WO_CHAIN: {
10191       bool isLittleEndian = Subtarget.isLittleEndian();
10192       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10193       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
10194                                            : Intrinsic::ppc_altivec_lvsl);
10195       if ((IID == Intr ||
10196            IID == Intrinsic::ppc_qpx_qvlpcld  ||
10197            IID == Intrinsic::ppc_qpx_qvlpcls) &&
10198         N->getOperand(1)->getOpcode() == ISD::ADD) {
10199         SDValue Add = N->getOperand(1);
10200
10201         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
10202                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
10203
10204         if (DAG.MaskedValueIsZero(
10205                 Add->getOperand(1),
10206                 APInt::getAllOnesValue(Bits /* alignment */)
10207                     .zext(
10208                         Add.getValueType().getScalarType().getSizeInBits()))) {
10209           SDNode *BasePtr = Add->getOperand(0).getNode();
10210           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10211                                     UE = BasePtr->use_end();
10212                UI != UE; ++UI) {
10213             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10214                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
10215               // We've found another LVSL/LVSR, and this address is an aligned
10216               // multiple of that one. The results will be the same, so use the
10217               // one we've just found instead.
10218
10219               return SDValue(*UI, 0);
10220             }
10221           }
10222         }
10223
10224         if (isa<ConstantSDNode>(Add->getOperand(1))) {
10225           SDNode *BasePtr = Add->getOperand(0).getNode();
10226           for (SDNode::use_iterator UI = BasePtr->use_begin(),
10227                UE = BasePtr->use_end(); UI != UE; ++UI) {
10228             if (UI->getOpcode() == ISD::ADD &&
10229                 isa<ConstantSDNode>(UI->getOperand(1)) &&
10230                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
10231                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
10232                 (1ULL << Bits) == 0) {
10233               SDNode *OtherAdd = *UI;
10234               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
10235                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
10236                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10237                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
10238                   return SDValue(*VI, 0);
10239                 }
10240               }
10241             }
10242           }
10243         }
10244       }
10245     }
10246
10247     break;
10248   case ISD::INTRINSIC_W_CHAIN: {
10249     // For little endian, VSX loads require generating lxvd2x/xxswapd.
10250     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10251       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10252       default:
10253         break;
10254       case Intrinsic::ppc_vsx_lxvw4x:
10255       case Intrinsic::ppc_vsx_lxvd2x:
10256         return expandVSXLoadForLE(N, DCI);
10257       }
10258     }
10259     break;
10260   }
10261   case ISD::INTRINSIC_VOID: {
10262     // For little endian, VSX stores require generating xxswapd/stxvd2x.
10263     if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) {
10264       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10265       default:
10266         break;
10267       case Intrinsic::ppc_vsx_stxvw4x:
10268       case Intrinsic::ppc_vsx_stxvd2x:
10269         return expandVSXStoreForLE(N, DCI);
10270       }
10271     }
10272     break;
10273   }
10274   case ISD::BSWAP:
10275     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
10276     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
10277         N->getOperand(0).hasOneUse() &&
10278         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
10279          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
10280           N->getValueType(0) == MVT::i64))) {
10281       SDValue Load = N->getOperand(0);
10282       LoadSDNode *LD = cast<LoadSDNode>(Load);
10283       // Create the byte-swapping load.
10284       SDValue Ops[] = {
10285         LD->getChain(),    // Chain
10286         LD->getBasePtr(),  // Ptr
10287         DAG.getValueType(N->getValueType(0)) // VT
10288       };
10289       SDValue BSLoad =
10290         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
10291                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
10292                                               MVT::i64 : MVT::i32, MVT::Other),
10293                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
10294
10295       // If this is an i16 load, insert the truncate.
10296       SDValue ResVal = BSLoad;
10297       if (N->getValueType(0) == MVT::i16)
10298         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
10299
10300       // First, combine the bswap away.  This makes the value produced by the
10301       // load dead.
10302       DCI.CombineTo(N, ResVal);
10303
10304       // Next, combine the load away, we give it a bogus result value but a real
10305       // chain result.  The result value is dead because the bswap is dead.
10306       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
10307
10308       // Return N so it doesn't get rechecked!
10309       return SDValue(N, 0);
10310     }
10311
10312     break;
10313   case PPCISD::VCMP: {
10314     // If a VCMPo node already exists with exactly the same operands as this
10315     // node, use its result instead of this node (VCMPo computes both a CR6 and
10316     // a normal output).
10317     //
10318     if (!N->getOperand(0).hasOneUse() &&
10319         !N->getOperand(1).hasOneUse() &&
10320         !N->getOperand(2).hasOneUse()) {
10321
10322       // Scan all of the users of the LHS, looking for VCMPo's that match.
10323       SDNode *VCMPoNode = nullptr;
10324
10325       SDNode *LHSN = N->getOperand(0).getNode();
10326       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
10327            UI != E; ++UI)
10328         if (UI->getOpcode() == PPCISD::VCMPo &&
10329             UI->getOperand(1) == N->getOperand(1) &&
10330             UI->getOperand(2) == N->getOperand(2) &&
10331             UI->getOperand(0) == N->getOperand(0)) {
10332           VCMPoNode = *UI;
10333           break;
10334         }
10335
10336       // If there is no VCMPo node, or if the flag value has a single use, don't
10337       // transform this.
10338       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
10339         break;
10340
10341       // Look at the (necessarily single) use of the flag value.  If it has a
10342       // chain, this transformation is more complex.  Note that multiple things
10343       // could use the value result, which we should ignore.
10344       SDNode *FlagUser = nullptr;
10345       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
10346            FlagUser == nullptr; ++UI) {
10347         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
10348         SDNode *User = *UI;
10349         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
10350           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
10351             FlagUser = User;
10352             break;
10353           }
10354         }
10355       }
10356
10357       // If the user is a MFOCRF instruction, we know this is safe.
10358       // Otherwise we give up for right now.
10359       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
10360         return SDValue(VCMPoNode, 0);
10361     }
10362     break;
10363   }
10364   case ISD::BRCOND: {
10365     SDValue Cond = N->getOperand(1);
10366     SDValue Target = N->getOperand(2);
10367  
10368     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10369         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
10370           Intrinsic::ppc_is_decremented_ctr_nonzero) {
10371
10372       // We now need to make the intrinsic dead (it cannot be instruction
10373       // selected).
10374       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
10375       assert(Cond.getNode()->hasOneUse() &&
10376              "Counter decrement has more than one use");
10377
10378       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
10379                          N->getOperand(0), Target);
10380     }
10381   }
10382   break;
10383   case ISD::BR_CC: {
10384     // If this is a branch on an altivec predicate comparison, lower this so
10385     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
10386     // lowering is done pre-legalize, because the legalizer lowers the predicate
10387     // compare down to code that is difficult to reassemble.
10388     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
10389     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
10390
10391     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
10392     // value. If so, pass-through the AND to get to the intrinsic.
10393     if (LHS.getOpcode() == ISD::AND &&
10394         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10395         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
10396           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10397         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10398         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
10399           isZero())
10400       LHS = LHS.getOperand(0);
10401
10402     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
10403         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
10404           Intrinsic::ppc_is_decremented_ctr_nonzero &&
10405         isa<ConstantSDNode>(RHS)) {
10406       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10407              "Counter decrement comparison is not EQ or NE");
10408
10409       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10410       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
10411                     (CC == ISD::SETNE && !Val);
10412
10413       // We now need to make the intrinsic dead (it cannot be instruction
10414       // selected).
10415       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
10416       assert(LHS.getNode()->hasOneUse() &&
10417              "Counter decrement has more than one use");
10418
10419       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
10420                          N->getOperand(0), N->getOperand(4));
10421     }
10422
10423     int CompareOpc;
10424     bool isDot;
10425
10426     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
10427         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
10428         getAltivecCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
10429       assert(isDot && "Can't compare against a vector result!");
10430
10431       // If this is a comparison against something other than 0/1, then we know
10432       // that the condition is never/always true.
10433       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
10434       if (Val != 0 && Val != 1) {
10435         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
10436           return N->getOperand(0);
10437         // Always !=, turn it into an unconditional branch.
10438         return DAG.getNode(ISD::BR, dl, MVT::Other,
10439                            N->getOperand(0), N->getOperand(4));
10440       }
10441
10442       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
10443
10444       // Create the PPCISD altivec 'dot' comparison node.
10445       SDValue Ops[] = {
10446         LHS.getOperand(2),  // LHS of compare
10447         LHS.getOperand(3),  // RHS of compare
10448         DAG.getConstant(CompareOpc, dl, MVT::i32)
10449       };
10450       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
10451       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10452
10453       // Unpack the result based on how the target uses it.
10454       PPC::Predicate CompOpc;
10455       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
10456       default:  // Can't happen, don't crash on invalid number though.
10457       case 0:   // Branch on the value of the EQ bit of CR6.
10458         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
10459         break;
10460       case 1:   // Branch on the inverted value of the EQ bit of CR6.
10461         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
10462         break;
10463       case 2:   // Branch on the value of the LT bit of CR6.
10464         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
10465         break;
10466       case 3:   // Branch on the inverted value of the LT bit of CR6.
10467         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
10468         break;
10469       }
10470
10471       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
10472                          DAG.getConstant(CompOpc, dl, MVT::i32),
10473                          DAG.getRegister(PPC::CR6, MVT::i32),
10474                          N->getOperand(4), CompNode.getValue(1));
10475     }
10476     break;
10477   }
10478   }
10479
10480   return SDValue();
10481 }
10482
10483 SDValue
10484 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10485                                   SelectionDAG &DAG,
10486                                   std::vector<SDNode *> *Created) const {
10487   // fold (sdiv X, pow2)
10488   EVT VT = N->getValueType(0);
10489   if (VT == MVT::i64 && !Subtarget.isPPC64())
10490     return SDValue();
10491   if ((VT != MVT::i32 && VT != MVT::i64) ||
10492       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
10493     return SDValue();
10494
10495   SDLoc DL(N);
10496   SDValue N0 = N->getOperand(0);
10497
10498   bool IsNegPow2 = (-Divisor).isPowerOf2();
10499   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
10500   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
10501
10502   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
10503   if (Created)
10504     Created->push_back(Op.getNode());
10505
10506   if (IsNegPow2) {
10507     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
10508     if (Created)
10509       Created->push_back(Op.getNode());
10510   }
10511
10512   return Op;
10513 }
10514
10515 //===----------------------------------------------------------------------===//
10516 // Inline Assembly Support
10517 //===----------------------------------------------------------------------===//
10518
10519 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10520                                                       APInt &KnownZero,
10521                                                       APInt &KnownOne,
10522                                                       const SelectionDAG &DAG,
10523                                                       unsigned Depth) const {
10524   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
10525   switch (Op.getOpcode()) {
10526   default: break;
10527   case PPCISD::LBRX: {
10528     // lhbrx is known to have the top bits cleared out.
10529     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
10530       KnownZero = 0xFFFF0000;
10531     break;
10532   }
10533   case ISD::INTRINSIC_WO_CHAIN: {
10534     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
10535     default: break;
10536     case Intrinsic::ppc_altivec_vcmpbfp_p:
10537     case Intrinsic::ppc_altivec_vcmpeqfp_p:
10538     case Intrinsic::ppc_altivec_vcmpequb_p:
10539     case Intrinsic::ppc_altivec_vcmpequh_p:
10540     case Intrinsic::ppc_altivec_vcmpequw_p:
10541     case Intrinsic::ppc_altivec_vcmpequd_p:
10542     case Intrinsic::ppc_altivec_vcmpgefp_p:
10543     case Intrinsic::ppc_altivec_vcmpgtfp_p:
10544     case Intrinsic::ppc_altivec_vcmpgtsb_p:
10545     case Intrinsic::ppc_altivec_vcmpgtsh_p:
10546     case Intrinsic::ppc_altivec_vcmpgtsw_p:
10547     case Intrinsic::ppc_altivec_vcmpgtsd_p:
10548     case Intrinsic::ppc_altivec_vcmpgtub_p:
10549     case Intrinsic::ppc_altivec_vcmpgtuh_p:
10550     case Intrinsic::ppc_altivec_vcmpgtuw_p:
10551     case Intrinsic::ppc_altivec_vcmpgtud_p:
10552       KnownZero = ~1U;  // All bits but the low one are known to be zero.
10553       break;
10554     }
10555   }
10556   }
10557 }
10558
10559 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10560   switch (Subtarget.getDarwinDirective()) {
10561   default: break;
10562   case PPC::DIR_970:
10563   case PPC::DIR_PWR4:
10564   case PPC::DIR_PWR5:
10565   case PPC::DIR_PWR5X:
10566   case PPC::DIR_PWR6:
10567   case PPC::DIR_PWR6X:
10568   case PPC::DIR_PWR7:
10569   case PPC::DIR_PWR8: {
10570     if (!ML)
10571       break;
10572
10573     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
10574
10575     // For small loops (between 5 and 8 instructions), align to a 32-byte
10576     // boundary so that the entire loop fits in one instruction-cache line.
10577     uint64_t LoopSize = 0;
10578     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
10579       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
10580         LoopSize += TII->GetInstSizeInBytes(J);
10581
10582     if (LoopSize > 16 && LoopSize <= 32)
10583       return 5;
10584
10585     break;
10586   }
10587   }
10588
10589   return TargetLowering::getPrefLoopAlignment(ML);
10590 }
10591
10592 /// getConstraintType - Given a constraint, return the type of
10593 /// constraint it is for this target.
10594 PPCTargetLowering::ConstraintType
10595 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
10596   if (Constraint.size() == 1) {
10597     switch (Constraint[0]) {
10598     default: break;
10599     case 'b':
10600     case 'r':
10601     case 'f':
10602     case 'v':
10603     case 'y':
10604       return C_RegisterClass;
10605     case 'Z':
10606       // FIXME: While Z does indicate a memory constraint, it specifically
10607       // indicates an r+r address (used in conjunction with the 'y' modifier
10608       // in the replacement string). Currently, we're forcing the base
10609       // register to be r0 in the asm printer (which is interpreted as zero)
10610       // and forming the complete address in the second register. This is
10611       // suboptimal.
10612       return C_Memory;
10613     }
10614   } else if (Constraint == "wc") { // individual CR bits.
10615     return C_RegisterClass;
10616   } else if (Constraint == "wa" || Constraint == "wd" ||
10617              Constraint == "wf" || Constraint == "ws") {
10618     return C_RegisterClass; // VSX registers.
10619   }
10620   return TargetLowering::getConstraintType(Constraint);
10621 }
10622
10623 /// Examine constraint type and operand type and determine a weight value.
10624 /// This object must already have been set up with the operand type
10625 /// and the current alternative constraint selected.
10626 TargetLowering::ConstraintWeight
10627 PPCTargetLowering::getSingleConstraintMatchWeight(
10628     AsmOperandInfo &info, const char *constraint) const {
10629   ConstraintWeight weight = CW_Invalid;
10630   Value *CallOperandVal = info.CallOperandVal;
10631     // If we don't have a value, we can't do a match,
10632     // but allow it at the lowest weight.
10633   if (!CallOperandVal)
10634     return CW_Default;
10635   Type *type = CallOperandVal->getType();
10636
10637   // Look at the constraint type.
10638   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
10639     return CW_Register; // an individual CR bit.
10640   else if ((StringRef(constraint) == "wa" ||
10641             StringRef(constraint) == "wd" ||
10642             StringRef(constraint) == "wf") &&
10643            type->isVectorTy())
10644     return CW_Register;
10645   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
10646     return CW_Register;
10647
10648   switch (*constraint) {
10649   default:
10650     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10651     break;
10652   case 'b':
10653     if (type->isIntegerTy())
10654       weight = CW_Register;
10655     break;
10656   case 'f':
10657     if (type->isFloatTy())
10658       weight = CW_Register;
10659     break;
10660   case 'd':
10661     if (type->isDoubleTy())
10662       weight = CW_Register;
10663     break;
10664   case 'v':
10665     if (type->isVectorTy())
10666       weight = CW_Register;
10667     break;
10668   case 'y':
10669     weight = CW_Register;
10670     break;
10671   case 'Z':
10672     weight = CW_Memory;
10673     break;
10674   }
10675   return weight;
10676 }
10677
10678 std::pair<unsigned, const TargetRegisterClass *>
10679 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10680                                                 const std::string &Constraint,
10681                                                 MVT VT) const {
10682   if (Constraint.size() == 1) {
10683     // GCC RS6000 Constraint Letters
10684     switch (Constraint[0]) {
10685     case 'b':   // R1-R31
10686       if (VT == MVT::i64 && Subtarget.isPPC64())
10687         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
10688       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
10689     case 'r':   // R0-R31
10690       if (VT == MVT::i64 && Subtarget.isPPC64())
10691         return std::make_pair(0U, &PPC::G8RCRegClass);
10692       return std::make_pair(0U, &PPC::GPRCRegClass);
10693     case 'f':
10694       if (VT == MVT::f32 || VT == MVT::i32)
10695         return std::make_pair(0U, &PPC::F4RCRegClass);
10696       if (VT == MVT::f64 || VT == MVT::i64)
10697         return std::make_pair(0U, &PPC::F8RCRegClass);
10698       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10699         return std::make_pair(0U, &PPC::QFRCRegClass);
10700       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10701         return std::make_pair(0U, &PPC::QSRCRegClass);
10702       break;
10703     case 'v':
10704       if (VT == MVT::v4f64 && Subtarget.hasQPX())
10705         return std::make_pair(0U, &PPC::QFRCRegClass);
10706       if (VT == MVT::v4f32 && Subtarget.hasQPX())
10707         return std::make_pair(0U, &PPC::QSRCRegClass);
10708       return std::make_pair(0U, &PPC::VRRCRegClass);
10709     case 'y':   // crrc
10710       return std::make_pair(0U, &PPC::CRRCRegClass);
10711     }
10712   } else if (Constraint == "wc") { // an individual CR bit.
10713     return std::make_pair(0U, &PPC::CRBITRCRegClass);
10714   } else if (Constraint == "wa" || Constraint == "wd" ||
10715              Constraint == "wf") {
10716     return std::make_pair(0U, &PPC::VSRCRegClass);
10717   } else if (Constraint == "ws") {
10718     if (VT == MVT::f32)
10719       return std::make_pair(0U, &PPC::VSSRCRegClass);
10720     else
10721       return std::make_pair(0U, &PPC::VSFRCRegClass);
10722   }
10723
10724   std::pair<unsigned, const TargetRegisterClass *> R =
10725       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10726
10727   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
10728   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
10729   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
10730   // register.
10731   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
10732   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
10733   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
10734       PPC::GPRCRegClass.contains(R.first))
10735     return std::make_pair(TRI->getMatchingSuperReg(R.first,
10736                             PPC::sub_32, &PPC::G8RCRegClass),
10737                           &PPC::G8RCRegClass);
10738
10739   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
10740   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
10741     R.first = PPC::CR0;
10742     R.second = &PPC::CRRCRegClass;
10743   }
10744
10745   return R;
10746 }
10747
10748
10749 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10750 /// vector.  If it is invalid, don't add anything to Ops.
10751 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10752                                                      std::string &Constraint,
10753                                                      std::vector<SDValue>&Ops,
10754                                                      SelectionDAG &DAG) const {
10755   SDValue Result;
10756
10757   // Only support length 1 constraints.
10758   if (Constraint.length() > 1) return;
10759
10760   char Letter = Constraint[0];
10761   switch (Letter) {
10762   default: break;
10763   case 'I':
10764   case 'J':
10765   case 'K':
10766   case 'L':
10767   case 'M':
10768   case 'N':
10769   case 'O':
10770   case 'P': {
10771     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
10772     if (!CST) return; // Must be an immediate to match.
10773     SDLoc dl(Op);
10774     int64_t Value = CST->getSExtValue();
10775     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
10776                          // numbers are printed as such.
10777     switch (Letter) {
10778     default: llvm_unreachable("Unknown constraint letter!");
10779     case 'I':  // "I" is a signed 16-bit constant.
10780       if (isInt<16>(Value))
10781         Result = DAG.getTargetConstant(Value, dl, TCVT);
10782       break;
10783     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
10784       if (isShiftedUInt<16, 16>(Value))
10785         Result = DAG.getTargetConstant(Value, dl, TCVT);
10786       break;
10787     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
10788       if (isShiftedInt<16, 16>(Value))
10789         Result = DAG.getTargetConstant(Value, dl, TCVT);
10790       break;
10791     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
10792       if (isUInt<16>(Value))
10793         Result = DAG.getTargetConstant(Value, dl, TCVT);
10794       break;
10795     case 'M':  // "M" is a constant that is greater than 31.
10796       if (Value > 31)
10797         Result = DAG.getTargetConstant(Value, dl, TCVT);
10798       break;
10799     case 'N':  // "N" is a positive constant that is an exact power of two.
10800       if (Value > 0 && isPowerOf2_64(Value))
10801         Result = DAG.getTargetConstant(Value, dl, TCVT);
10802       break;
10803     case 'O':  // "O" is the constant zero.
10804       if (Value == 0)
10805         Result = DAG.getTargetConstant(Value, dl, TCVT);
10806       break;
10807     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
10808       if (isInt<16>(-Value))
10809         Result = DAG.getTargetConstant(Value, dl, TCVT);
10810       break;
10811     }
10812     break;
10813   }
10814   }
10815
10816   if (Result.getNode()) {
10817     Ops.push_back(Result);
10818     return;
10819   }
10820
10821   // Handle standard constraint letters.
10822   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10823 }
10824
10825 // isLegalAddressingMode - Return true if the addressing mode represented
10826 // by AM is legal for this target, for a load/store of the specified type.
10827 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10828                                               Type *Ty) const {
10829   // PPC does not allow r+i addressing modes for vectors!
10830   if (Ty->isVectorTy() && AM.BaseOffs != 0)
10831     return false;
10832
10833   // PPC allows a sign-extended 16-bit immediate field.
10834   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
10835     return false;
10836
10837   // No global is ever allowed as a base.
10838   if (AM.BaseGV)
10839     return false;
10840
10841   // PPC only support r+r,
10842   switch (AM.Scale) {
10843   case 0:  // "r+i" or just "i", depending on HasBaseReg.
10844     break;
10845   case 1:
10846     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
10847       return false;
10848     // Otherwise we have r+r or r+i.
10849     break;
10850   case 2:
10851     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
10852       return false;
10853     // Allow 2*r as r+r.
10854     break;
10855   default:
10856     // No other scales are supported.
10857     return false;
10858   }
10859
10860   return true;
10861 }
10862
10863 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
10864                                            SelectionDAG &DAG) const {
10865   MachineFunction &MF = DAG.getMachineFunction();
10866   MachineFrameInfo *MFI = MF.getFrameInfo();
10867   MFI->setReturnAddressIsTaken(true);
10868
10869   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
10870     return SDValue();
10871
10872   SDLoc dl(Op);
10873   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10874
10875   // Make sure the function does not optimize away the store of the RA to
10876   // the stack.
10877   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
10878   FuncInfo->setLRStoreRequired();
10879   bool isPPC64 = Subtarget.isPPC64();
10880
10881   if (Depth > 0) {
10882     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10883     SDValue Offset =
10884         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
10885                         isPPC64 ? MVT::i64 : MVT::i32);
10886     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10887                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10888                                    FrameAddr, Offset),
10889                        MachinePointerInfo(), false, false, false, 0);
10890   }
10891
10892   // Just load the return address off the stack.
10893   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
10894   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10895                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10896 }
10897
10898 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
10899                                           SelectionDAG &DAG) const {
10900   SDLoc dl(Op);
10901   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10902
10903   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
10904   bool isPPC64 = PtrVT == MVT::i64;
10905
10906   MachineFunction &MF = DAG.getMachineFunction();
10907   MachineFrameInfo *MFI = MF.getFrameInfo();
10908   MFI->setFrameAddressIsTaken(true);
10909
10910   // Naked functions never have a frame pointer, and so we use r1. For all
10911   // other functions, this decision must be delayed until during PEI.
10912   unsigned FrameReg;
10913   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
10914     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
10915   else
10916     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
10917
10918   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
10919                                          PtrVT);
10920   while (Depth--)
10921     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
10922                             FrameAddr, MachinePointerInfo(), false, false,
10923                             false, 0);
10924   return FrameAddr;
10925 }
10926
10927 // FIXME? Maybe this could be a TableGen attribute on some registers and
10928 // this table could be generated automatically from RegInfo.
10929 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
10930                                               EVT VT) const {
10931   bool isPPC64 = Subtarget.isPPC64();
10932   bool isDarwinABI = Subtarget.isDarwinABI();
10933
10934   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
10935       (!isPPC64 && VT != MVT::i32))
10936     report_fatal_error("Invalid register global variable type");
10937
10938   bool is64Bit = isPPC64 && VT == MVT::i64;
10939   unsigned Reg = StringSwitch<unsigned>(RegName)
10940                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
10941                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
10942                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
10943                                   (is64Bit ? PPC::X13 : PPC::R13))
10944                    .Default(0);
10945
10946   if (Reg)
10947     return Reg;
10948   report_fatal_error("Invalid register name global variable");
10949 }
10950
10951 bool
10952 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10953   // The PowerPC target isn't yet aware of offsets.
10954   return false;
10955 }
10956
10957 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10958                                            const CallInst &I,
10959                                            unsigned Intrinsic) const {
10960
10961   switch (Intrinsic) {
10962   case Intrinsic::ppc_qpx_qvlfd:
10963   case Intrinsic::ppc_qpx_qvlfs:
10964   case Intrinsic::ppc_qpx_qvlfcd:
10965   case Intrinsic::ppc_qpx_qvlfcs:
10966   case Intrinsic::ppc_qpx_qvlfiwa:
10967   case Intrinsic::ppc_qpx_qvlfiwz:
10968   case Intrinsic::ppc_altivec_lvx:
10969   case Intrinsic::ppc_altivec_lvxl:
10970   case Intrinsic::ppc_altivec_lvebx:
10971   case Intrinsic::ppc_altivec_lvehx:
10972   case Intrinsic::ppc_altivec_lvewx:
10973   case Intrinsic::ppc_vsx_lxvd2x:
10974   case Intrinsic::ppc_vsx_lxvw4x: {
10975     EVT VT;
10976     switch (Intrinsic) {
10977     case Intrinsic::ppc_altivec_lvebx:
10978       VT = MVT::i8;
10979       break;
10980     case Intrinsic::ppc_altivec_lvehx:
10981       VT = MVT::i16;
10982       break;
10983     case Intrinsic::ppc_altivec_lvewx:
10984       VT = MVT::i32;
10985       break;
10986     case Intrinsic::ppc_vsx_lxvd2x:
10987       VT = MVT::v2f64;
10988       break;
10989     case Intrinsic::ppc_qpx_qvlfd:
10990       VT = MVT::v4f64;
10991       break;
10992     case Intrinsic::ppc_qpx_qvlfs:
10993       VT = MVT::v4f32;
10994       break;
10995     case Intrinsic::ppc_qpx_qvlfcd:
10996       VT = MVT::v2f64;
10997       break;
10998     case Intrinsic::ppc_qpx_qvlfcs:
10999       VT = MVT::v2f32;
11000       break;
11001     default:
11002       VT = MVT::v4i32;
11003       break;
11004     }
11005
11006     Info.opc = ISD::INTRINSIC_W_CHAIN;
11007     Info.memVT = VT;
11008     Info.ptrVal = I.getArgOperand(0);
11009     Info.offset = -VT.getStoreSize()+1;
11010     Info.size = 2*VT.getStoreSize()-1;
11011     Info.align = 1;
11012     Info.vol = false;
11013     Info.readMem = true;
11014     Info.writeMem = false;
11015     return true;
11016   }
11017   case Intrinsic::ppc_qpx_qvlfda:
11018   case Intrinsic::ppc_qpx_qvlfsa:
11019   case Intrinsic::ppc_qpx_qvlfcda:
11020   case Intrinsic::ppc_qpx_qvlfcsa:
11021   case Intrinsic::ppc_qpx_qvlfiwaa:
11022   case Intrinsic::ppc_qpx_qvlfiwza: {
11023     EVT VT;
11024     switch (Intrinsic) {
11025     case Intrinsic::ppc_qpx_qvlfda:
11026       VT = MVT::v4f64;
11027       break;
11028     case Intrinsic::ppc_qpx_qvlfsa:
11029       VT = MVT::v4f32;
11030       break;
11031     case Intrinsic::ppc_qpx_qvlfcda:
11032       VT = MVT::v2f64;
11033       break;
11034     case Intrinsic::ppc_qpx_qvlfcsa:
11035       VT = MVT::v2f32;
11036       break;
11037     default:
11038       VT = MVT::v4i32;
11039       break;
11040     }
11041
11042     Info.opc = ISD::INTRINSIC_W_CHAIN;
11043     Info.memVT = VT;
11044     Info.ptrVal = I.getArgOperand(0);
11045     Info.offset = 0;
11046     Info.size = VT.getStoreSize();
11047     Info.align = 1;
11048     Info.vol = false;
11049     Info.readMem = true;
11050     Info.writeMem = false;
11051     return true;
11052   }
11053   case Intrinsic::ppc_qpx_qvstfd:
11054   case Intrinsic::ppc_qpx_qvstfs:
11055   case Intrinsic::ppc_qpx_qvstfcd:
11056   case Intrinsic::ppc_qpx_qvstfcs:
11057   case Intrinsic::ppc_qpx_qvstfiw:
11058   case Intrinsic::ppc_altivec_stvx:
11059   case Intrinsic::ppc_altivec_stvxl:
11060   case Intrinsic::ppc_altivec_stvebx:
11061   case Intrinsic::ppc_altivec_stvehx:
11062   case Intrinsic::ppc_altivec_stvewx:
11063   case Intrinsic::ppc_vsx_stxvd2x:
11064   case Intrinsic::ppc_vsx_stxvw4x: {
11065     EVT VT;
11066     switch (Intrinsic) {
11067     case Intrinsic::ppc_altivec_stvebx:
11068       VT = MVT::i8;
11069       break;
11070     case Intrinsic::ppc_altivec_stvehx:
11071       VT = MVT::i16;
11072       break;
11073     case Intrinsic::ppc_altivec_stvewx:
11074       VT = MVT::i32;
11075       break;
11076     case Intrinsic::ppc_vsx_stxvd2x:
11077       VT = MVT::v2f64;
11078       break;
11079     case Intrinsic::ppc_qpx_qvstfd:
11080       VT = MVT::v4f64;
11081       break;
11082     case Intrinsic::ppc_qpx_qvstfs:
11083       VT = MVT::v4f32;
11084       break;
11085     case Intrinsic::ppc_qpx_qvstfcd:
11086       VT = MVT::v2f64;
11087       break;
11088     case Intrinsic::ppc_qpx_qvstfcs:
11089       VT = MVT::v2f32;
11090       break;
11091     default:
11092       VT = MVT::v4i32;
11093       break;
11094     }
11095
11096     Info.opc = ISD::INTRINSIC_VOID;
11097     Info.memVT = VT;
11098     Info.ptrVal = I.getArgOperand(1);
11099     Info.offset = -VT.getStoreSize()+1;
11100     Info.size = 2*VT.getStoreSize()-1;
11101     Info.align = 1;
11102     Info.vol = false;
11103     Info.readMem = false;
11104     Info.writeMem = true;
11105     return true;
11106   }
11107   case Intrinsic::ppc_qpx_qvstfda:
11108   case Intrinsic::ppc_qpx_qvstfsa:
11109   case Intrinsic::ppc_qpx_qvstfcda:
11110   case Intrinsic::ppc_qpx_qvstfcsa:
11111   case Intrinsic::ppc_qpx_qvstfiwa: {
11112     EVT VT;
11113     switch (Intrinsic) {
11114     case Intrinsic::ppc_qpx_qvstfda:
11115       VT = MVT::v4f64;
11116       break;
11117     case Intrinsic::ppc_qpx_qvstfsa:
11118       VT = MVT::v4f32;
11119       break;
11120     case Intrinsic::ppc_qpx_qvstfcda:
11121       VT = MVT::v2f64;
11122       break;
11123     case Intrinsic::ppc_qpx_qvstfcsa:
11124       VT = MVT::v2f32;
11125       break;
11126     default:
11127       VT = MVT::v4i32;
11128       break;
11129     }
11130
11131     Info.opc = ISD::INTRINSIC_VOID;
11132     Info.memVT = VT;
11133     Info.ptrVal = I.getArgOperand(1);
11134     Info.offset = 0;
11135     Info.size = VT.getStoreSize();
11136     Info.align = 1;
11137     Info.vol = false;
11138     Info.readMem = false;
11139     Info.writeMem = true;
11140     return true;
11141   }
11142   default:
11143     break;
11144   }
11145
11146   return false;
11147 }
11148
11149 /// getOptimalMemOpType - Returns the target specific optimal type for load
11150 /// and store operations as a result of memset, memcpy, and memmove
11151 /// lowering. If DstAlign is zero that means it's safe to destination
11152 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
11153 /// means there isn't a need to check it against alignment requirement,
11154 /// probably because the source does not need to be loaded. If 'IsMemset' is
11155 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
11156 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
11157 /// source is constant so it does not need to be loaded.
11158 /// It returns EVT::Other if the type should be determined using generic
11159 /// target-independent logic.
11160 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
11161                                            unsigned DstAlign, unsigned SrcAlign,
11162                                            bool IsMemset, bool ZeroMemset,
11163                                            bool MemcpyStrSrc,
11164                                            MachineFunction &MF) const {
11165   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
11166     const Function *F = MF.getFunction();
11167     // When expanding a memset, require at least two QPX instructions to cover
11168     // the cost of loading the value to be stored from the constant pool.
11169     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
11170        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
11171         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11172       return MVT::v4f64;
11173     }
11174
11175     // We should use Altivec/VSX loads and stores when available. For unaligned
11176     // addresses, unaligned VSX loads are only fast starting with the P8.
11177     if (Subtarget.hasAltivec() && Size >= 16 &&
11178         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
11179          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
11180       return MVT::v4i32;
11181   }
11182
11183   if (Subtarget.isPPC64()) {
11184     return MVT::i64;
11185   }
11186
11187   return MVT::i32;
11188 }
11189
11190 /// \brief Returns true if it is beneficial to convert a load of a constant
11191 /// to just the constant itself.
11192 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11193                                                           Type *Ty) const {
11194   assert(Ty->isIntegerTy());
11195
11196   unsigned BitSize = Ty->getPrimitiveSizeInBits();
11197   if (BitSize == 0 || BitSize > 64)
11198     return false;
11199   return true;
11200 }
11201
11202 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11203   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11204     return false;
11205   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11206   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11207   return NumBits1 == 64 && NumBits2 == 32;
11208 }
11209
11210 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11211   if (!VT1.isInteger() || !VT2.isInteger())
11212     return false;
11213   unsigned NumBits1 = VT1.getSizeInBits();
11214   unsigned NumBits2 = VT2.getSizeInBits();
11215   return NumBits1 == 64 && NumBits2 == 32;
11216 }
11217
11218 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11219   // Generally speaking, zexts are not free, but they are free when they can be
11220   // folded with other operations.
11221   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
11222     EVT MemVT = LD->getMemoryVT();
11223     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
11224          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
11225         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
11226          LD->getExtensionType() == ISD::ZEXTLOAD))
11227       return true;
11228   }
11229
11230   // FIXME: Add other cases...
11231   //  - 32-bit shifts with a zext to i64
11232   //  - zext after ctlz, bswap, etc.
11233   //  - zext after and by a constant mask
11234
11235   return TargetLowering::isZExtFree(Val, VT2);
11236 }
11237
11238 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
11239   assert(VT.isFloatingPoint());
11240   return true;
11241 }
11242
11243 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11244   return isInt<16>(Imm) || isUInt<16>(Imm);
11245 }
11246
11247 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11248   return isInt<16>(Imm) || isUInt<16>(Imm);
11249 }
11250
11251 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11252                                                        unsigned,
11253                                                        unsigned,
11254                                                        bool *Fast) const {
11255   if (DisablePPCUnaligned)
11256     return false;
11257
11258   // PowerPC supports unaligned memory access for simple non-vector types.
11259   // Although accessing unaligned addresses is not as efficient as accessing
11260   // aligned addresses, it is generally more efficient than manual expansion,
11261   // and generally only traps for software emulation when crossing page
11262   // boundaries.
11263
11264   if (!VT.isSimple())
11265     return false;
11266
11267   if (VT.getSimpleVT().isVector()) {
11268     if (Subtarget.hasVSX()) {
11269       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
11270           VT != MVT::v4f32 && VT != MVT::v4i32)
11271         return false;
11272     } else {
11273       return false;
11274     }
11275   }
11276
11277   if (VT == MVT::ppcf128)
11278     return false;
11279
11280   if (Fast)
11281     *Fast = true;
11282
11283   return true;
11284 }
11285
11286 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
11287   VT = VT.getScalarType();
11288
11289   if (!VT.isSimple())
11290     return false;
11291
11292   switch (VT.getSimpleVT().SimpleTy) {
11293   case MVT::f32:
11294   case MVT::f64:
11295     return true;
11296   default:
11297     break;
11298   }
11299
11300   return false;
11301 }
11302
11303 const MCPhysReg *
11304 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
11305   // LR is a callee-save register, but we must treat it as clobbered by any call
11306   // site. Hence we include LR in the scratch registers, which are in turn added
11307   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
11308   // to CTR, which is used by any indirect call.
11309   static const MCPhysReg ScratchRegs[] = {
11310     PPC::X12, PPC::LR8, PPC::CTR8, 0
11311   };
11312
11313   return ScratchRegs;
11314 }
11315
11316 bool
11317 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
11318                      EVT VT , unsigned DefinedValues) const {
11319   if (VT == MVT::v2i64)
11320     return false;
11321
11322   if (Subtarget.hasQPX()) {
11323     if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1)
11324       return true;
11325   }
11326
11327   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
11328 }
11329
11330 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
11331   if (DisableILPPref || Subtarget.enableMachineScheduler())
11332     return TargetLowering::getSchedulingPreference(N);
11333
11334   return Sched::ILP;
11335 }
11336
11337 // Create a fast isel object.
11338 FastISel *
11339 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
11340                                   const TargetLibraryInfo *LibInfo) const {
11341   return PPC::createFastISel(FuncInfo, LibInfo);
11342 }