fbcc34ee6557c598fa6e981547b355ca7cb1bbc3
[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 "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
40 using namespace llvm;
41
42 // FIXME: Remove this once soft-float is supported.
43 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
44 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
45
46 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
47 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
48
49 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
50 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
51
52 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
53 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
54
55 // FIXME: Remove this once the bug has been fixed!
56 extern cl::opt<bool> ANDIGlueBug;
57
58 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
59     : TargetLowering(TM),
60       Subtarget(*TM.getSubtargetImpl()) {
61   setPow2SDivIsCheap();
62
63   // Use _setjmp/_longjmp instead of setjmp/longjmp.
64   setUseUnderscoreSetJmp(true);
65   setUseUnderscoreLongJmp(true);
66
67   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68   // arguments are at least 4/8 bytes aligned.
69   bool isPPC64 = Subtarget.isPPC64();
70   setMinStackArgumentAlignment(isPPC64 ? 8:4);
71
72   // Set up the register classes.
73   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
76
77   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
79   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
80
81   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
82
83   // PowerPC has pre-inc load and store's.
84   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
85   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
89   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
90   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
91   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
92   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
93   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
94
95   if (Subtarget.useCRBits()) {
96     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
97
98     if (isPPC64 || Subtarget.hasFPCVT()) {
99       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
100       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
101                          isPPC64 ? MVT::i64 : MVT::i32);
102       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
103       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
104                          isPPC64 ? MVT::i64 : MVT::i32);
105     } else {
106       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
107       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
108     }
109
110     // PowerPC does not support direct load / store of condition registers
111     setOperationAction(ISD::LOAD, MVT::i1, Custom);
112     setOperationAction(ISD::STORE, MVT::i1, Custom);
113
114     // FIXME: Remove this once the ANDI glue bug is fixed:
115     if (ANDIGlueBug)
116       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
117
118     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
119     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
120     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
121     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
122     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
123     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
124
125     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
126   }
127
128   // This is used in the ppcf128->int sequence.  Note it has different semantics
129   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
130   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
131
132   // We do not currently implement these libm ops for PowerPC.
133   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
134   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
135   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
136   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
137   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
138   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
139
140   // PowerPC has no SREM/UREM instructions
141   setOperationAction(ISD::SREM, MVT::i32, Expand);
142   setOperationAction(ISD::UREM, MVT::i32, Expand);
143   setOperationAction(ISD::SREM, MVT::i64, Expand);
144   setOperationAction(ISD::UREM, MVT::i64, Expand);
145
146   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
147   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
148   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
149   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
150   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
151   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
152   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
153   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
154   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
155
156   // We don't support sin/cos/sqrt/fmod/pow
157   setOperationAction(ISD::FSIN , MVT::f64, Expand);
158   setOperationAction(ISD::FCOS , MVT::f64, Expand);
159   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
160   setOperationAction(ISD::FREM , MVT::f64, Expand);
161   setOperationAction(ISD::FPOW , MVT::f64, Expand);
162   setOperationAction(ISD::FMA  , MVT::f64, Legal);
163   setOperationAction(ISD::FSIN , MVT::f32, Expand);
164   setOperationAction(ISD::FCOS , MVT::f32, Expand);
165   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
166   setOperationAction(ISD::FREM , MVT::f32, Expand);
167   setOperationAction(ISD::FPOW , MVT::f32, Expand);
168   setOperationAction(ISD::FMA  , MVT::f32, Legal);
169
170   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
171
172   // If we're enabling GP optimizations, use hardware square root
173   if (!Subtarget.hasFSQRT() &&
174       !(TM.Options.UnsafeFPMath &&
175         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
176     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
177
178   if (!Subtarget.hasFSQRT() &&
179       !(TM.Options.UnsafeFPMath &&
180         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
181     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
182
183   if (Subtarget.hasFCPSGN()) {
184     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
185     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
186   } else {
187     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
188     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
189   }
190
191   if (Subtarget.hasFPRND()) {
192     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
193     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
194     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
195     setOperationAction(ISD::FROUND, MVT::f64, Legal);
196
197     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
198     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
199     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
200     setOperationAction(ISD::FROUND, MVT::f32, Legal);
201   }
202
203   // PowerPC does not have BSWAP, CTPOP or CTTZ
204   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
205   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
206   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
207   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
208   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
209   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
210   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
211   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
212
213   if (Subtarget.hasPOPCNTD()) {
214     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
215     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
216   } else {
217     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
218     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
219   }
220
221   // PowerPC does not have ROTR
222   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
223   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
224
225   if (!Subtarget.useCRBits()) {
226     // PowerPC does not have Select
227     setOperationAction(ISD::SELECT, MVT::i32, Expand);
228     setOperationAction(ISD::SELECT, MVT::i64, Expand);
229     setOperationAction(ISD::SELECT, MVT::f32, Expand);
230     setOperationAction(ISD::SELECT, MVT::f64, Expand);
231   }
232
233   // PowerPC wants to turn select_cc of FP into fsel when possible.
234   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
235   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
236
237   // PowerPC wants to optimize integer setcc a bit
238   if (!Subtarget.useCRBits())
239     setOperationAction(ISD::SETCC, MVT::i32, Custom);
240
241   // PowerPC does not have BRCOND which requires SetCC
242   if (!Subtarget.useCRBits())
243     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
244
245   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
246
247   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
248   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
249
250   // PowerPC does not have [U|S]INT_TO_FP
251   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
252   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
253
254   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
255   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
256   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
257   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
258
259   // We cannot sextinreg(i1).  Expand to shifts.
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
261
262   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
263   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
264   // support continuation, user-level threading, and etc.. As a result, no
265   // other SjLj exception interfaces are implemented and please don't build
266   // your own exception handling based on them.
267   // LLVM/Clang supports zero-cost DWARF exception handling.
268   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
269   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
270
271   // We want to legalize GlobalAddress and ConstantPool nodes into the
272   // appropriate instructions to materialize the address.
273   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
274   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
275   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
276   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
277   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
278   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
279   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
280   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
281   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
282   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
283
284   // TRAP is legal.
285   setOperationAction(ISD::TRAP, MVT::Other, Legal);
286
287   // TRAMPOLINE is custom lowered.
288   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
289   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
290
291   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
292   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
293
294   if (Subtarget.isSVR4ABI()) {
295     if (isPPC64) {
296       // VAARG always uses double-word chunks, so promote anything smaller.
297       setOperationAction(ISD::VAARG, MVT::i1, Promote);
298       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
299       setOperationAction(ISD::VAARG, MVT::i8, Promote);
300       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
301       setOperationAction(ISD::VAARG, MVT::i16, Promote);
302       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
303       setOperationAction(ISD::VAARG, MVT::i32, Promote);
304       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
305       setOperationAction(ISD::VAARG, MVT::Other, Expand);
306     } else {
307       // VAARG is custom lowered with the 32-bit SVR4 ABI.
308       setOperationAction(ISD::VAARG, MVT::Other, Custom);
309       setOperationAction(ISD::VAARG, MVT::i64, Custom);
310     }
311   } else
312     setOperationAction(ISD::VAARG, MVT::Other, Expand);
313
314   if (Subtarget.isSVR4ABI() && !isPPC64)
315     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
316     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
317   else
318     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
319
320   // Use the default implementation.
321   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
322   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
323   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
324   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
325   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
326
327   // We want to custom lower some of our intrinsics.
328   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
329
330   // To handle counter-based loop conditions.
331   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
332
333   // Comparisons that require checking two conditions.
334   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
335   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
336   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
337   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
338   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
339   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
340   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
341   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
342   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
343   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
344   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
345   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
346
347   if (Subtarget.has64BitSupport()) {
348     // They also have instructions for converting between i64 and fp.
349     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
350     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
351     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
352     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
353     // This is just the low 32 bits of a (signed) fp->i64 conversion.
354     // We cannot do this with Promote because i64 is not a legal type.
355     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
356
357     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
358       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
359   } else {
360     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
361     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
362   }
363
364   // With the instructions enabled under FPCVT, we can do everything.
365   if (Subtarget.hasFPCVT()) {
366     if (Subtarget.has64BitSupport()) {
367       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
368       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
369       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
370       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
371     }
372
373     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
374     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
375     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
376     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
377   }
378
379   if (Subtarget.use64BitRegs()) {
380     // 64-bit PowerPC implementations can support i64 types directly
381     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
382     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
383     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
384     // 64-bit PowerPC wants to expand i128 shifts itself.
385     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
386     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
387     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
388   } else {
389     // 32-bit PowerPC wants to expand i64 shifts itself.
390     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
391     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
392     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
393   }
394
395   if (Subtarget.hasAltivec()) {
396     // First set operation action for all vector types to expand. Then we
397     // will selectively turn on ones that can be effectively codegen'd.
398     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
399          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
400       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
401
402       // add/sub are legal for all supported vector VT's.
403       setOperationAction(ISD::ADD , VT, Legal);
404       setOperationAction(ISD::SUB , VT, Legal);
405
406       // We promote all shuffles to v16i8.
407       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
408       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
409
410       // We promote all non-typed operations to v4i32.
411       setOperationAction(ISD::AND   , VT, Promote);
412       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
413       setOperationAction(ISD::OR    , VT, Promote);
414       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
415       setOperationAction(ISD::XOR   , VT, Promote);
416       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
417       setOperationAction(ISD::LOAD  , VT, Promote);
418       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
419       setOperationAction(ISD::SELECT, VT, Promote);
420       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
421       setOperationAction(ISD::STORE, VT, Promote);
422       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
423
424       // No other operations are legal.
425       setOperationAction(ISD::MUL , VT, Expand);
426       setOperationAction(ISD::SDIV, VT, Expand);
427       setOperationAction(ISD::SREM, VT, Expand);
428       setOperationAction(ISD::UDIV, VT, Expand);
429       setOperationAction(ISD::UREM, VT, Expand);
430       setOperationAction(ISD::FDIV, VT, Expand);
431       setOperationAction(ISD::FREM, VT, Expand);
432       setOperationAction(ISD::FNEG, VT, Expand);
433       setOperationAction(ISD::FSQRT, VT, Expand);
434       setOperationAction(ISD::FLOG, VT, Expand);
435       setOperationAction(ISD::FLOG10, VT, Expand);
436       setOperationAction(ISD::FLOG2, VT, Expand);
437       setOperationAction(ISD::FEXP, VT, Expand);
438       setOperationAction(ISD::FEXP2, VT, Expand);
439       setOperationAction(ISD::FSIN, VT, Expand);
440       setOperationAction(ISD::FCOS, VT, Expand);
441       setOperationAction(ISD::FABS, VT, Expand);
442       setOperationAction(ISD::FPOWI, VT, Expand);
443       setOperationAction(ISD::FFLOOR, VT, Expand);
444       setOperationAction(ISD::FCEIL,  VT, Expand);
445       setOperationAction(ISD::FTRUNC, VT, Expand);
446       setOperationAction(ISD::FRINT,  VT, Expand);
447       setOperationAction(ISD::FNEARBYINT, VT, Expand);
448       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
449       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
450       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
451       setOperationAction(ISD::MULHU, VT, Expand);
452       setOperationAction(ISD::MULHS, VT, Expand);
453       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
454       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
455       setOperationAction(ISD::UDIVREM, VT, Expand);
456       setOperationAction(ISD::SDIVREM, VT, Expand);
457       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
458       setOperationAction(ISD::FPOW, VT, Expand);
459       setOperationAction(ISD::BSWAP, VT, Expand);
460       setOperationAction(ISD::CTPOP, VT, Expand);
461       setOperationAction(ISD::CTLZ, VT, Expand);
462       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
463       setOperationAction(ISD::CTTZ, VT, Expand);
464       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
465       setOperationAction(ISD::VSELECT, VT, Expand);
466       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
467
468       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
469            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
470         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
471         setTruncStoreAction(VT, InnerVT, Expand);
472       }
473       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
474       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
475       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
476     }
477
478     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
479     // with merges, splats, etc.
480     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
481
482     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
483     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
484     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
485     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
486     setOperationAction(ISD::SELECT, MVT::v4i32,
487                        Subtarget.useCRBits() ? Legal : Expand);
488     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
489     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
490     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
491     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
492     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
493     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
494     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
495     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
496     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
497
498     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
499     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
500     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
501     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
502
503     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
504     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
505
506     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
507       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
508       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
509     }
510
511     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
512     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
513     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
514
515     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
516     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
517
518     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
519     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
520     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
521     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
522
523     // Altivec does not contain unordered floating-point compare instructions
524     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
525     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
526     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
527     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
528
529     if (Subtarget.hasVSX()) {
530       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
531       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
532
533       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
534       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
535       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
536       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
537       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
538
539       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
540
541       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
542       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
543
544       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
545       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
546
547       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
548       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
549       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
550       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
551       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
552
553       // Share the Altivec comparison restrictions.
554       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
555       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
556       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
557       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
558
559       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
560       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
561
562       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
563
564       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
565
566       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
567       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
568
569       // VSX v2i64 only supports non-arithmetic operations.
570       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
571       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
572
573       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
574       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
575       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
576
577       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
578
579       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
580       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
581       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
582       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
583
584       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
585
586       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
587       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
588       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
589       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
590
591       // Vector operation legalization checks the result type of
592       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
593       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
594       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
595       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
596       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
597
598       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
599     }
600   }
601
602   if (Subtarget.has64BitSupport())
603     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
604
605   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
606
607   if (!isPPC64) {
608     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
609     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
610   }
611
612   setBooleanContents(ZeroOrOneBooleanContent);
613   // Altivec instructions set fields to all zeros or all ones.
614   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
615
616   if (!isPPC64) {
617     // These libcalls are not available in 32-bit.
618     setLibcallName(RTLIB::SHL_I128, nullptr);
619     setLibcallName(RTLIB::SRL_I128, nullptr);
620     setLibcallName(RTLIB::SRA_I128, nullptr);
621   }
622
623   if (isPPC64) {
624     setStackPointerRegisterToSaveRestore(PPC::X1);
625     setExceptionPointerRegister(PPC::X3);
626     setExceptionSelectorRegister(PPC::X4);
627   } else {
628     setStackPointerRegisterToSaveRestore(PPC::R1);
629     setExceptionPointerRegister(PPC::R3);
630     setExceptionSelectorRegister(PPC::R4);
631   }
632
633   // We have target-specific dag combine patterns for the following nodes:
634   setTargetDAGCombine(ISD::SINT_TO_FP);
635   setTargetDAGCombine(ISD::LOAD);
636   setTargetDAGCombine(ISD::STORE);
637   setTargetDAGCombine(ISD::BR_CC);
638   if (Subtarget.useCRBits())
639     setTargetDAGCombine(ISD::BRCOND);
640   setTargetDAGCombine(ISD::BSWAP);
641   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
642   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
643   setTargetDAGCombine(ISD::INTRINSIC_VOID);
644
645   setTargetDAGCombine(ISD::SIGN_EXTEND);
646   setTargetDAGCombine(ISD::ZERO_EXTEND);
647   setTargetDAGCombine(ISD::ANY_EXTEND);
648
649   if (Subtarget.useCRBits()) {
650     setTargetDAGCombine(ISD::TRUNCATE);
651     setTargetDAGCombine(ISD::SETCC);
652     setTargetDAGCombine(ISD::SELECT_CC);
653   }
654
655   // Use reciprocal estimates.
656   if (TM.Options.UnsafeFPMath) {
657     setTargetDAGCombine(ISD::FDIV);
658     setTargetDAGCombine(ISD::FSQRT);
659   }
660
661   // Darwin long double math library functions have $LDBL128 appended.
662   if (Subtarget.isDarwin()) {
663     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
664     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
665     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
666     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
667     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
668     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
669     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
670     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
671     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
672     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
673   }
674
675   // With 32 condition bits, we don't need to sink (and duplicate) compares
676   // aggressively in CodeGenPrep.
677   if (Subtarget.useCRBits())
678     setHasMultipleConditionRegisters();
679
680   setMinFunctionAlignment(2);
681   if (Subtarget.isDarwin())
682     setPrefFunctionAlignment(4);
683
684   setInsertFencesForAtomic(true);
685
686   if (Subtarget.enableMachineScheduler())
687     setSchedulingPreference(Sched::Source);
688   else
689     setSchedulingPreference(Sched::Hybrid);
690
691   computeRegisterProperties();
692
693   // The Freescale cores does better with aggressive inlining of memcpy and
694   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
695   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
696       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
697     MaxStoresPerMemset = 32;
698     MaxStoresPerMemsetOptSize = 16;
699     MaxStoresPerMemcpy = 32;
700     MaxStoresPerMemcpyOptSize = 8;
701     MaxStoresPerMemmove = 32;
702     MaxStoresPerMemmoveOptSize = 8;
703
704     setPrefFunctionAlignment(4);
705   }
706 }
707
708 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
709 /// the desired ByVal argument alignment.
710 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
711                              unsigned MaxMaxAlign) {
712   if (MaxAlign == MaxMaxAlign)
713     return;
714   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
715     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
716       MaxAlign = 32;
717     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
718       MaxAlign = 16;
719   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
720     unsigned EltAlign = 0;
721     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
722     if (EltAlign > MaxAlign)
723       MaxAlign = EltAlign;
724   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
725     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
726       unsigned EltAlign = 0;
727       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
728       if (EltAlign > MaxAlign)
729         MaxAlign = EltAlign;
730       if (MaxAlign == MaxMaxAlign)
731         break;
732     }
733   }
734 }
735
736 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
737 /// function arguments in the caller parameter area.
738 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
739   // Darwin passes everything on 4 byte boundary.
740   if (Subtarget.isDarwin())
741     return 4;
742
743   // 16byte and wider vectors are passed on 16byte boundary.
744   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
745   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
746   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
747     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
748   return Align;
749 }
750
751 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
752   switch (Opcode) {
753   default: return nullptr;
754   case PPCISD::FSEL:            return "PPCISD::FSEL";
755   case PPCISD::FCFID:           return "PPCISD::FCFID";
756   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
757   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
758   case PPCISD::FRE:             return "PPCISD::FRE";
759   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
760   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
761   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
762   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
763   case PPCISD::VPERM:           return "PPCISD::VPERM";
764   case PPCISD::Hi:              return "PPCISD::Hi";
765   case PPCISD::Lo:              return "PPCISD::Lo";
766   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
767   case PPCISD::LOAD:            return "PPCISD::LOAD";
768   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
769   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
770   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
771   case PPCISD::SRL:             return "PPCISD::SRL";
772   case PPCISD::SRA:             return "PPCISD::SRA";
773   case PPCISD::SHL:             return "PPCISD::SHL";
774   case PPCISD::CALL:            return "PPCISD::CALL";
775   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
776   case PPCISD::CALL_TLS:        return "PPCISD::CALL_TLS";
777   case PPCISD::CALL_NOP_TLS:    return "PPCISD::CALL_NOP_TLS";
778   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
779   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
780   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
781   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
782   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
783   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
784   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
785   case PPCISD::VCMP:            return "PPCISD::VCMP";
786   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
787   case PPCISD::LBRX:            return "PPCISD::LBRX";
788   case PPCISD::STBRX:           return "PPCISD::STBRX";
789   case PPCISD::LARX:            return "PPCISD::LARX";
790   case PPCISD::STCX:            return "PPCISD::STCX";
791   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
792   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
793   case PPCISD::BDZ:             return "PPCISD::BDZ";
794   case PPCISD::MFFS:            return "PPCISD::MFFS";
795   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
796   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
797   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
798   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
799   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
800   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
801   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
802   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
803   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
804   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
805   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
806   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
807   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
808   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
809   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
810   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
811   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
812   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
813   case PPCISD::SC:              return "PPCISD::SC";
814   }
815 }
816
817 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
818   if (!VT.isVector())
819     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
820   return VT.changeVectorElementTypeToInteger();
821 }
822
823 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
824   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
825   return true;
826 }
827
828 //===----------------------------------------------------------------------===//
829 // Node matching predicates, for use by the tblgen matching code.
830 //===----------------------------------------------------------------------===//
831
832 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
833 static bool isFloatingPointZero(SDValue Op) {
834   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
835     return CFP->getValueAPF().isZero();
836   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
837     // Maybe this has already been legalized into the constant pool?
838     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
839       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
840         return CFP->getValueAPF().isZero();
841   }
842   return false;
843 }
844
845 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
846 /// true if Op is undef or if it matches the specified value.
847 static bool isConstantOrUndef(int Op, int Val) {
848   return Op < 0 || Op == Val;
849 }
850
851 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
852 /// VPKUHUM instruction.
853 /// The ShuffleKind distinguishes between big-endian operations with
854 /// two different inputs (0), either-endian operations with two identical
855 /// inputs (1), and little-endian operantion with two different inputs (2).
856 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
857 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
858                                SelectionDAG &DAG) {
859   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
860   if (ShuffleKind == 0) {
861     if (IsLE)
862       return false;
863     for (unsigned i = 0; i != 16; ++i)
864       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
865         return false;
866   } else if (ShuffleKind == 2) {
867     if (!IsLE)
868       return false;
869     for (unsigned i = 0; i != 16; ++i)
870       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
871         return false;
872   } else if (ShuffleKind == 1) {
873     unsigned j = IsLE ? 0 : 1;
874     for (unsigned i = 0; i != 8; ++i)
875       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
876           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
877         return false;
878   }
879   return true;
880 }
881
882 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
883 /// VPKUWUM instruction.
884 /// The ShuffleKind distinguishes between big-endian operations with
885 /// two different inputs (0), either-endian operations with two identical
886 /// inputs (1), and little-endian operantion with two different inputs (2).
887 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
888 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
889                                SelectionDAG &DAG) {
890   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
891   if (ShuffleKind == 0) {
892     if (IsLE)
893       return false;
894     for (unsigned i = 0; i != 16; i += 2)
895       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
896           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
897         return false;
898   } else if (ShuffleKind == 2) {
899     if (!IsLE)
900       return false;
901     for (unsigned i = 0; i != 16; i += 2)
902       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
903           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
904         return false;
905   } else if (ShuffleKind == 1) {
906     unsigned j = IsLE ? 0 : 2;
907     for (unsigned i = 0; i != 8; i += 2)
908       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
909           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
910           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
911           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
912         return false;
913   }
914   return true;
915 }
916
917 /// isVMerge - Common function, used to match vmrg* shuffles.
918 ///
919 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
920                      unsigned LHSStart, unsigned RHSStart) {
921   if (N->getValueType(0) != MVT::v16i8)
922     return false;
923   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
924          "Unsupported merge size!");
925
926   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
927     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
928       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
929                              LHSStart+j+i*UnitSize) ||
930           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
931                              RHSStart+j+i*UnitSize))
932         return false;
933     }
934   return true;
935 }
936
937 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
938 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
939 /// The ShuffleKind distinguishes between big-endian merges with two 
940 /// different inputs (0), either-endian merges with two identical inputs (1),
941 /// and little-endian merges with two different inputs (2).  For the latter,
942 /// the input operands are swapped (see PPCInstrAltivec.td).
943 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
944                              unsigned ShuffleKind, SelectionDAG &DAG) {
945   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
946     if (ShuffleKind == 1) // unary
947       return isVMerge(N, UnitSize, 0, 0);
948     else if (ShuffleKind == 2) // swapped
949       return isVMerge(N, UnitSize, 0, 16);
950     else
951       return false;
952   } else {
953     if (ShuffleKind == 1) // unary
954       return isVMerge(N, UnitSize, 8, 8);
955     else if (ShuffleKind == 0) // normal
956       return isVMerge(N, UnitSize, 8, 24);
957     else
958       return false;
959   }
960 }
961
962 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
963 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
964 /// The ShuffleKind distinguishes between big-endian merges with two 
965 /// different inputs (0), either-endian merges with two identical inputs (1),
966 /// and little-endian merges with two different inputs (2).  For the latter,
967 /// the input operands are swapped (see PPCInstrAltivec.td).
968 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
969                              unsigned ShuffleKind, SelectionDAG &DAG) {
970   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
971     if (ShuffleKind == 1) // unary
972       return isVMerge(N, UnitSize, 8, 8);
973     else if (ShuffleKind == 2) // swapped
974       return isVMerge(N, UnitSize, 8, 24);
975     else
976       return false;
977   } else {
978     if (ShuffleKind == 1) // unary
979       return isVMerge(N, UnitSize, 0, 0);
980     else if (ShuffleKind == 0) // normal
981       return isVMerge(N, UnitSize, 0, 16);
982     else
983       return false;
984   }
985 }
986
987
988 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
989 /// amount, otherwise return -1.
990 /// The ShuffleKind distinguishes between big-endian operations with two 
991 /// different inputs (0), either-endian operations with two identical inputs
992 /// (1), and little-endian operations with two different inputs (2).  For the
993 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
994 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
995                              SelectionDAG &DAG) {
996   if (N->getValueType(0) != MVT::v16i8)
997     return -1;
998
999   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1000
1001   // Find the first non-undef value in the shuffle mask.
1002   unsigned i;
1003   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1004     /*search*/;
1005
1006   if (i == 16) return -1;  // all undef.
1007
1008   // Otherwise, check to see if the rest of the elements are consecutively
1009   // numbered from this value.
1010   unsigned ShiftAmt = SVOp->getMaskElt(i);
1011   if (ShiftAmt < i) return -1;
1012
1013   ShiftAmt -= i;
1014   bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1015     isLittleEndian();
1016
1017   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1018     // Check the rest of the elements to see if they are consecutive.
1019     for (++i; i != 16; ++i)
1020       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1021         return -1;
1022   } else if (ShuffleKind == 1) {
1023     // Check the rest of the elements to see if they are consecutive.
1024     for (++i; i != 16; ++i)
1025       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1026         return -1;
1027   } else
1028     return -1;
1029
1030   if (ShuffleKind == 2 && isLE)
1031     ShiftAmt = 16 - ShiftAmt;
1032
1033   return ShiftAmt;
1034 }
1035
1036 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1037 /// specifies a splat of a single element that is suitable for input to
1038 /// VSPLTB/VSPLTH/VSPLTW.
1039 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1040   assert(N->getValueType(0) == MVT::v16i8 &&
1041          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1042
1043   // This is a splat operation if each element of the permute is the same, and
1044   // if the value doesn't reference the second vector.
1045   unsigned ElementBase = N->getMaskElt(0);
1046
1047   // FIXME: Handle UNDEF elements too!
1048   if (ElementBase >= 16)
1049     return false;
1050
1051   // Check that the indices are consecutive, in the case of a multi-byte element
1052   // splatted with a v16i8 mask.
1053   for (unsigned i = 1; i != EltSize; ++i)
1054     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1055       return false;
1056
1057   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1058     if (N->getMaskElt(i) < 0) continue;
1059     for (unsigned j = 0; j != EltSize; ++j)
1060       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1061         return false;
1062   }
1063   return true;
1064 }
1065
1066 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1067 /// are -0.0.
1068 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1069   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1070
1071   APInt APVal, APUndef;
1072   unsigned BitSize;
1073   bool HasAnyUndefs;
1074
1075   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1076     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1077       return CFP->getValueAPF().isNegZero();
1078
1079   return false;
1080 }
1081
1082 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1083 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1084 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1085                                 SelectionDAG &DAG) {
1086   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1087   assert(isSplatShuffleMask(SVOp, EltSize));
1088   if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1089     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1090   else
1091     return SVOp->getMaskElt(0) / EltSize;
1092 }
1093
1094 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1095 /// by using a vspltis[bhw] instruction of the specified element size, return
1096 /// the constant being splatted.  The ByteSize field indicates the number of
1097 /// bytes of each element [124] -> [bhw].
1098 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1099   SDValue OpVal(nullptr, 0);
1100
1101   // If ByteSize of the splat is bigger than the element size of the
1102   // build_vector, then we have a case where we are checking for a splat where
1103   // multiple elements of the buildvector are folded together into a single
1104   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1105   unsigned EltSize = 16/N->getNumOperands();
1106   if (EltSize < ByteSize) {
1107     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1108     SDValue UniquedVals[4];
1109     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1110
1111     // See if all of the elements in the buildvector agree across.
1112     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1113       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1114       // If the element isn't a constant, bail fully out.
1115       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1116
1117
1118       if (!UniquedVals[i&(Multiple-1)].getNode())
1119         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1120       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1121         return SDValue();  // no match.
1122     }
1123
1124     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1125     // either constant or undef values that are identical for each chunk.  See
1126     // if these chunks can form into a larger vspltis*.
1127
1128     // Check to see if all of the leading entries are either 0 or -1.  If
1129     // neither, then this won't fit into the immediate field.
1130     bool LeadingZero = true;
1131     bool LeadingOnes = true;
1132     for (unsigned i = 0; i != Multiple-1; ++i) {
1133       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1134
1135       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1136       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1137     }
1138     // Finally, check the least significant entry.
1139     if (LeadingZero) {
1140       if (!UniquedVals[Multiple-1].getNode())
1141         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1142       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1143       if (Val < 16)
1144         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1145     }
1146     if (LeadingOnes) {
1147       if (!UniquedVals[Multiple-1].getNode())
1148         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1149       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1150       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1151         return DAG.getTargetConstant(Val, MVT::i32);
1152     }
1153
1154     return SDValue();
1155   }
1156
1157   // Check to see if this buildvec has a single non-undef value in its elements.
1158   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1159     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1160     if (!OpVal.getNode())
1161       OpVal = N->getOperand(i);
1162     else if (OpVal != N->getOperand(i))
1163       return SDValue();
1164   }
1165
1166   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1167
1168   unsigned ValSizeInBytes = EltSize;
1169   uint64_t Value = 0;
1170   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1171     Value = CN->getZExtValue();
1172   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1173     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1174     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1175   }
1176
1177   // If the splat value is larger than the element value, then we can never do
1178   // this splat.  The only case that we could fit the replicated bits into our
1179   // immediate field for would be zero, and we prefer to use vxor for it.
1180   if (ValSizeInBytes < ByteSize) return SDValue();
1181
1182   // If the element value is larger than the splat value, cut it in half and
1183   // check to see if the two halves are equal.  Continue doing this until we
1184   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1185   while (ValSizeInBytes > ByteSize) {
1186     ValSizeInBytes >>= 1;
1187
1188     // If the top half equals the bottom half, we're still ok.
1189     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1190          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1191       return SDValue();
1192   }
1193
1194   // Properly sign extend the value.
1195   int MaskVal = SignExtend32(Value, ByteSize * 8);
1196
1197   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1198   if (MaskVal == 0) return SDValue();
1199
1200   // Finally, if this value fits in a 5 bit sext field, return it
1201   if (SignExtend32<5>(MaskVal) == MaskVal)
1202     return DAG.getTargetConstant(MaskVal, MVT::i32);
1203   return SDValue();
1204 }
1205
1206 //===----------------------------------------------------------------------===//
1207 //  Addressing Mode Selection
1208 //===----------------------------------------------------------------------===//
1209
1210 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1211 /// or 64-bit immediate, and if the value can be accurately represented as a
1212 /// sign extension from a 16-bit value.  If so, this returns true and the
1213 /// immediate.
1214 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1215   if (!isa<ConstantSDNode>(N))
1216     return false;
1217
1218   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1219   if (N->getValueType(0) == MVT::i32)
1220     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1221   else
1222     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1223 }
1224 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1225   return isIntS16Immediate(Op.getNode(), Imm);
1226 }
1227
1228
1229 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1230 /// can be represented as an indexed [r+r] operation.  Returns false if it
1231 /// can be more efficiently represented with [r+imm].
1232 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1233                                             SDValue &Index,
1234                                             SelectionDAG &DAG) const {
1235   short imm = 0;
1236   if (N.getOpcode() == ISD::ADD) {
1237     if (isIntS16Immediate(N.getOperand(1), imm))
1238       return false;    // r+i
1239     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1240       return false;    // r+i
1241
1242     Base = N.getOperand(0);
1243     Index = N.getOperand(1);
1244     return true;
1245   } else if (N.getOpcode() == ISD::OR) {
1246     if (isIntS16Immediate(N.getOperand(1), imm))
1247       return false;    // r+i can fold it if we can.
1248
1249     // If this is an or of disjoint bitfields, we can codegen this as an add
1250     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1251     // disjoint.
1252     APInt LHSKnownZero, LHSKnownOne;
1253     APInt RHSKnownZero, RHSKnownOne;
1254     DAG.computeKnownBits(N.getOperand(0),
1255                          LHSKnownZero, LHSKnownOne);
1256
1257     if (LHSKnownZero.getBoolValue()) {
1258       DAG.computeKnownBits(N.getOperand(1),
1259                            RHSKnownZero, RHSKnownOne);
1260       // If all of the bits are known zero on the LHS or RHS, the add won't
1261       // carry.
1262       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1263         Base = N.getOperand(0);
1264         Index = N.getOperand(1);
1265         return true;
1266       }
1267     }
1268   }
1269
1270   return false;
1271 }
1272
1273 // If we happen to be doing an i64 load or store into a stack slot that has
1274 // less than a 4-byte alignment, then the frame-index elimination may need to
1275 // use an indexed load or store instruction (because the offset may not be a
1276 // multiple of 4). The extra register needed to hold the offset comes from the
1277 // register scavenger, and it is possible that the scavenger will need to use
1278 // an emergency spill slot. As a result, we need to make sure that a spill slot
1279 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1280 // stack slot.
1281 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1282   // FIXME: This does not handle the LWA case.
1283   if (VT != MVT::i64)
1284     return;
1285
1286   // NOTE: We'll exclude negative FIs here, which come from argument
1287   // lowering, because there are no known test cases triggering this problem
1288   // using packed structures (or similar). We can remove this exclusion if
1289   // we find such a test case. The reason why this is so test-case driven is
1290   // because this entire 'fixup' is only to prevent crashes (from the
1291   // register scavenger) on not-really-valid inputs. For example, if we have:
1292   //   %a = alloca i1
1293   //   %b = bitcast i1* %a to i64*
1294   //   store i64* a, i64 b
1295   // then the store should really be marked as 'align 1', but is not. If it
1296   // were marked as 'align 1' then the indexed form would have been
1297   // instruction-selected initially, and the problem this 'fixup' is preventing
1298   // won't happen regardless.
1299   if (FrameIdx < 0)
1300     return;
1301
1302   MachineFunction &MF = DAG.getMachineFunction();
1303   MachineFrameInfo *MFI = MF.getFrameInfo();
1304
1305   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1306   if (Align >= 4)
1307     return;
1308
1309   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1310   FuncInfo->setHasNonRISpills();
1311 }
1312
1313 /// Returns true if the address N can be represented by a base register plus
1314 /// a signed 16-bit displacement [r+imm], and if it is not better
1315 /// represented as reg+reg.  If Aligned is true, only accept displacements
1316 /// suitable for STD and friends, i.e. multiples of 4.
1317 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1318                                             SDValue &Base,
1319                                             SelectionDAG &DAG,
1320                                             bool Aligned) const {
1321   // FIXME dl should come from parent load or store, not from address
1322   SDLoc dl(N);
1323   // If this can be more profitably realized as r+r, fail.
1324   if (SelectAddressRegReg(N, Disp, Base, DAG))
1325     return false;
1326
1327   if (N.getOpcode() == ISD::ADD) {
1328     short imm = 0;
1329     if (isIntS16Immediate(N.getOperand(1), imm) &&
1330         (!Aligned || (imm & 3) == 0)) {
1331       Disp = DAG.getTargetConstant(imm, N.getValueType());
1332       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1333         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1334         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1335       } else {
1336         Base = N.getOperand(0);
1337       }
1338       return true; // [r+i]
1339     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1340       // Match LOAD (ADD (X, Lo(G))).
1341       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1342              && "Cannot handle constant offsets yet!");
1343       Disp = N.getOperand(1).getOperand(0);  // The global address.
1344       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1345              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1346              Disp.getOpcode() == ISD::TargetConstantPool ||
1347              Disp.getOpcode() == ISD::TargetJumpTable);
1348       Base = N.getOperand(0);
1349       return true;  // [&g+r]
1350     }
1351   } else if (N.getOpcode() == ISD::OR) {
1352     short imm = 0;
1353     if (isIntS16Immediate(N.getOperand(1), imm) &&
1354         (!Aligned || (imm & 3) == 0)) {
1355       // If this is an or of disjoint bitfields, we can codegen this as an add
1356       // (for better address arithmetic) if the LHS and RHS of the OR are
1357       // provably disjoint.
1358       APInt LHSKnownZero, LHSKnownOne;
1359       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1360
1361       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1362         // If all of the bits are known zero on the LHS or RHS, the add won't
1363         // carry.
1364         if (FrameIndexSDNode *FI =
1365               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1366           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1367           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1368         } else {
1369           Base = N.getOperand(0);
1370         }
1371         Disp = DAG.getTargetConstant(imm, N.getValueType());
1372         return true;
1373       }
1374     }
1375   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1376     // Loading from a constant address.
1377
1378     // If this address fits entirely in a 16-bit sext immediate field, codegen
1379     // this as "d, 0"
1380     short Imm;
1381     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1382       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1383       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1384                              CN->getValueType(0));
1385       return true;
1386     }
1387
1388     // Handle 32-bit sext immediates with LIS + addr mode.
1389     if ((CN->getValueType(0) == MVT::i32 ||
1390          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1391         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1392       int Addr = (int)CN->getZExtValue();
1393
1394       // Otherwise, break this down into an LIS + disp.
1395       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1396
1397       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1398       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1399       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1400       return true;
1401     }
1402   }
1403
1404   Disp = DAG.getTargetConstant(0, getPointerTy());
1405   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1406     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1407     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1408   } else
1409     Base = N;
1410   return true;      // [r+0]
1411 }
1412
1413 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1414 /// represented as an indexed [r+r] operation.
1415 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1416                                                 SDValue &Index,
1417                                                 SelectionDAG &DAG) const {
1418   // Check to see if we can easily represent this as an [r+r] address.  This
1419   // will fail if it thinks that the address is more profitably represented as
1420   // reg+imm, e.g. where imm = 0.
1421   if (SelectAddressRegReg(N, Base, Index, DAG))
1422     return true;
1423
1424   // If the operand is an addition, always emit this as [r+r], since this is
1425   // better (for code size, and execution, as the memop does the add for free)
1426   // than emitting an explicit add.
1427   if (N.getOpcode() == ISD::ADD) {
1428     Base = N.getOperand(0);
1429     Index = N.getOperand(1);
1430     return true;
1431   }
1432
1433   // Otherwise, do it the hard way, using R0 as the base register.
1434   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1435                          N.getValueType());
1436   Index = N;
1437   return true;
1438 }
1439
1440 /// getPreIndexedAddressParts - returns true by value, base pointer and
1441 /// offset pointer and addressing mode by reference if the node's address
1442 /// can be legally represented as pre-indexed load / store address.
1443 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1444                                                   SDValue &Offset,
1445                                                   ISD::MemIndexedMode &AM,
1446                                                   SelectionDAG &DAG) const {
1447   if (DisablePPCPreinc) return false;
1448
1449   bool isLoad = true;
1450   SDValue Ptr;
1451   EVT VT;
1452   unsigned Alignment;
1453   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1454     Ptr = LD->getBasePtr();
1455     VT = LD->getMemoryVT();
1456     Alignment = LD->getAlignment();
1457   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1458     Ptr = ST->getBasePtr();
1459     VT  = ST->getMemoryVT();
1460     Alignment = ST->getAlignment();
1461     isLoad = false;
1462   } else
1463     return false;
1464
1465   // PowerPC doesn't have preinc load/store instructions for vectors.
1466   if (VT.isVector())
1467     return false;
1468
1469   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1470
1471     // Common code will reject creating a pre-inc form if the base pointer
1472     // is a frame index, or if N is a store and the base pointer is either
1473     // the same as or a predecessor of the value being stored.  Check for
1474     // those situations here, and try with swapped Base/Offset instead.
1475     bool Swap = false;
1476
1477     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1478       Swap = true;
1479     else if (!isLoad) {
1480       SDValue Val = cast<StoreSDNode>(N)->getValue();
1481       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1482         Swap = true;
1483     }
1484
1485     if (Swap)
1486       std::swap(Base, Offset);
1487
1488     AM = ISD::PRE_INC;
1489     return true;
1490   }
1491
1492   // LDU/STU can only handle immediates that are a multiple of 4.
1493   if (VT != MVT::i64) {
1494     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1495       return false;
1496   } else {
1497     // LDU/STU need an address with at least 4-byte alignment.
1498     if (Alignment < 4)
1499       return false;
1500
1501     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1502       return false;
1503   }
1504
1505   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1506     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1507     // sext i32 to i64 when addr mode is r+i.
1508     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1509         LD->getExtensionType() == ISD::SEXTLOAD &&
1510         isa<ConstantSDNode>(Offset))
1511       return false;
1512   }
1513
1514   AM = ISD::PRE_INC;
1515   return true;
1516 }
1517
1518 //===----------------------------------------------------------------------===//
1519 //  LowerOperation implementation
1520 //===----------------------------------------------------------------------===//
1521
1522 /// GetLabelAccessInfo - Return true if we should reference labels using a
1523 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1524 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1525                                unsigned &LoOpFlags,
1526                                const GlobalValue *GV = nullptr) {
1527   HiOpFlags = PPCII::MO_HA;
1528   LoOpFlags = PPCII::MO_LO;
1529
1530   // Don't use the pic base if not in PIC relocation model.
1531   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1532
1533   if (isPIC) {
1534     HiOpFlags |= PPCII::MO_PIC_FLAG;
1535     LoOpFlags |= PPCII::MO_PIC_FLAG;
1536   }
1537
1538   // If this is a reference to a global value that requires a non-lazy-ptr, make
1539   // sure that instruction lowering adds it.
1540   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1541     HiOpFlags |= PPCII::MO_NLP_FLAG;
1542     LoOpFlags |= PPCII::MO_NLP_FLAG;
1543
1544     if (GV->hasHiddenVisibility()) {
1545       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1546       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1547     }
1548   }
1549
1550   return isPIC;
1551 }
1552
1553 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1554                              SelectionDAG &DAG) {
1555   EVT PtrVT = HiPart.getValueType();
1556   SDValue Zero = DAG.getConstant(0, PtrVT);
1557   SDLoc DL(HiPart);
1558
1559   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1560   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1561
1562   // With PIC, the first instruction is actually "GR+hi(&G)".
1563   if (isPIC)
1564     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1565                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1566
1567   // Generate non-pic code that has direct accesses to the constant pool.
1568   // The address of the global is just (hi(&g)+lo(&g)).
1569   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1570 }
1571
1572 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1573                                              SelectionDAG &DAG) const {
1574   EVT PtrVT = Op.getValueType();
1575   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1576   const Constant *C = CP->getConstVal();
1577
1578   // 64-bit SVR4 ABI code is always position-independent.
1579   // The actual address of the GlobalValue is stored in the TOC.
1580   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1581     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1582     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1583                        DAG.getRegister(PPC::X2, MVT::i64));
1584   }
1585
1586   unsigned MOHiFlag, MOLoFlag;
1587   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1588
1589   if (isPIC && Subtarget.isSVR4ABI()) {
1590     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1591                                            PPCII::MO_PIC_FLAG);
1592     SDLoc DL(CP);
1593     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1594                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1595   }
1596
1597   SDValue CPIHi =
1598     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1599   SDValue CPILo =
1600     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1601   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1602 }
1603
1604 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1605   EVT PtrVT = Op.getValueType();
1606   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1607
1608   // 64-bit SVR4 ABI code is always position-independent.
1609   // The actual address of the GlobalValue is stored in the TOC.
1610   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1611     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1612     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1613                        DAG.getRegister(PPC::X2, MVT::i64));
1614   }
1615
1616   unsigned MOHiFlag, MOLoFlag;
1617   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1618
1619   if (isPIC && Subtarget.isSVR4ABI()) {
1620     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1621                                         PPCII::MO_PIC_FLAG);
1622     SDLoc DL(GA);
1623     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1624                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1625   }
1626
1627   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1628   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1629   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1630 }
1631
1632 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1633                                              SelectionDAG &DAG) const {
1634   EVT PtrVT = Op.getValueType();
1635   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1636   const BlockAddress *BA = BASDN->getBlockAddress();
1637
1638   // 64-bit SVR4 ABI code is always position-independent.
1639   // The actual BlockAddress is stored in the TOC.
1640   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1641     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1642     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1643                        DAG.getRegister(PPC::X2, MVT::i64));
1644   }
1645
1646   unsigned MOHiFlag, MOLoFlag;
1647   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1648   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1649   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1650   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1651 }
1652
1653 // Generate a call to __tls_get_addr for the given GOT entry Op.
1654 std::pair<SDValue,SDValue>
1655 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1656                                 SelectionDAG &DAG) const {
1657
1658   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1659   TargetLowering::ArgListTy Args;
1660   TargetLowering::ArgListEntry Entry;
1661   Entry.Node = Op;
1662   Entry.Ty = IntPtrTy;
1663   Args.push_back(Entry);
1664
1665   TargetLowering::CallLoweringInfo CLI(DAG);
1666   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1667     .setCallee(CallingConv::C, IntPtrTy,
1668                DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1669                std::move(Args), 0);
1670
1671   return LowerCallTo(CLI);
1672 }
1673
1674 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1675                                               SelectionDAG &DAG) const {
1676
1677   // FIXME: TLS addresses currently use medium model code sequences,
1678   // which is the most useful form.  Eventually support for small and
1679   // large models could be added if users need it, at the cost of
1680   // additional complexity.
1681   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1682   SDLoc dl(GA);
1683   const GlobalValue *GV = GA->getGlobal();
1684   EVT PtrVT = getPointerTy();
1685   bool is64bit = Subtarget.isPPC64();
1686   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1687   PICLevel::Level picLevel = M->getPICLevel();
1688
1689   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1690
1691   if (Model == TLSModel::LocalExec) {
1692     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1693                                                PPCII::MO_TPREL_HA);
1694     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1695                                                PPCII::MO_TPREL_LO);
1696     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1697                                      is64bit ? MVT::i64 : MVT::i32);
1698     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1699     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1700   }
1701
1702   if (Model == TLSModel::InitialExec) {
1703     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1704     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1705                                                 PPCII::MO_TLS);
1706     SDValue GOTPtr;
1707     if (is64bit) {
1708       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1709       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1710                            PtrVT, GOTReg, TGA);
1711     } else
1712       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1713     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1714                                    PtrVT, TGA, GOTPtr);
1715     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1716   }
1717
1718   if (Model == TLSModel::GeneralDynamic) {
1719     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1720                                              PPCII::MO_TLSGD);
1721     SDValue GOTPtr;
1722     if (is64bit) {
1723       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1724       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1725                                    GOTReg, TGA);
1726     } else {
1727       if (picLevel == PICLevel::Small)
1728         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1729       else
1730         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1731     }
1732     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1733                                    GOTPtr, TGA);
1734     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1735     return CallResult.first;
1736   }
1737
1738   if (Model == TLSModel::LocalDynamic) {
1739     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1740                                              PPCII::MO_TLSLD);
1741     SDValue GOTPtr;
1742     if (is64bit) {
1743       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1744       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1745                            GOTReg, TGA);
1746     } else {
1747       if (picLevel == PICLevel::Small)
1748         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1749       else
1750         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1751     }
1752     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1753                                    GOTPtr, TGA);
1754     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1755     SDValue TLSAddr = CallResult.first;
1756     SDValue Chain = CallResult.second;
1757     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1758                                       Chain, TLSAddr, TGA);
1759     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1760   }
1761
1762   llvm_unreachable("Unknown TLS model!");
1763 }
1764
1765 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1766                                               SelectionDAG &DAG) const {
1767   EVT PtrVT = Op.getValueType();
1768   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1769   SDLoc DL(GSDN);
1770   const GlobalValue *GV = GSDN->getGlobal();
1771
1772   // 64-bit SVR4 ABI code is always position-independent.
1773   // The actual address of the GlobalValue is stored in the TOC.
1774   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1775     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1776     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1777                        DAG.getRegister(PPC::X2, MVT::i64));
1778   }
1779
1780   unsigned MOHiFlag, MOLoFlag;
1781   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1782
1783   if (isPIC && Subtarget.isSVR4ABI()) {
1784     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1785                                             GSDN->getOffset(),
1786                                             PPCII::MO_PIC_FLAG);
1787     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1788                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1789   }
1790
1791   SDValue GAHi =
1792     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1793   SDValue GALo =
1794     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1795
1796   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1797
1798   // If the global reference is actually to a non-lazy-pointer, we have to do an
1799   // extra load to get the address of the global.
1800   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1801     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1802                       false, false, false, 0);
1803   return Ptr;
1804 }
1805
1806 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1807   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1808   SDLoc dl(Op);
1809
1810   if (Op.getValueType() == MVT::v2i64) {
1811     // When the operands themselves are v2i64 values, we need to do something
1812     // special because VSX has no underlying comparison operations for these.
1813     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1814       // Equality can be handled by casting to the legal type for Altivec
1815       // comparisons, everything else needs to be expanded.
1816       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1817         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1818                  DAG.getSetCC(dl, MVT::v4i32,
1819                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1820                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1821                    CC));
1822       }
1823
1824       return SDValue();
1825     }
1826
1827     // We handle most of these in the usual way.
1828     return Op;
1829   }
1830
1831   // If we're comparing for equality to zero, expose the fact that this is
1832   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1833   // fold the new nodes.
1834   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1835     if (C->isNullValue() && CC == ISD::SETEQ) {
1836       EVT VT = Op.getOperand(0).getValueType();
1837       SDValue Zext = Op.getOperand(0);
1838       if (VT.bitsLT(MVT::i32)) {
1839         VT = MVT::i32;
1840         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1841       }
1842       unsigned Log2b = Log2_32(VT.getSizeInBits());
1843       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1844       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1845                                 DAG.getConstant(Log2b, MVT::i32));
1846       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1847     }
1848     // Leave comparisons against 0 and -1 alone for now, since they're usually
1849     // optimized.  FIXME: revisit this when we can custom lower all setcc
1850     // optimizations.
1851     if (C->isAllOnesValue() || C->isNullValue())
1852       return SDValue();
1853   }
1854
1855   // If we have an integer seteq/setne, turn it into a compare against zero
1856   // by xor'ing the rhs with the lhs, which is faster than setting a
1857   // condition register, reading it back out, and masking the correct bit.  The
1858   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1859   // the result to other bit-twiddling opportunities.
1860   EVT LHSVT = Op.getOperand(0).getValueType();
1861   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1862     EVT VT = Op.getValueType();
1863     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1864                                 Op.getOperand(1));
1865     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1866   }
1867   return SDValue();
1868 }
1869
1870 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1871                                       const PPCSubtarget &Subtarget) const {
1872   SDNode *Node = Op.getNode();
1873   EVT VT = Node->getValueType(0);
1874   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1875   SDValue InChain = Node->getOperand(0);
1876   SDValue VAListPtr = Node->getOperand(1);
1877   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1878   SDLoc dl(Node);
1879
1880   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1881
1882   // gpr_index
1883   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1884                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1885                                     false, false, false, 0);
1886   InChain = GprIndex.getValue(1);
1887
1888   if (VT == MVT::i64) {
1889     // Check if GprIndex is even
1890     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1891                                  DAG.getConstant(1, MVT::i32));
1892     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1893                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1894     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1895                                           DAG.getConstant(1, MVT::i32));
1896     // Align GprIndex to be even if it isn't
1897     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1898                            GprIndex);
1899   }
1900
1901   // fpr index is 1 byte after gpr
1902   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1903                                DAG.getConstant(1, MVT::i32));
1904
1905   // fpr
1906   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1907                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1908                                     false, false, false, 0);
1909   InChain = FprIndex.getValue(1);
1910
1911   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1912                                        DAG.getConstant(8, MVT::i32));
1913
1914   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1915                                         DAG.getConstant(4, MVT::i32));
1916
1917   // areas
1918   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1919                                      MachinePointerInfo(), false, false,
1920                                      false, 0);
1921   InChain = OverflowArea.getValue(1);
1922
1923   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1924                                     MachinePointerInfo(), false, false,
1925                                     false, 0);
1926   InChain = RegSaveArea.getValue(1);
1927
1928   // select overflow_area if index > 8
1929   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1930                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1931
1932   // adjustment constant gpr_index * 4/8
1933   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1934                                     VT.isInteger() ? GprIndex : FprIndex,
1935                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1936                                                     MVT::i32));
1937
1938   // OurReg = RegSaveArea + RegConstant
1939   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1940                                RegConstant);
1941
1942   // Floating types are 32 bytes into RegSaveArea
1943   if (VT.isFloatingPoint())
1944     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1945                          DAG.getConstant(32, MVT::i32));
1946
1947   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1948   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1949                                    VT.isInteger() ? GprIndex : FprIndex,
1950                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1951                                                    MVT::i32));
1952
1953   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1954                               VT.isInteger() ? VAListPtr : FprPtr,
1955                               MachinePointerInfo(SV),
1956                               MVT::i8, false, false, 0);
1957
1958   // determine if we should load from reg_save_area or overflow_area
1959   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1960
1961   // increase overflow_area by 4/8 if gpr/fpr > 8
1962   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1963                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1964                                           MVT::i32));
1965
1966   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1967                              OverflowAreaPlusN);
1968
1969   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1970                               OverflowAreaPtr,
1971                               MachinePointerInfo(),
1972                               MVT::i32, false, false, 0);
1973
1974   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1975                      false, false, false, 0);
1976 }
1977
1978 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1979                                        const PPCSubtarget &Subtarget) const {
1980   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1981
1982   // We have to copy the entire va_list struct:
1983   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1984   return DAG.getMemcpy(Op.getOperand(0), Op,
1985                        Op.getOperand(1), Op.getOperand(2),
1986                        DAG.getConstant(12, MVT::i32), 8, false, true,
1987                        MachinePointerInfo(), MachinePointerInfo());
1988 }
1989
1990 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1991                                                   SelectionDAG &DAG) const {
1992   return Op.getOperand(0);
1993 }
1994
1995 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1996                                                 SelectionDAG &DAG) const {
1997   SDValue Chain = Op.getOperand(0);
1998   SDValue Trmp = Op.getOperand(1); // trampoline
1999   SDValue FPtr = Op.getOperand(2); // nested function
2000   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2001   SDLoc dl(Op);
2002
2003   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2004   bool isPPC64 = (PtrVT == MVT::i64);
2005   Type *IntPtrTy =
2006     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2007                                                              *DAG.getContext());
2008
2009   TargetLowering::ArgListTy Args;
2010   TargetLowering::ArgListEntry Entry;
2011
2012   Entry.Ty = IntPtrTy;
2013   Entry.Node = Trmp; Args.push_back(Entry);
2014
2015   // TrampSize == (isPPC64 ? 48 : 40);
2016   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2017                                isPPC64 ? MVT::i64 : MVT::i32);
2018   Args.push_back(Entry);
2019
2020   Entry.Node = FPtr; Args.push_back(Entry);
2021   Entry.Node = Nest; Args.push_back(Entry);
2022
2023   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2024   TargetLowering::CallLoweringInfo CLI(DAG);
2025   CLI.setDebugLoc(dl).setChain(Chain)
2026     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2027                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2028                std::move(Args), 0);
2029
2030   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2031   return CallResult.second;
2032 }
2033
2034 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2035                                         const PPCSubtarget &Subtarget) const {
2036   MachineFunction &MF = DAG.getMachineFunction();
2037   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2038
2039   SDLoc dl(Op);
2040
2041   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2042     // vastart just stores the address of the VarArgsFrameIndex slot into the
2043     // memory location argument.
2044     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2045     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2046     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2047     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2048                         MachinePointerInfo(SV),
2049                         false, false, 0);
2050   }
2051
2052   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2053   // We suppose the given va_list is already allocated.
2054   //
2055   // typedef struct {
2056   //  char gpr;     /* index into the array of 8 GPRs
2057   //                 * stored in the register save area
2058   //                 * gpr=0 corresponds to r3,
2059   //                 * gpr=1 to r4, etc.
2060   //                 */
2061   //  char fpr;     /* index into the array of 8 FPRs
2062   //                 * stored in the register save area
2063   //                 * fpr=0 corresponds to f1,
2064   //                 * fpr=1 to f2, etc.
2065   //                 */
2066   //  char *overflow_arg_area;
2067   //                /* location on stack that holds
2068   //                 * the next overflow argument
2069   //                 */
2070   //  char *reg_save_area;
2071   //               /* where r3:r10 and f1:f8 (if saved)
2072   //                * are stored
2073   //                */
2074   // } va_list[1];
2075
2076
2077   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2078   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2079
2080
2081   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2082
2083   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2084                                             PtrVT);
2085   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2086                                  PtrVT);
2087
2088   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2089   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2090
2091   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2092   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2093
2094   uint64_t FPROffset = 1;
2095   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2096
2097   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2098
2099   // Store first byte : number of int regs
2100   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2101                                          Op.getOperand(1),
2102                                          MachinePointerInfo(SV),
2103                                          MVT::i8, false, false, 0);
2104   uint64_t nextOffset = FPROffset;
2105   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2106                                   ConstFPROffset);
2107
2108   // Store second byte : number of float regs
2109   SDValue secondStore =
2110     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2111                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2112                       false, false, 0);
2113   nextOffset += StackOffset;
2114   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2115
2116   // Store second word : arguments given on stack
2117   SDValue thirdStore =
2118     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2119                  MachinePointerInfo(SV, nextOffset),
2120                  false, false, 0);
2121   nextOffset += FrameOffset;
2122   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2123
2124   // Store third word : arguments given in registers
2125   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2126                       MachinePointerInfo(SV, nextOffset),
2127                       false, false, 0);
2128
2129 }
2130
2131 #include "PPCGenCallingConv.inc"
2132
2133 // Function whose sole purpose is to kill compiler warnings 
2134 // stemming from unused functions included from PPCGenCallingConv.inc.
2135 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2136   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2137 }
2138
2139 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2140                                       CCValAssign::LocInfo &LocInfo,
2141                                       ISD::ArgFlagsTy &ArgFlags,
2142                                       CCState &State) {
2143   return true;
2144 }
2145
2146 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2147                                              MVT &LocVT,
2148                                              CCValAssign::LocInfo &LocInfo,
2149                                              ISD::ArgFlagsTy &ArgFlags,
2150                                              CCState &State) {
2151   static const MCPhysReg ArgRegs[] = {
2152     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2153     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2154   };
2155   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2156
2157   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2158
2159   // Skip one register if the first unallocated register has an even register
2160   // number and there are still argument registers available which have not been
2161   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2162   // need to skip a register if RegNum is odd.
2163   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2164     State.AllocateReg(ArgRegs[RegNum]);
2165   }
2166
2167   // Always return false here, as this function only makes sure that the first
2168   // unallocated register has an odd register number and does not actually
2169   // allocate a register for the current argument.
2170   return false;
2171 }
2172
2173 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2174                                                MVT &LocVT,
2175                                                CCValAssign::LocInfo &LocInfo,
2176                                                ISD::ArgFlagsTy &ArgFlags,
2177                                                CCState &State) {
2178   static const MCPhysReg ArgRegs[] = {
2179     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2180     PPC::F8
2181   };
2182
2183   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2184
2185   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2186
2187   // If there is only one Floating-point register left we need to put both f64
2188   // values of a split ppc_fp128 value on the stack.
2189   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2190     State.AllocateReg(ArgRegs[RegNum]);
2191   }
2192
2193   // Always return false here, as this function only makes sure that the two f64
2194   // values a ppc_fp128 value is split into are both passed in registers or both
2195   // passed on the stack and does not actually allocate a register for the
2196   // current argument.
2197   return false;
2198 }
2199
2200 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2201 /// on Darwin.
2202 static const MCPhysReg *GetFPR() {
2203   static const MCPhysReg FPR[] = {
2204     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2205     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2206   };
2207
2208   return FPR;
2209 }
2210
2211 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2212 /// the stack.
2213 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2214                                        unsigned PtrByteSize) {
2215   unsigned ArgSize = ArgVT.getStoreSize();
2216   if (Flags.isByVal())
2217     ArgSize = Flags.getByValSize();
2218
2219   // Round up to multiples of the pointer size, except for array members,
2220   // which are always packed.
2221   if (!Flags.isInConsecutiveRegs())
2222     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2223
2224   return ArgSize;
2225 }
2226
2227 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2228 /// on the stack.
2229 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2230                                             ISD::ArgFlagsTy Flags,
2231                                             unsigned PtrByteSize) {
2232   unsigned Align = PtrByteSize;
2233
2234   // Altivec parameters are padded to a 16 byte boundary.
2235   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2236       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2237       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2238     Align = 16;
2239
2240   // ByVal parameters are aligned as requested.
2241   if (Flags.isByVal()) {
2242     unsigned BVAlign = Flags.getByValAlign();
2243     if (BVAlign > PtrByteSize) {
2244       if (BVAlign % PtrByteSize != 0)
2245           llvm_unreachable(
2246             "ByVal alignment is not a multiple of the pointer size");
2247
2248       Align = BVAlign;
2249     }
2250   }
2251
2252   // Array members are always packed to their original alignment.
2253   if (Flags.isInConsecutiveRegs()) {
2254     // If the array member was split into multiple registers, the first
2255     // needs to be aligned to the size of the full type.  (Except for
2256     // ppcf128, which is only aligned as its f64 components.)
2257     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2258       Align = OrigVT.getStoreSize();
2259     else
2260       Align = ArgVT.getStoreSize();
2261   }
2262
2263   return Align;
2264 }
2265
2266 /// CalculateStackSlotUsed - Return whether this argument will use its
2267 /// stack slot (instead of being passed in registers).  ArgOffset,
2268 /// AvailableFPRs, and AvailableVRs must hold the current argument
2269 /// position, and will be updated to account for this argument.
2270 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2271                                    ISD::ArgFlagsTy Flags,
2272                                    unsigned PtrByteSize,
2273                                    unsigned LinkageSize,
2274                                    unsigned ParamAreaSize,
2275                                    unsigned &ArgOffset,
2276                                    unsigned &AvailableFPRs,
2277                                    unsigned &AvailableVRs) {
2278   bool UseMemory = false;
2279
2280   // Respect alignment of argument on the stack.
2281   unsigned Align =
2282     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2283   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2284   // If there's no space left in the argument save area, we must
2285   // use memory (this check also catches zero-sized arguments).
2286   if (ArgOffset >= LinkageSize + ParamAreaSize)
2287     UseMemory = true;
2288
2289   // Allocate argument on the stack.
2290   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2291   if (Flags.isInConsecutiveRegsLast())
2292     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2293   // If we overran the argument save area, we must use memory
2294   // (this check catches arguments passed partially in memory)
2295   if (ArgOffset > LinkageSize + ParamAreaSize)
2296     UseMemory = true;
2297
2298   // However, if the argument is actually passed in an FPR or a VR,
2299   // we don't use memory after all.
2300   if (!Flags.isByVal()) {
2301     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2302       if (AvailableFPRs > 0) {
2303         --AvailableFPRs;
2304         return false;
2305       }
2306     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2307         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2308         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2309       if (AvailableVRs > 0) {
2310         --AvailableVRs;
2311         return false;
2312       }
2313   }
2314
2315   return UseMemory;
2316 }
2317
2318 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2319 /// ensure minimum alignment required for target.
2320 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2321                                      unsigned NumBytes) {
2322   unsigned TargetAlign =
2323       Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2324   unsigned AlignMask = TargetAlign - 1;
2325   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2326   return NumBytes;
2327 }
2328
2329 SDValue
2330 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2331                                         CallingConv::ID CallConv, bool isVarArg,
2332                                         const SmallVectorImpl<ISD::InputArg>
2333                                           &Ins,
2334                                         SDLoc dl, SelectionDAG &DAG,
2335                                         SmallVectorImpl<SDValue> &InVals)
2336                                           const {
2337   if (Subtarget.isSVR4ABI()) {
2338     if (Subtarget.isPPC64())
2339       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2340                                          dl, DAG, InVals);
2341     else
2342       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2343                                          dl, DAG, InVals);
2344   } else {
2345     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2346                                        dl, DAG, InVals);
2347   }
2348 }
2349
2350 SDValue
2351 PPCTargetLowering::LowerFormalArguments_32SVR4(
2352                                       SDValue Chain,
2353                                       CallingConv::ID CallConv, bool isVarArg,
2354                                       const SmallVectorImpl<ISD::InputArg>
2355                                         &Ins,
2356                                       SDLoc dl, SelectionDAG &DAG,
2357                                       SmallVectorImpl<SDValue> &InVals) const {
2358
2359   // 32-bit SVR4 ABI Stack Frame Layout:
2360   //              +-----------------------------------+
2361   //        +-->  |            Back chain             |
2362   //        |     +-----------------------------------+
2363   //        |     | Floating-point register save area |
2364   //        |     +-----------------------------------+
2365   //        |     |    General register save area     |
2366   //        |     +-----------------------------------+
2367   //        |     |          CR save word             |
2368   //        |     +-----------------------------------+
2369   //        |     |         VRSAVE save word          |
2370   //        |     +-----------------------------------+
2371   //        |     |         Alignment padding         |
2372   //        |     +-----------------------------------+
2373   //        |     |     Vector register save area     |
2374   //        |     +-----------------------------------+
2375   //        |     |       Local variable space        |
2376   //        |     +-----------------------------------+
2377   //        |     |        Parameter list area        |
2378   //        |     +-----------------------------------+
2379   //        |     |           LR save word            |
2380   //        |     +-----------------------------------+
2381   // SP-->  +---  |            Back chain             |
2382   //              +-----------------------------------+
2383   //
2384   // Specifications:
2385   //   System V Application Binary Interface PowerPC Processor Supplement
2386   //   AltiVec Technology Programming Interface Manual
2387
2388   MachineFunction &MF = DAG.getMachineFunction();
2389   MachineFrameInfo *MFI = MF.getFrameInfo();
2390   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2391
2392   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2393   // Potential tail calls could cause overwriting of argument stack slots.
2394   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2395                        (CallConv == CallingConv::Fast));
2396   unsigned PtrByteSize = 4;
2397
2398   // Assign locations to all of the incoming arguments.
2399   SmallVector<CCValAssign, 16> ArgLocs;
2400   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2401                  *DAG.getContext());
2402
2403   // Reserve space for the linkage area on the stack.
2404   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2405   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2406
2407   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2408
2409   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410     CCValAssign &VA = ArgLocs[i];
2411
2412     // Arguments stored in registers.
2413     if (VA.isRegLoc()) {
2414       const TargetRegisterClass *RC;
2415       EVT ValVT = VA.getValVT();
2416
2417       switch (ValVT.getSimpleVT().SimpleTy) {
2418         default:
2419           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2420         case MVT::i1:
2421         case MVT::i32:
2422           RC = &PPC::GPRCRegClass;
2423           break;
2424         case MVT::f32:
2425           RC = &PPC::F4RCRegClass;
2426           break;
2427         case MVT::f64:
2428           if (Subtarget.hasVSX())
2429             RC = &PPC::VSFRCRegClass;
2430           else
2431             RC = &PPC::F8RCRegClass;
2432           break;
2433         case MVT::v16i8:
2434         case MVT::v8i16:
2435         case MVT::v4i32:
2436         case MVT::v4f32:
2437           RC = &PPC::VRRCRegClass;
2438           break;
2439         case MVT::v2f64:
2440         case MVT::v2i64:
2441           RC = &PPC::VSHRCRegClass;
2442           break;
2443       }
2444
2445       // Transform the arguments stored in physical registers into virtual ones.
2446       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2447       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2448                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2449
2450       if (ValVT == MVT::i1)
2451         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2452
2453       InVals.push_back(ArgValue);
2454     } else {
2455       // Argument stored in memory.
2456       assert(VA.isMemLoc());
2457
2458       unsigned ArgSize = VA.getLocVT().getStoreSize();
2459       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2460                                       isImmutable);
2461
2462       // Create load nodes to retrieve arguments from the stack.
2463       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2464       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2465                                    MachinePointerInfo(),
2466                                    false, false, false, 0));
2467     }
2468   }
2469
2470   // Assign locations to all of the incoming aggregate by value arguments.
2471   // Aggregates passed by value are stored in the local variable space of the
2472   // caller's stack frame, right above the parameter list area.
2473   SmallVector<CCValAssign, 16> ByValArgLocs;
2474   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2475                       ByValArgLocs, *DAG.getContext());
2476
2477   // Reserve stack space for the allocations in CCInfo.
2478   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2479
2480   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2481
2482   // Area that is at least reserved in the caller of this function.
2483   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2484   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2485
2486   // Set the size that is at least reserved in caller of this function.  Tail
2487   // call optimized function's reserved stack space needs to be aligned so that
2488   // taking the difference between two stack areas will result in an aligned
2489   // stack.
2490   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2491   FuncInfo->setMinReservedArea(MinReservedArea);
2492
2493   SmallVector<SDValue, 8> MemOps;
2494
2495   // If the function takes variable number of arguments, make a frame index for
2496   // the start of the first vararg value... for expansion of llvm.va_start.
2497   if (isVarArg) {
2498     static const MCPhysReg GPArgRegs[] = {
2499       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2500       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2501     };
2502     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2503
2504     static const MCPhysReg FPArgRegs[] = {
2505       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2506       PPC::F8
2507     };
2508     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2509     if (DisablePPCFloatInVariadic)
2510       NumFPArgRegs = 0;
2511
2512     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2513                                                           NumGPArgRegs));
2514     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2515                                                           NumFPArgRegs));
2516
2517     // Make room for NumGPArgRegs and NumFPArgRegs.
2518     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2519                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2520
2521     FuncInfo->setVarArgsStackOffset(
2522       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2523                              CCInfo.getNextStackOffset(), true));
2524
2525     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2526     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2527
2528     // The fixed integer arguments of a variadic function are stored to the
2529     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2530     // the result of va_next.
2531     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2532       // Get an existing live-in vreg, or add a new one.
2533       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2534       if (!VReg)
2535         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2536
2537       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2538       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2539                                    MachinePointerInfo(), false, false, 0);
2540       MemOps.push_back(Store);
2541       // Increment the address by four for the next argument to store
2542       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2543       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2544     }
2545
2546     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2547     // is set.
2548     // The double arguments are stored to the VarArgsFrameIndex
2549     // on the stack.
2550     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2551       // Get an existing live-in vreg, or add a new one.
2552       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2553       if (!VReg)
2554         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2555
2556       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2557       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2558                                    MachinePointerInfo(), false, false, 0);
2559       MemOps.push_back(Store);
2560       // Increment the address by eight for the next argument to store
2561       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2562                                          PtrVT);
2563       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2564     }
2565   }
2566
2567   if (!MemOps.empty())
2568     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2569
2570   return Chain;
2571 }
2572
2573 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2574 // value to MVT::i64 and then truncate to the correct register size.
2575 SDValue
2576 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2577                                      SelectionDAG &DAG, SDValue ArgVal,
2578                                      SDLoc dl) const {
2579   if (Flags.isSExt())
2580     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2581                          DAG.getValueType(ObjectVT));
2582   else if (Flags.isZExt())
2583     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2584                          DAG.getValueType(ObjectVT));
2585
2586   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2587 }
2588
2589 SDValue
2590 PPCTargetLowering::LowerFormalArguments_64SVR4(
2591                                       SDValue Chain,
2592                                       CallingConv::ID CallConv, bool isVarArg,
2593                                       const SmallVectorImpl<ISD::InputArg>
2594                                         &Ins,
2595                                       SDLoc dl, SelectionDAG &DAG,
2596                                       SmallVectorImpl<SDValue> &InVals) const {
2597   // TODO: add description of PPC stack frame format, or at least some docs.
2598   //
2599   bool isELFv2ABI = Subtarget.isELFv2ABI();
2600   bool isLittleEndian = Subtarget.isLittleEndian();
2601   MachineFunction &MF = DAG.getMachineFunction();
2602   MachineFrameInfo *MFI = MF.getFrameInfo();
2603   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2604
2605   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2606   // Potential tail calls could cause overwriting of argument stack slots.
2607   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2608                        (CallConv == CallingConv::Fast));
2609   unsigned PtrByteSize = 8;
2610
2611   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2612                                                           isELFv2ABI);
2613
2614   static const MCPhysReg GPR[] = {
2615     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2616     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2617   };
2618
2619   static const MCPhysReg *FPR = GetFPR();
2620
2621   static const MCPhysReg VR[] = {
2622     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2623     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2624   };
2625   static const MCPhysReg VSRH[] = {
2626     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2627     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2628   };
2629
2630   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2631   const unsigned Num_FPR_Regs = 13;
2632   const unsigned Num_VR_Regs  = array_lengthof(VR);
2633
2634   // Do a first pass over the arguments to determine whether the ABI
2635   // guarantees that our caller has allocated the parameter save area
2636   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2637   // in the ELFv2 ABI, it is true if this is a vararg function or if
2638   // any parameter is located in a stack slot.
2639
2640   bool HasParameterArea = !isELFv2ABI || isVarArg;
2641   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2642   unsigned NumBytes = LinkageSize;
2643   unsigned AvailableFPRs = Num_FPR_Regs;
2644   unsigned AvailableVRs = Num_VR_Regs;
2645   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2646     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2647                                PtrByteSize, LinkageSize, ParamAreaSize,
2648                                NumBytes, AvailableFPRs, AvailableVRs))
2649       HasParameterArea = true;
2650
2651   // Add DAG nodes to load the arguments or copy them out of registers.  On
2652   // entry to a function on PPC, the arguments start after the linkage area,
2653   // although the first ones are often in registers.
2654
2655   unsigned ArgOffset = LinkageSize;
2656   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2657   SmallVector<SDValue, 8> MemOps;
2658   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2659   unsigned CurArgIdx = 0;
2660   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2661     SDValue ArgVal;
2662     bool needsLoad = false;
2663     EVT ObjectVT = Ins[ArgNo].VT;
2664     EVT OrigVT = Ins[ArgNo].ArgVT;
2665     unsigned ObjSize = ObjectVT.getStoreSize();
2666     unsigned ArgSize = ObjSize;
2667     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2668     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2669     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2670
2671     /* Respect alignment of argument on the stack.  */
2672     unsigned Align =
2673       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2674     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2675     unsigned CurArgOffset = ArgOffset;
2676
2677     /* Compute GPR index associated with argument offset.  */
2678     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2679     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2680
2681     // FIXME the codegen can be much improved in some cases.
2682     // We do not have to keep everything in memory.
2683     if (Flags.isByVal()) {
2684       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2685       ObjSize = Flags.getByValSize();
2686       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2687       // Empty aggregate parameters do not take up registers.  Examples:
2688       //   struct { } a;
2689       //   union  { } b;
2690       //   int c[0];
2691       // etc.  However, we have to provide a place-holder in InVals, so
2692       // pretend we have an 8-byte item at the current address for that
2693       // purpose.
2694       if (!ObjSize) {
2695         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2696         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2697         InVals.push_back(FIN);
2698         continue;
2699       }
2700
2701       // Create a stack object covering all stack doublewords occupied
2702       // by the argument.  If the argument is (fully or partially) on
2703       // the stack, or if the argument is fully in registers but the
2704       // caller has allocated the parameter save anyway, we can refer
2705       // directly to the caller's stack frame.  Otherwise, create a
2706       // local copy in our own frame.
2707       int FI;
2708       if (HasParameterArea ||
2709           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2710         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2711       else
2712         FI = MFI->CreateStackObject(ArgSize, Align, false);
2713       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2714
2715       // Handle aggregates smaller than 8 bytes.
2716       if (ObjSize < PtrByteSize) {
2717         // The value of the object is its address, which differs from the
2718         // address of the enclosing doubleword on big-endian systems.
2719         SDValue Arg = FIN;
2720         if (!isLittleEndian) {
2721           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2722           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2723         }
2724         InVals.push_back(Arg);
2725
2726         if (GPR_idx != Num_GPR_Regs) {
2727           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2728           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2729           SDValue Store;
2730
2731           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2732             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2733                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2734             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2735                                       MachinePointerInfo(FuncArg),
2736                                       ObjType, false, false, 0);
2737           } else {
2738             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2739             // store the whole register as-is to the parameter save area
2740             // slot.
2741             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2742                                  MachinePointerInfo(FuncArg),
2743                                  false, false, 0);
2744           }
2745
2746           MemOps.push_back(Store);
2747         }
2748         // Whether we copied from a register or not, advance the offset
2749         // into the parameter save area by a full doubleword.
2750         ArgOffset += PtrByteSize;
2751         continue;
2752       }
2753
2754       // The value of the object is its address, which is the address of
2755       // its first stack doubleword.
2756       InVals.push_back(FIN);
2757
2758       // Store whatever pieces of the object are in registers to memory.
2759       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2760         if (GPR_idx == Num_GPR_Regs)
2761           break;
2762
2763         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2764         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2765         SDValue Addr = FIN;
2766         if (j) {
2767           SDValue Off = DAG.getConstant(j, PtrVT);
2768           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2769         }
2770         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2771                                      MachinePointerInfo(FuncArg, j),
2772                                      false, false, 0);
2773         MemOps.push_back(Store);
2774         ++GPR_idx;
2775       }
2776       ArgOffset += ArgSize;
2777       continue;
2778     }
2779
2780     switch (ObjectVT.getSimpleVT().SimpleTy) {
2781     default: llvm_unreachable("Unhandled argument type!");
2782     case MVT::i1:
2783     case MVT::i32:
2784     case MVT::i64:
2785       // These can be scalar arguments or elements of an integer array type
2786       // passed directly.  Clang may use those instead of "byval" aggregate
2787       // types to avoid forcing arguments to memory unnecessarily.
2788       if (GPR_idx != Num_GPR_Regs) {
2789         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2790         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2791
2792         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2793           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2794           // value to MVT::i64 and then truncate to the correct register size.
2795           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2796       } else {
2797         needsLoad = true;
2798         ArgSize = PtrByteSize;
2799       }
2800       ArgOffset += 8;
2801       break;
2802
2803     case MVT::f32:
2804     case MVT::f64:
2805       // These can be scalar arguments or elements of a float array type
2806       // passed directly.  The latter are used to implement ELFv2 homogenous
2807       // float aggregates.
2808       if (FPR_idx != Num_FPR_Regs) {
2809         unsigned VReg;
2810
2811         if (ObjectVT == MVT::f32)
2812           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2813         else
2814           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2815                                             &PPC::VSFRCRegClass :
2816                                             &PPC::F8RCRegClass);
2817
2818         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2819         ++FPR_idx;
2820       } else if (GPR_idx != Num_GPR_Regs) {
2821         // This can only ever happen in the presence of f32 array types,
2822         // since otherwise we never run out of FPRs before running out
2823         // of GPRs.
2824         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2825         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2826
2827         if (ObjectVT == MVT::f32) {
2828           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2829             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2830                                  DAG.getConstant(32, MVT::i32));
2831           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2832         }
2833
2834         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2835       } else {
2836         needsLoad = true;
2837       }
2838
2839       // When passing an array of floats, the array occupies consecutive
2840       // space in the argument area; only round up to the next doubleword
2841       // at the end of the array.  Otherwise, each float takes 8 bytes.
2842       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2843       ArgOffset += ArgSize;
2844       if (Flags.isInConsecutiveRegsLast())
2845         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2846       break;
2847     case MVT::v4f32:
2848     case MVT::v4i32:
2849     case MVT::v8i16:
2850     case MVT::v16i8:
2851     case MVT::v2f64:
2852     case MVT::v2i64:
2853       // These can be scalar arguments or elements of a vector array type
2854       // passed directly.  The latter are used to implement ELFv2 homogenous
2855       // vector aggregates.
2856       if (VR_idx != Num_VR_Regs) {
2857         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2858                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2859                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2860         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2861         ++VR_idx;
2862       } else {
2863         needsLoad = true;
2864       }
2865       ArgOffset += 16;
2866       break;
2867     }
2868
2869     // We need to load the argument to a virtual register if we determined
2870     // above that we ran out of physical registers of the appropriate type.
2871     if (needsLoad) {
2872       if (ObjSize < ArgSize && !isLittleEndian)
2873         CurArgOffset += ArgSize - ObjSize;
2874       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2875       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2876       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2877                            false, false, false, 0);
2878     }
2879
2880     InVals.push_back(ArgVal);
2881   }
2882
2883   // Area that is at least reserved in the caller of this function.
2884   unsigned MinReservedArea;
2885   if (HasParameterArea)
2886     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2887   else
2888     MinReservedArea = LinkageSize;
2889
2890   // Set the size that is at least reserved in caller of this function.  Tail
2891   // call optimized functions' reserved stack space needs to be aligned so that
2892   // taking the difference between two stack areas will result in an aligned
2893   // stack.
2894   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2895   FuncInfo->setMinReservedArea(MinReservedArea);
2896
2897   // If the function takes variable number of arguments, make a frame index for
2898   // the start of the first vararg value... for expansion of llvm.va_start.
2899   if (isVarArg) {
2900     int Depth = ArgOffset;
2901
2902     FuncInfo->setVarArgsFrameIndex(
2903       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2904     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2905
2906     // If this function is vararg, store any remaining integer argument regs
2907     // to their spots on the stack so that they may be loaded by deferencing the
2908     // result of va_next.
2909     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2910          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2911       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2912       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2913       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2914                                    MachinePointerInfo(), false, false, 0);
2915       MemOps.push_back(Store);
2916       // Increment the address by four for the next argument to store
2917       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2918       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2919     }
2920   }
2921
2922   if (!MemOps.empty())
2923     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2924
2925   return Chain;
2926 }
2927
2928 SDValue
2929 PPCTargetLowering::LowerFormalArguments_Darwin(
2930                                       SDValue Chain,
2931                                       CallingConv::ID CallConv, bool isVarArg,
2932                                       const SmallVectorImpl<ISD::InputArg>
2933                                         &Ins,
2934                                       SDLoc dl, SelectionDAG &DAG,
2935                                       SmallVectorImpl<SDValue> &InVals) const {
2936   // TODO: add description of PPC stack frame format, or at least some docs.
2937   //
2938   MachineFunction &MF = DAG.getMachineFunction();
2939   MachineFrameInfo *MFI = MF.getFrameInfo();
2940   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2941
2942   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2943   bool isPPC64 = PtrVT == MVT::i64;
2944   // Potential tail calls could cause overwriting of argument stack slots.
2945   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2946                        (CallConv == CallingConv::Fast));
2947   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2948
2949   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2950                                                           false);
2951   unsigned ArgOffset = LinkageSize;
2952   // Area that is at least reserved in caller of this function.
2953   unsigned MinReservedArea = ArgOffset;
2954
2955   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2956     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2957     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2958   };
2959   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2960     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2961     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2962   };
2963
2964   static const MCPhysReg *FPR = GetFPR();
2965
2966   static const MCPhysReg VR[] = {
2967     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2968     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2969   };
2970
2971   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2972   const unsigned Num_FPR_Regs = 13;
2973   const unsigned Num_VR_Regs  = array_lengthof( VR);
2974
2975   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2976
2977   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2978
2979   // In 32-bit non-varargs functions, the stack space for vectors is after the
2980   // stack space for non-vectors.  We do not use this space unless we have
2981   // too many vectors to fit in registers, something that only occurs in
2982   // constructed examples:), but we have to walk the arglist to figure
2983   // that out...for the pathological case, compute VecArgOffset as the
2984   // start of the vector parameter area.  Computing VecArgOffset is the
2985   // entire point of the following loop.
2986   unsigned VecArgOffset = ArgOffset;
2987   if (!isVarArg && !isPPC64) {
2988     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2989          ++ArgNo) {
2990       EVT ObjectVT = Ins[ArgNo].VT;
2991       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2992
2993       if (Flags.isByVal()) {
2994         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2995         unsigned ObjSize = Flags.getByValSize();
2996         unsigned ArgSize =
2997                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2998         VecArgOffset += ArgSize;
2999         continue;
3000       }
3001
3002       switch(ObjectVT.getSimpleVT().SimpleTy) {
3003       default: llvm_unreachable("Unhandled argument type!");
3004       case MVT::i1:
3005       case MVT::i32:
3006       case MVT::f32:
3007         VecArgOffset += 4;
3008         break;
3009       case MVT::i64:  // PPC64
3010       case MVT::f64:
3011         // FIXME: We are guaranteed to be !isPPC64 at this point.
3012         // Does MVT::i64 apply?
3013         VecArgOffset += 8;
3014         break;
3015       case MVT::v4f32:
3016       case MVT::v4i32:
3017       case MVT::v8i16:
3018       case MVT::v16i8:
3019         // Nothing to do, we're only looking at Nonvector args here.
3020         break;
3021       }
3022     }
3023   }
3024   // We've found where the vector parameter area in memory is.  Skip the
3025   // first 12 parameters; these don't use that memory.
3026   VecArgOffset = ((VecArgOffset+15)/16)*16;
3027   VecArgOffset += 12*16;
3028
3029   // Add DAG nodes to load the arguments or copy them out of registers.  On
3030   // entry to a function on PPC, the arguments start after the linkage area,
3031   // although the first ones are often in registers.
3032
3033   SmallVector<SDValue, 8> MemOps;
3034   unsigned nAltivecParamsAtEnd = 0;
3035   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3036   unsigned CurArgIdx = 0;
3037   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3038     SDValue ArgVal;
3039     bool needsLoad = false;
3040     EVT ObjectVT = Ins[ArgNo].VT;
3041     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3042     unsigned ArgSize = ObjSize;
3043     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3044     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3045     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3046
3047     unsigned CurArgOffset = ArgOffset;
3048
3049     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3050     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3051         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3052       if (isVarArg || isPPC64) {
3053         MinReservedArea = ((MinReservedArea+15)/16)*16;
3054         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3055                                                   Flags,
3056                                                   PtrByteSize);
3057       } else  nAltivecParamsAtEnd++;
3058     } else
3059       // Calculate min reserved area.
3060       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3061                                                 Flags,
3062                                                 PtrByteSize);
3063
3064     // FIXME the codegen can be much improved in some cases.
3065     // We do not have to keep everything in memory.
3066     if (Flags.isByVal()) {
3067       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3068       ObjSize = Flags.getByValSize();
3069       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3070       // Objects of size 1 and 2 are right justified, everything else is
3071       // left justified.  This means the memory address is adjusted forwards.
3072       if (ObjSize==1 || ObjSize==2) {
3073         CurArgOffset = CurArgOffset + (4 - ObjSize);
3074       }
3075       // The value of the object is its address.
3076       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3077       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3078       InVals.push_back(FIN);
3079       if (ObjSize==1 || ObjSize==2) {
3080         if (GPR_idx != Num_GPR_Regs) {
3081           unsigned VReg;
3082           if (isPPC64)
3083             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3084           else
3085             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3086           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3087           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3088           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3089                                             MachinePointerInfo(FuncArg),
3090                                             ObjType, false, false, 0);
3091           MemOps.push_back(Store);
3092           ++GPR_idx;
3093         }
3094
3095         ArgOffset += PtrByteSize;
3096
3097         continue;
3098       }
3099       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3100         // Store whatever pieces of the object are in registers
3101         // to memory.  ArgOffset will be the address of the beginning
3102         // of the object.
3103         if (GPR_idx != Num_GPR_Regs) {
3104           unsigned VReg;
3105           if (isPPC64)
3106             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3107           else
3108             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3109           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3110           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3111           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3112           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3113                                        MachinePointerInfo(FuncArg, j),
3114                                        false, false, 0);
3115           MemOps.push_back(Store);
3116           ++GPR_idx;
3117           ArgOffset += PtrByteSize;
3118         } else {
3119           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3120           break;
3121         }
3122       }
3123       continue;
3124     }
3125
3126     switch (ObjectVT.getSimpleVT().SimpleTy) {
3127     default: llvm_unreachable("Unhandled argument type!");
3128     case MVT::i1:
3129     case MVT::i32:
3130       if (!isPPC64) {
3131         if (GPR_idx != Num_GPR_Regs) {
3132           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3133           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3134
3135           if (ObjectVT == MVT::i1)
3136             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3137
3138           ++GPR_idx;
3139         } else {
3140           needsLoad = true;
3141           ArgSize = PtrByteSize;
3142         }
3143         // All int arguments reserve stack space in the Darwin ABI.
3144         ArgOffset += PtrByteSize;
3145         break;
3146       }
3147       // FALLTHROUGH
3148     case MVT::i64:  // PPC64
3149       if (GPR_idx != Num_GPR_Regs) {
3150         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3151         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3152
3153         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3154           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3155           // value to MVT::i64 and then truncate to the correct register size.
3156           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3157
3158         ++GPR_idx;
3159       } else {
3160         needsLoad = true;
3161         ArgSize = PtrByteSize;
3162       }
3163       // All int arguments reserve stack space in the Darwin ABI.
3164       ArgOffset += 8;
3165       break;
3166
3167     case MVT::f32:
3168     case MVT::f64:
3169       // Every 4 bytes of argument space consumes one of the GPRs available for
3170       // argument passing.
3171       if (GPR_idx != Num_GPR_Regs) {
3172         ++GPR_idx;
3173         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3174           ++GPR_idx;
3175       }
3176       if (FPR_idx != Num_FPR_Regs) {
3177         unsigned VReg;
3178
3179         if (ObjectVT == MVT::f32)
3180           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3181         else
3182           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3183
3184         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3185         ++FPR_idx;
3186       } else {
3187         needsLoad = true;
3188       }
3189
3190       // All FP arguments reserve stack space in the Darwin ABI.
3191       ArgOffset += isPPC64 ? 8 : ObjSize;
3192       break;
3193     case MVT::v4f32:
3194     case MVT::v4i32:
3195     case MVT::v8i16:
3196     case MVT::v16i8:
3197       // Note that vector arguments in registers don't reserve stack space,
3198       // except in varargs functions.
3199       if (VR_idx != Num_VR_Regs) {
3200         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3201         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3202         if (isVarArg) {
3203           while ((ArgOffset % 16) != 0) {
3204             ArgOffset += PtrByteSize;
3205             if (GPR_idx != Num_GPR_Regs)
3206               GPR_idx++;
3207           }
3208           ArgOffset += 16;
3209           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3210         }
3211         ++VR_idx;
3212       } else {
3213         if (!isVarArg && !isPPC64) {
3214           // Vectors go after all the nonvectors.
3215           CurArgOffset = VecArgOffset;
3216           VecArgOffset += 16;
3217         } else {
3218           // Vectors are aligned.
3219           ArgOffset = ((ArgOffset+15)/16)*16;
3220           CurArgOffset = ArgOffset;
3221           ArgOffset += 16;
3222         }
3223         needsLoad = true;
3224       }
3225       break;
3226     }
3227
3228     // We need to load the argument to a virtual register if we determined above
3229     // that we ran out of physical registers of the appropriate type.
3230     if (needsLoad) {
3231       int FI = MFI->CreateFixedObject(ObjSize,
3232                                       CurArgOffset + (ArgSize - ObjSize),
3233                                       isImmutable);
3234       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3235       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3236                            false, false, false, 0);
3237     }
3238
3239     InVals.push_back(ArgVal);
3240   }
3241
3242   // Allow for Altivec parameters at the end, if needed.
3243   if (nAltivecParamsAtEnd) {
3244     MinReservedArea = ((MinReservedArea+15)/16)*16;
3245     MinReservedArea += 16*nAltivecParamsAtEnd;
3246   }
3247
3248   // Area that is at least reserved in the caller of this function.
3249   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3250
3251   // Set the size that is at least reserved in caller of this function.  Tail
3252   // call optimized functions' reserved stack space needs to be aligned so that
3253   // taking the difference between two stack areas will result in an aligned
3254   // stack.
3255   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3256   FuncInfo->setMinReservedArea(MinReservedArea);
3257
3258   // If the function takes variable number of arguments, make a frame index for
3259   // the start of the first vararg value... for expansion of llvm.va_start.
3260   if (isVarArg) {
3261     int Depth = ArgOffset;
3262
3263     FuncInfo->setVarArgsFrameIndex(
3264       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3265                              Depth, true));
3266     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3267
3268     // If this function is vararg, store any remaining integer argument regs
3269     // to their spots on the stack so that they may be loaded by deferencing the
3270     // result of va_next.
3271     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3272       unsigned VReg;
3273
3274       if (isPPC64)
3275         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3276       else
3277         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3278
3279       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3280       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3281                                    MachinePointerInfo(), false, false, 0);
3282       MemOps.push_back(Store);
3283       // Increment the address by four for the next argument to store
3284       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3285       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3286     }
3287   }
3288
3289   if (!MemOps.empty())
3290     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3291
3292   return Chain;
3293 }
3294
3295 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3296 /// adjusted to accommodate the arguments for the tailcall.
3297 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3298                                    unsigned ParamSize) {
3299
3300   if (!isTailCall) return 0;
3301
3302   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3303   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3304   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3305   // Remember only if the new adjustement is bigger.
3306   if (SPDiff < FI->getTailCallSPDelta())
3307     FI->setTailCallSPDelta(SPDiff);
3308
3309   return SPDiff;
3310 }
3311
3312 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3313 /// for tail call optimization. Targets which want to do tail call
3314 /// optimization should implement this function.
3315 bool
3316 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3317                                                      CallingConv::ID CalleeCC,
3318                                                      bool isVarArg,
3319                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3320                                                      SelectionDAG& DAG) const {
3321   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3322     return false;
3323
3324   // Variable argument functions are not supported.
3325   if (isVarArg)
3326     return false;
3327
3328   MachineFunction &MF = DAG.getMachineFunction();
3329   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3330   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3331     // Functions containing by val parameters are not supported.
3332     for (unsigned i = 0; i != Ins.size(); i++) {
3333        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3334        if (Flags.isByVal()) return false;
3335     }
3336
3337     // Non-PIC/GOT tail calls are supported.
3338     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3339       return true;
3340
3341     // At the moment we can only do local tail calls (in same module, hidden
3342     // or protected) if we are generating PIC.
3343     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3344       return G->getGlobal()->hasHiddenVisibility()
3345           || G->getGlobal()->hasProtectedVisibility();
3346   }
3347
3348   return false;
3349 }
3350
3351 /// isCallCompatibleAddress - Return the immediate to use if the specified
3352 /// 32-bit value is representable in the immediate field of a BxA instruction.
3353 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3354   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3355   if (!C) return nullptr;
3356
3357   int Addr = C->getZExtValue();
3358   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3359       SignExtend32<26>(Addr) != Addr)
3360     return nullptr;  // Top 6 bits have to be sext of immediate.
3361
3362   return DAG.getConstant((int)C->getZExtValue() >> 2,
3363                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3364 }
3365
3366 namespace {
3367
3368 struct TailCallArgumentInfo {
3369   SDValue Arg;
3370   SDValue FrameIdxOp;
3371   int       FrameIdx;
3372
3373   TailCallArgumentInfo() : FrameIdx(0) {}
3374 };
3375
3376 }
3377
3378 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3379 static void
3380 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3381                                            SDValue Chain,
3382                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3383                    SmallVectorImpl<SDValue> &MemOpChains,
3384                    SDLoc dl) {
3385   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3386     SDValue Arg = TailCallArgs[i].Arg;
3387     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3388     int FI = TailCallArgs[i].FrameIdx;
3389     // Store relative to framepointer.
3390     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3391                                        MachinePointerInfo::getFixedStack(FI),
3392                                        false, false, 0));
3393   }
3394 }
3395
3396 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3397 /// the appropriate stack slot for the tail call optimized function call.
3398 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3399                                                MachineFunction &MF,
3400                                                SDValue Chain,
3401                                                SDValue OldRetAddr,
3402                                                SDValue OldFP,
3403                                                int SPDiff,
3404                                                bool isPPC64,
3405                                                bool isDarwinABI,
3406                                                SDLoc dl) {
3407   if (SPDiff) {
3408     // Calculate the new stack slot for the return address.
3409     int SlotSize = isPPC64 ? 8 : 4;
3410     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3411                                                                    isDarwinABI);
3412     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3413                                                           NewRetAddrLoc, true);
3414     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3415     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3416     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3417                          MachinePointerInfo::getFixedStack(NewRetAddr),
3418                          false, false, 0);
3419
3420     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3421     // slot as the FP is never overwritten.
3422     if (isDarwinABI) {
3423       int NewFPLoc =
3424         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3425       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3426                                                           true);
3427       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3428       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3429                            MachinePointerInfo::getFixedStack(NewFPIdx),
3430                            false, false, 0);
3431     }
3432   }
3433   return Chain;
3434 }
3435
3436 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3437 /// the position of the argument.
3438 static void
3439 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3440                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3441                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3442   int Offset = ArgOffset + SPDiff;
3443   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3444   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3445   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3446   SDValue FIN = DAG.getFrameIndex(FI, VT);
3447   TailCallArgumentInfo Info;
3448   Info.Arg = Arg;
3449   Info.FrameIdxOp = FIN;
3450   Info.FrameIdx = FI;
3451   TailCallArguments.push_back(Info);
3452 }
3453
3454 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3455 /// stack slot. Returns the chain as result and the loaded frame pointers in
3456 /// LROpOut/FPOpout. Used when tail calling.
3457 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3458                                                         int SPDiff,
3459                                                         SDValue Chain,
3460                                                         SDValue &LROpOut,
3461                                                         SDValue &FPOpOut,
3462                                                         bool isDarwinABI,
3463                                                         SDLoc dl) const {
3464   if (SPDiff) {
3465     // Load the LR and FP stack slot for later adjusting.
3466     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3467     LROpOut = getReturnAddrFrameIndex(DAG);
3468     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3469                           false, false, false, 0);
3470     Chain = SDValue(LROpOut.getNode(), 1);
3471
3472     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3473     // slot as the FP is never overwritten.
3474     if (isDarwinABI) {
3475       FPOpOut = getFramePointerFrameIndex(DAG);
3476       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3477                             false, false, false, 0);
3478       Chain = SDValue(FPOpOut.getNode(), 1);
3479     }
3480   }
3481   return Chain;
3482 }
3483
3484 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3485 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3486 /// specified by the specific parameter attribute. The copy will be passed as
3487 /// a byval function parameter.
3488 /// Sometimes what we are copying is the end of a larger object, the part that
3489 /// does not fit in registers.
3490 static SDValue
3491 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3492                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3493                           SDLoc dl) {
3494   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3495   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3496                        false, false, MachinePointerInfo(),
3497                        MachinePointerInfo());
3498 }
3499
3500 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3501 /// tail calls.
3502 static void
3503 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3504                  SDValue Arg, SDValue PtrOff, int SPDiff,
3505                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3506                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3507                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3508                  SDLoc dl) {
3509   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3510   if (!isTailCall) {
3511     if (isVector) {
3512       SDValue StackPtr;
3513       if (isPPC64)
3514         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3515       else
3516         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3517       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3518                            DAG.getConstant(ArgOffset, PtrVT));
3519     }
3520     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3521                                        MachinePointerInfo(), false, false, 0));
3522   // Calculate and remember argument location.
3523   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3524                                   TailCallArguments);
3525 }
3526
3527 static
3528 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3529                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3530                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3531                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3532   MachineFunction &MF = DAG.getMachineFunction();
3533
3534   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3535   // might overwrite each other in case of tail call optimization.
3536   SmallVector<SDValue, 8> MemOpChains2;
3537   // Do not flag preceding copytoreg stuff together with the following stuff.
3538   InFlag = SDValue();
3539   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3540                                     MemOpChains2, dl);
3541   if (!MemOpChains2.empty())
3542     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3543
3544   // Store the return address to the appropriate stack slot.
3545   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3546                                         isPPC64, isDarwinABI, dl);
3547
3548   // Emit callseq_end just before tailcall node.
3549   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3550                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3551   InFlag = Chain.getValue(1);
3552 }
3553
3554 static
3555 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3556                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3557                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3558                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3559                      const PPCSubtarget &Subtarget) {
3560
3561   bool isPPC64 = Subtarget.isPPC64();
3562   bool isSVR4ABI = Subtarget.isSVR4ABI();
3563   bool isELFv2ABI = Subtarget.isELFv2ABI();
3564
3565   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3566   NodeTys.push_back(MVT::Other);   // Returns a chain
3567   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3568
3569   unsigned CallOpc = PPCISD::CALL;
3570
3571   bool needIndirectCall = true;
3572   if (!isSVR4ABI || !isPPC64)
3573     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3574       // If this is an absolute destination address, use the munged value.
3575       Callee = SDValue(Dest, 0);
3576       needIndirectCall = false;
3577     }
3578
3579   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3580     unsigned OpFlags = 0;
3581     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3582          (Subtarget.getTargetTriple().isMacOSX() &&
3583           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3584          (G->getGlobal()->isDeclaration() ||
3585           G->getGlobal()->isWeakForLinker())) ||
3586         (Subtarget.isTargetELF() && !isPPC64 &&
3587          !G->getGlobal()->hasLocalLinkage() &&
3588          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3589       // PC-relative references to external symbols should go through $stub,
3590       // unless we're building with the leopard linker or later, which
3591       // automatically synthesizes these stubs.
3592       OpFlags = PPCII::MO_PLT_OR_STUB;
3593     }
3594
3595     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3596     // every direct call is) turn it into a TargetGlobalAddress /
3597     // TargetExternalSymbol node so that legalize doesn't hack it.
3598     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3599                                         Callee.getValueType(), 0, OpFlags);
3600     needIndirectCall = false;
3601   }
3602
3603   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3604     unsigned char OpFlags = 0;
3605
3606     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3607          (Subtarget.getTargetTriple().isMacOSX() &&
3608           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3609         (Subtarget.isTargetELF() && !isPPC64 &&
3610          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3611       // PC-relative references to external symbols should go through $stub,
3612       // unless we're building with the leopard linker or later, which
3613       // automatically synthesizes these stubs.
3614       OpFlags = PPCII::MO_PLT_OR_STUB;
3615     }
3616
3617     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3618                                          OpFlags);
3619     needIndirectCall = false;
3620   }
3621
3622   if (needIndirectCall) {
3623     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3624     // to do the call, we can't use PPCISD::CALL.
3625     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3626
3627     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3628       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3629       // entry point, but to the function descriptor (the function entry point
3630       // address is part of the function descriptor though).
3631       // The function descriptor is a three doubleword structure with the
3632       // following fields: function entry point, TOC base address and
3633       // environment pointer.
3634       // Thus for a call through a function pointer, the following actions need
3635       // to be performed:
3636       //   1. Save the TOC of the caller in the TOC save area of its stack
3637       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3638       //   2. Load the address of the function entry point from the function
3639       //      descriptor.
3640       //   3. Load the TOC of the callee from the function descriptor into r2.
3641       //   4. Load the environment pointer from the function descriptor into
3642       //      r11.
3643       //   5. Branch to the function entry point address.
3644       //   6. On return of the callee, the TOC of the caller needs to be
3645       //      restored (this is done in FinishCall()).
3646       //
3647       // All those operations are flagged together to ensure that no other
3648       // operations can be scheduled in between. E.g. without flagging the
3649       // operations together, a TOC access in the caller could be scheduled
3650       // between the load of the callee TOC and the branch to the callee, which
3651       // results in the TOC access going through the TOC of the callee instead
3652       // of going through the TOC of the caller, which leads to incorrect code.
3653
3654       // Load the address of the function entry point from the function
3655       // descriptor.
3656       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3657       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3658                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3659       Chain = LoadFuncPtr.getValue(1);
3660       InFlag = LoadFuncPtr.getValue(2);
3661
3662       // Load environment pointer into r11.
3663       // Offset of the environment pointer within the function descriptor.
3664       SDValue PtrOff = DAG.getIntPtrConstant(16);
3665
3666       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3667       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3668                                        InFlag);
3669       Chain = LoadEnvPtr.getValue(1);
3670       InFlag = LoadEnvPtr.getValue(2);
3671
3672       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3673                                         InFlag);
3674       Chain = EnvVal.getValue(0);
3675       InFlag = EnvVal.getValue(1);
3676
3677       // Load TOC of the callee into r2. We are using a target-specific load
3678       // with r2 hard coded, because the result of a target-independent load
3679       // would never go directly into r2, since r2 is a reserved register (which
3680       // prevents the register allocator from allocating it), resulting in an
3681       // additional register being allocated and an unnecessary move instruction
3682       // being generated.
3683       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3684       SDValue TOCOff = DAG.getIntPtrConstant(8);
3685       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3686       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3687                                        AddTOC, InFlag);
3688       Chain = LoadTOCPtr.getValue(0);
3689       InFlag = LoadTOCPtr.getValue(1);
3690
3691       MTCTROps[0] = Chain;
3692       MTCTROps[1] = LoadFuncPtr;
3693       MTCTROps[2] = InFlag;
3694     }
3695
3696     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3697                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3698     InFlag = Chain.getValue(1);
3699
3700     NodeTys.clear();
3701     NodeTys.push_back(MVT::Other);
3702     NodeTys.push_back(MVT::Glue);
3703     Ops.push_back(Chain);
3704     CallOpc = PPCISD::BCTRL;
3705     Callee.setNode(nullptr);
3706     // Add use of X11 (holding environment pointer)
3707     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3708       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3709     // Add CTR register as callee so a bctr can be emitted later.
3710     if (isTailCall)
3711       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3712   }
3713
3714   // If this is a direct call, pass the chain and the callee.
3715   if (Callee.getNode()) {
3716     Ops.push_back(Chain);
3717     Ops.push_back(Callee);
3718
3719     // If this is a call to __tls_get_addr, find the symbol whose address
3720     // is to be taken and add it to the list.  This will be used to 
3721     // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3722     // We find the symbol by walking the chain to the CopyFromReg, walking
3723     // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3724     // pulling the symbol from that node.
3725     if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3726       if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3727         assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3728         SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3729         SDValue TGTAddr = AddI->getOperand(1);
3730         assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3731                "Didn't find target global TLS address where we expected one");
3732         Ops.push_back(TGTAddr);
3733         CallOpc = PPCISD::CALL_TLS;
3734       }
3735   }
3736   // If this is a tail call add stack pointer delta.
3737   if (isTailCall)
3738     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3739
3740   // Add argument registers to the end of the list so that they are known live
3741   // into the call.
3742   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3743     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3744                                   RegsToPass[i].second.getValueType()));
3745
3746   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3747   if (Callee.getNode() && isELFv2ABI)
3748     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3749
3750   return CallOpc;
3751 }
3752
3753 static
3754 bool isLocalCall(const SDValue &Callee)
3755 {
3756   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3757     return !G->getGlobal()->isDeclaration() &&
3758            !G->getGlobal()->isWeakForLinker();
3759   return false;
3760 }
3761
3762 SDValue
3763 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3764                                    CallingConv::ID CallConv, bool isVarArg,
3765                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3766                                    SDLoc dl, SelectionDAG &DAG,
3767                                    SmallVectorImpl<SDValue> &InVals) const {
3768
3769   SmallVector<CCValAssign, 16> RVLocs;
3770   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3771                     *DAG.getContext());
3772   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3773
3774   // Copy all of the result registers out of their specified physreg.
3775   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3776     CCValAssign &VA = RVLocs[i];
3777     assert(VA.isRegLoc() && "Can only return in registers!");
3778
3779     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3780                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3781     Chain = Val.getValue(1);
3782     InFlag = Val.getValue(2);
3783
3784     switch (VA.getLocInfo()) {
3785     default: llvm_unreachable("Unknown loc info!");
3786     case CCValAssign::Full: break;
3787     case CCValAssign::AExt:
3788       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3789       break;
3790     case CCValAssign::ZExt:
3791       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3792                         DAG.getValueType(VA.getValVT()));
3793       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3794       break;
3795     case CCValAssign::SExt:
3796       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3797                         DAG.getValueType(VA.getValVT()));
3798       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3799       break;
3800     }
3801
3802     InVals.push_back(Val);
3803   }
3804
3805   return Chain;
3806 }
3807
3808 SDValue
3809 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3810                               bool isTailCall, bool isVarArg,
3811                               SelectionDAG &DAG,
3812                               SmallVector<std::pair<unsigned, SDValue>, 8>
3813                                 &RegsToPass,
3814                               SDValue InFlag, SDValue Chain,
3815                               SDValue &Callee,
3816                               int SPDiff, unsigned NumBytes,
3817                               const SmallVectorImpl<ISD::InputArg> &Ins,
3818                               SmallVectorImpl<SDValue> &InVals) const {
3819
3820   bool isELFv2ABI = Subtarget.isELFv2ABI();
3821   std::vector<EVT> NodeTys;
3822   SmallVector<SDValue, 8> Ops;
3823   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3824                                  isTailCall, RegsToPass, Ops, NodeTys,
3825                                  Subtarget);
3826
3827   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3828   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3829     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3830
3831   // When performing tail call optimization the callee pops its arguments off
3832   // the stack. Account for this here so these bytes can be pushed back on in
3833   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3834   int BytesCalleePops =
3835     (CallConv == CallingConv::Fast &&
3836      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3837
3838   // Add a register mask operand representing the call-preserved registers.
3839   const TargetRegisterInfo *TRI =
3840       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3841   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3842   assert(Mask && "Missing call preserved mask for calling convention");
3843   Ops.push_back(DAG.getRegisterMask(Mask));
3844
3845   if (InFlag.getNode())
3846     Ops.push_back(InFlag);
3847
3848   // Emit tail call.
3849   if (isTailCall) {
3850     assert(((Callee.getOpcode() == ISD::Register &&
3851              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3852             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3853             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3854             isa<ConstantSDNode>(Callee)) &&
3855     "Expecting an global address, external symbol, absolute value or register");
3856
3857     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3858   }
3859
3860   // Add a NOP immediately after the branch instruction when using the 64-bit
3861   // SVR4 ABI. At link time, if caller and callee are in a different module and
3862   // thus have a different TOC, the call will be replaced with a call to a stub
3863   // function which saves the current TOC, loads the TOC of the callee and
3864   // branches to the callee. The NOP will be replaced with a load instruction
3865   // which restores the TOC of the caller from the TOC save slot of the current
3866   // stack frame. If caller and callee belong to the same module (and have the
3867   // same TOC), the NOP will remain unchanged.
3868
3869   bool needsTOCRestore = false;
3870   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3871     if (CallOpc == PPCISD::BCTRL) {
3872       // This is a call through a function pointer.
3873       // Restore the caller TOC from the save area into R2.
3874       // See PrepareCall() for more information about calls through function
3875       // pointers in the 64-bit SVR4 ABI.
3876       // We are using a target-specific load with r2 hard coded, because the
3877       // result of a target-independent load would never go directly into r2,
3878       // since r2 is a reserved register (which prevents the register allocator
3879       // from allocating it), resulting in an additional register being
3880       // allocated and an unnecessary move instruction being generated.
3881       needsTOCRestore = true;
3882     } else if ((CallOpc == PPCISD::CALL) &&
3883                (!isLocalCall(Callee) ||
3884                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3885       // Otherwise insert NOP for non-local calls.
3886       CallOpc = PPCISD::CALL_NOP;
3887     } else if (CallOpc == PPCISD::CALL_TLS)
3888       // For 64-bit SVR4, TLS calls are always non-local.
3889       CallOpc = PPCISD::CALL_NOP_TLS;
3890   }
3891
3892   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3893   InFlag = Chain.getValue(1);
3894
3895   if (needsTOCRestore) {
3896     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3897     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3898     SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3899     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3900     SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3901     SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3902     Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3903     InFlag = Chain.getValue(1);
3904   }
3905
3906   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3907                              DAG.getIntPtrConstant(BytesCalleePops, true),
3908                              InFlag, dl);
3909   if (!Ins.empty())
3910     InFlag = Chain.getValue(1);
3911
3912   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3913                          Ins, dl, DAG, InVals);
3914 }
3915
3916 SDValue
3917 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3918                              SmallVectorImpl<SDValue> &InVals) const {
3919   SelectionDAG &DAG                     = CLI.DAG;
3920   SDLoc &dl                             = CLI.DL;
3921   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3922   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3923   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3924   SDValue Chain                         = CLI.Chain;
3925   SDValue Callee                        = CLI.Callee;
3926   bool &isTailCall                      = CLI.IsTailCall;
3927   CallingConv::ID CallConv              = CLI.CallConv;
3928   bool isVarArg                         = CLI.IsVarArg;
3929
3930   if (isTailCall)
3931     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3932                                                    Ins, DAG);
3933
3934   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3935     report_fatal_error("failed to perform tail call elimination on a call "
3936                        "site marked musttail");
3937
3938   if (Subtarget.isSVR4ABI()) {
3939     if (Subtarget.isPPC64())
3940       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3941                               isTailCall, Outs, OutVals, Ins,
3942                               dl, DAG, InVals);
3943     else
3944       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3945                               isTailCall, Outs, OutVals, Ins,
3946                               dl, DAG, InVals);
3947   }
3948
3949   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3950                           isTailCall, Outs, OutVals, Ins,
3951                           dl, DAG, InVals);
3952 }
3953
3954 SDValue
3955 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3956                                     CallingConv::ID CallConv, bool isVarArg,
3957                                     bool isTailCall,
3958                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3959                                     const SmallVectorImpl<SDValue> &OutVals,
3960                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3961                                     SDLoc dl, SelectionDAG &DAG,
3962                                     SmallVectorImpl<SDValue> &InVals) const {
3963   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3964   // of the 32-bit SVR4 ABI stack frame layout.
3965
3966   assert((CallConv == CallingConv::C ||
3967           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3968
3969   unsigned PtrByteSize = 4;
3970
3971   MachineFunction &MF = DAG.getMachineFunction();
3972
3973   // Mark this function as potentially containing a function that contains a
3974   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3975   // and restoring the callers stack pointer in this functions epilog. This is
3976   // done because by tail calling the called function might overwrite the value
3977   // in this function's (MF) stack pointer stack slot 0(SP).
3978   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3979       CallConv == CallingConv::Fast)
3980     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3981
3982   // Count how many bytes are to be pushed on the stack, including the linkage
3983   // area, parameter list area and the part of the local variable space which
3984   // contains copies of aggregates which are passed by value.
3985
3986   // Assign locations to all of the outgoing arguments.
3987   SmallVector<CCValAssign, 16> ArgLocs;
3988   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3989                  *DAG.getContext());
3990
3991   // Reserve space for the linkage area on the stack.
3992   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3993                        PtrByteSize);
3994
3995   if (isVarArg) {
3996     // Handle fixed and variable vector arguments differently.
3997     // Fixed vector arguments go into registers as long as registers are
3998     // available. Variable vector arguments always go into memory.
3999     unsigned NumArgs = Outs.size();
4000
4001     for (unsigned i = 0; i != NumArgs; ++i) {
4002       MVT ArgVT = Outs[i].VT;
4003       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4004       bool Result;
4005
4006       if (Outs[i].IsFixed) {
4007         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4008                                CCInfo);
4009       } else {
4010         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4011                                       ArgFlags, CCInfo);
4012       }
4013
4014       if (Result) {
4015 #ifndef NDEBUG
4016         errs() << "Call operand #" << i << " has unhandled type "
4017              << EVT(ArgVT).getEVTString() << "\n";
4018 #endif
4019         llvm_unreachable(nullptr);
4020       }
4021     }
4022   } else {
4023     // All arguments are treated the same.
4024     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4025   }
4026
4027   // Assign locations to all of the outgoing aggregate by value arguments.
4028   SmallVector<CCValAssign, 16> ByValArgLocs;
4029   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4030                       ByValArgLocs, *DAG.getContext());
4031
4032   // Reserve stack space for the allocations in CCInfo.
4033   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4034
4035   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4036
4037   // Size of the linkage area, parameter list area and the part of the local
4038   // space variable where copies of aggregates which are passed by value are
4039   // stored.
4040   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4041
4042   // Calculate by how many bytes the stack has to be adjusted in case of tail
4043   // call optimization.
4044   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4045
4046   // Adjust the stack pointer for the new arguments...
4047   // These operations are automatically eliminated by the prolog/epilog pass
4048   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4049                                dl);
4050   SDValue CallSeqStart = Chain;
4051
4052   // Load the return address and frame pointer so it can be moved somewhere else
4053   // later.
4054   SDValue LROp, FPOp;
4055   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4056                                        dl);
4057
4058   // Set up a copy of the stack pointer for use loading and storing any
4059   // arguments that may not fit in the registers available for argument
4060   // passing.
4061   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4062
4063   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4064   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4065   SmallVector<SDValue, 8> MemOpChains;
4066
4067   bool seenFloatArg = false;
4068   // Walk the register/memloc assignments, inserting copies/loads.
4069   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4070        i != e;
4071        ++i) {
4072     CCValAssign &VA = ArgLocs[i];
4073     SDValue Arg = OutVals[i];
4074     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4075
4076     if (Flags.isByVal()) {
4077       // Argument is an aggregate which is passed by value, thus we need to
4078       // create a copy of it in the local variable space of the current stack
4079       // frame (which is the stack frame of the caller) and pass the address of
4080       // this copy to the callee.
4081       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4082       CCValAssign &ByValVA = ByValArgLocs[j++];
4083       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4084
4085       // Memory reserved in the local variable space of the callers stack frame.
4086       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4087
4088       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4089       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4090
4091       // Create a copy of the argument in the local area of the current
4092       // stack frame.
4093       SDValue MemcpyCall =
4094         CreateCopyOfByValArgument(Arg, PtrOff,
4095                                   CallSeqStart.getNode()->getOperand(0),
4096                                   Flags, DAG, dl);
4097
4098       // This must go outside the CALLSEQ_START..END.
4099       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4100                            CallSeqStart.getNode()->getOperand(1),
4101                            SDLoc(MemcpyCall));
4102       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4103                              NewCallSeqStart.getNode());
4104       Chain = CallSeqStart = NewCallSeqStart;
4105
4106       // Pass the address of the aggregate copy on the stack either in a
4107       // physical register or in the parameter list area of the current stack
4108       // frame to the callee.
4109       Arg = PtrOff;
4110     }
4111
4112     if (VA.isRegLoc()) {
4113       if (Arg.getValueType() == MVT::i1)
4114         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4115
4116       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4117       // Put argument in a physical register.
4118       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4119     } else {
4120       // Put argument in the parameter list area of the current stack frame.
4121       assert(VA.isMemLoc());
4122       unsigned LocMemOffset = VA.getLocMemOffset();
4123
4124       if (!isTailCall) {
4125         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4126         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4127
4128         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4129                                            MachinePointerInfo(),
4130                                            false, false, 0));
4131       } else {
4132         // Calculate and remember argument location.
4133         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4134                                  TailCallArguments);
4135       }
4136     }
4137   }
4138
4139   if (!MemOpChains.empty())
4140     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4141
4142   // Build a sequence of copy-to-reg nodes chained together with token chain
4143   // and flag operands which copy the outgoing args into the appropriate regs.
4144   SDValue InFlag;
4145   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4146     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4147                              RegsToPass[i].second, InFlag);
4148     InFlag = Chain.getValue(1);
4149   }
4150
4151   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4152   // registers.
4153   if (isVarArg) {
4154     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4155     SDValue Ops[] = { Chain, InFlag };
4156
4157     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4158                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4159
4160     InFlag = Chain.getValue(1);
4161   }
4162
4163   if (isTailCall)
4164     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4165                     false, TailCallArguments);
4166
4167   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4168                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4169                     Ins, InVals);
4170 }
4171
4172 // Copy an argument into memory, being careful to do this outside the
4173 // call sequence for the call to which the argument belongs.
4174 SDValue
4175 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4176                                               SDValue CallSeqStart,
4177                                               ISD::ArgFlagsTy Flags,
4178                                               SelectionDAG &DAG,
4179                                               SDLoc dl) const {
4180   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4181                         CallSeqStart.getNode()->getOperand(0),
4182                         Flags, DAG, dl);
4183   // The MEMCPY must go outside the CALLSEQ_START..END.
4184   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4185                              CallSeqStart.getNode()->getOperand(1),
4186                              SDLoc(MemcpyCall));
4187   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4188                          NewCallSeqStart.getNode());
4189   return NewCallSeqStart;
4190 }
4191
4192 SDValue
4193 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4194                                     CallingConv::ID CallConv, bool isVarArg,
4195                                     bool isTailCall,
4196                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4197                                     const SmallVectorImpl<SDValue> &OutVals,
4198                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4199                                     SDLoc dl, SelectionDAG &DAG,
4200                                     SmallVectorImpl<SDValue> &InVals) const {
4201
4202   bool isELFv2ABI = Subtarget.isELFv2ABI();
4203   bool isLittleEndian = Subtarget.isLittleEndian();
4204   unsigned NumOps = Outs.size();
4205
4206   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4207   unsigned PtrByteSize = 8;
4208
4209   MachineFunction &MF = DAG.getMachineFunction();
4210
4211   // Mark this function as potentially containing a function that contains a
4212   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4213   // and restoring the callers stack pointer in this functions epilog. This is
4214   // done because by tail calling the called function might overwrite the value
4215   // in this function's (MF) stack pointer stack slot 0(SP).
4216   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4217       CallConv == CallingConv::Fast)
4218     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4219
4220   // Count how many bytes are to be pushed on the stack, including the linkage
4221   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4222   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4223   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4224   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4225                                                           isELFv2ABI);
4226   unsigned NumBytes = LinkageSize;
4227
4228   // Add up all the space actually used.
4229   for (unsigned i = 0; i != NumOps; ++i) {
4230     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4231     EVT ArgVT = Outs[i].VT;
4232     EVT OrigVT = Outs[i].ArgVT;
4233
4234     /* Respect alignment of argument on the stack.  */
4235     unsigned Align =
4236       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4237     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4238
4239     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4240     if (Flags.isInConsecutiveRegsLast())
4241       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4242   }
4243
4244   unsigned NumBytesActuallyUsed = NumBytes;
4245
4246   // The prolog code of the callee may store up to 8 GPR argument registers to
4247   // the stack, allowing va_start to index over them in memory if its varargs.
4248   // Because we cannot tell if this is needed on the caller side, we have to
4249   // conservatively assume that it is needed.  As such, make sure we have at
4250   // least enough stack space for the caller to store the 8 GPRs.
4251   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4252   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4253
4254   // Tail call needs the stack to be aligned.
4255   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4256       CallConv == CallingConv::Fast)
4257     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4258
4259   // Calculate by how many bytes the stack has to be adjusted in case of tail
4260   // call optimization.
4261   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4262
4263   // To protect arguments on the stack from being clobbered in a tail call,
4264   // force all the loads to happen before doing any other lowering.
4265   if (isTailCall)
4266     Chain = DAG.getStackArgumentTokenFactor(Chain);
4267
4268   // Adjust the stack pointer for the new arguments...
4269   // These operations are automatically eliminated by the prolog/epilog pass
4270   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4271                                dl);
4272   SDValue CallSeqStart = Chain;
4273
4274   // Load the return address and frame pointer so it can be move somewhere else
4275   // later.
4276   SDValue LROp, FPOp;
4277   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4278                                        dl);
4279
4280   // Set up a copy of the stack pointer for use loading and storing any
4281   // arguments that may not fit in the registers available for argument
4282   // passing.
4283   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4284
4285   // Figure out which arguments are going to go in registers, and which in
4286   // memory.  Also, if this is a vararg function, floating point operations
4287   // must be stored to our stack, and loaded into integer regs as well, if
4288   // any integer regs are available for argument passing.
4289   unsigned ArgOffset = LinkageSize;
4290   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4291
4292   static const MCPhysReg GPR[] = {
4293     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4294     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4295   };
4296   static const MCPhysReg *FPR = GetFPR();
4297
4298   static const MCPhysReg VR[] = {
4299     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4300     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4301   };
4302   static const MCPhysReg VSRH[] = {
4303     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4304     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4305   };
4306
4307   const unsigned NumGPRs = array_lengthof(GPR);
4308   const unsigned NumFPRs = 13;
4309   const unsigned NumVRs  = array_lengthof(VR);
4310
4311   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4312   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4313
4314   SmallVector<SDValue, 8> MemOpChains;
4315   for (unsigned i = 0; i != NumOps; ++i) {
4316     SDValue Arg = OutVals[i];
4317     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4318     EVT ArgVT = Outs[i].VT;
4319     EVT OrigVT = Outs[i].ArgVT;
4320
4321     /* Respect alignment of argument on the stack.  */
4322     unsigned Align =
4323       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4324     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4325
4326     /* Compute GPR index associated with argument offset.  */
4327     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4328     GPR_idx = std::min(GPR_idx, NumGPRs);
4329
4330     // PtrOff will be used to store the current argument to the stack if a
4331     // register cannot be found for it.
4332     SDValue PtrOff;
4333
4334     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4335
4336     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4337
4338     // Promote integers to 64-bit values.
4339     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4340       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4341       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4342       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4343     }
4344
4345     // FIXME memcpy is used way more than necessary.  Correctness first.
4346     // Note: "by value" is code for passing a structure by value, not
4347     // basic types.
4348     if (Flags.isByVal()) {
4349       // Note: Size includes alignment padding, so
4350       //   struct x { short a; char b; }
4351       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4352       // These are the proper values we need for right-justifying the
4353       // aggregate in a parameter register.
4354       unsigned Size = Flags.getByValSize();
4355
4356       // An empty aggregate parameter takes up no storage and no
4357       // registers.
4358       if (Size == 0)
4359         continue;
4360
4361       // All aggregates smaller than 8 bytes must be passed right-justified.
4362       if (Size==1 || Size==2 || Size==4) {
4363         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4364         if (GPR_idx != NumGPRs) {
4365           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4366                                         MachinePointerInfo(), VT,
4367                                         false, false, false, 0);
4368           MemOpChains.push_back(Load.getValue(1));
4369           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4370
4371           ArgOffset += PtrByteSize;
4372           continue;
4373         }
4374       }
4375
4376       if (GPR_idx == NumGPRs && Size < 8) {
4377         SDValue AddPtr = PtrOff;
4378         if (!isLittleEndian) {
4379           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4380                                           PtrOff.getValueType());
4381           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4382         }
4383         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4384                                                           CallSeqStart,
4385                                                           Flags, DAG, dl);
4386         ArgOffset += PtrByteSize;
4387         continue;
4388       }
4389       // Copy entire object into memory.  There are cases where gcc-generated
4390       // code assumes it is there, even if it could be put entirely into
4391       // registers.  (This is not what the doc says.)
4392
4393       // FIXME: The above statement is likely due to a misunderstanding of the
4394       // documents.  All arguments must be copied into the parameter area BY
4395       // THE CALLEE in the event that the callee takes the address of any
4396       // formal argument.  That has not yet been implemented.  However, it is
4397       // reasonable to use the stack area as a staging area for the register
4398       // load.
4399
4400       // Skip this for small aggregates, as we will use the same slot for a
4401       // right-justified copy, below.
4402       if (Size >= 8)
4403         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4404                                                           CallSeqStart,
4405                                                           Flags, DAG, dl);
4406
4407       // When a register is available, pass a small aggregate right-justified.
4408       if (Size < 8 && GPR_idx != NumGPRs) {
4409         // The easiest way to get this right-justified in a register
4410         // is to copy the structure into the rightmost portion of a
4411         // local variable slot, then load the whole slot into the
4412         // register.
4413         // FIXME: The memcpy seems to produce pretty awful code for
4414         // small aggregates, particularly for packed ones.
4415         // FIXME: It would be preferable to use the slot in the
4416         // parameter save area instead of a new local variable.
4417         SDValue AddPtr = PtrOff;
4418         if (!isLittleEndian) {
4419           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4420           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4421         }
4422         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4423                                                           CallSeqStart,
4424                                                           Flags, DAG, dl);
4425
4426         // Load the slot into the register.
4427         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4428                                    MachinePointerInfo(),
4429                                    false, false, false, 0);
4430         MemOpChains.push_back(Load.getValue(1));
4431         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4432
4433         // Done with this argument.
4434         ArgOffset += PtrByteSize;
4435         continue;
4436       }
4437
4438       // For aggregates larger than PtrByteSize, copy the pieces of the
4439       // object that fit into registers from the parameter save area.
4440       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4441         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4442         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4443         if (GPR_idx != NumGPRs) {
4444           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4445                                      MachinePointerInfo(),
4446                                      false, false, false, 0);
4447           MemOpChains.push_back(Load.getValue(1));
4448           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4449           ArgOffset += PtrByteSize;
4450         } else {
4451           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4452           break;
4453         }
4454       }
4455       continue;
4456     }
4457
4458     switch (Arg.getSimpleValueType().SimpleTy) {
4459     default: llvm_unreachable("Unexpected ValueType for argument!");
4460     case MVT::i1:
4461     case MVT::i32:
4462     case MVT::i64:
4463       // These can be scalar arguments or elements of an integer array type
4464       // passed directly.  Clang may use those instead of "byval" aggregate
4465       // types to avoid forcing arguments to memory unnecessarily.
4466       if (GPR_idx != NumGPRs) {
4467         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4468       } else {
4469         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4470                          true, isTailCall, false, MemOpChains,
4471                          TailCallArguments, dl);
4472       }
4473       ArgOffset += PtrByteSize;
4474       break;
4475     case MVT::f32:
4476     case MVT::f64: {
4477       // These can be scalar arguments or elements of a float array type
4478       // passed directly.  The latter are used to implement ELFv2 homogenous
4479       // float aggregates.
4480
4481       // Named arguments go into FPRs first, and once they overflow, the
4482       // remaining arguments go into GPRs and then the parameter save area.
4483       // Unnamed arguments for vararg functions always go to GPRs and
4484       // then the parameter save area.  For now, put all arguments to vararg
4485       // routines always in both locations (FPR *and* GPR or stack slot).
4486       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4487
4488       // First load the argument into the next available FPR.
4489       if (FPR_idx != NumFPRs)
4490         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4491
4492       // Next, load the argument into GPR or stack slot if needed.
4493       if (!NeedGPROrStack)
4494         ;
4495       else if (GPR_idx != NumGPRs) {
4496         // In the non-vararg case, this can only ever happen in the
4497         // presence of f32 array types, since otherwise we never run
4498         // out of FPRs before running out of GPRs.
4499         SDValue ArgVal;
4500
4501         // Double values are always passed in a single GPR.
4502         if (Arg.getValueType() != MVT::f32) {
4503           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4504
4505         // Non-array float values are extended and passed in a GPR.
4506         } else if (!Flags.isInConsecutiveRegs()) {
4507           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4508           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4509
4510         // If we have an array of floats, we collect every odd element
4511         // together with its predecessor into one GPR.
4512         } else if (ArgOffset % PtrByteSize != 0) {
4513           SDValue Lo, Hi;
4514           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4515           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4516           if (!isLittleEndian)
4517             std::swap(Lo, Hi);
4518           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4519
4520         // The final element, if even, goes into the first half of a GPR.
4521         } else if (Flags.isInConsecutiveRegsLast()) {
4522           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4523           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4524           if (!isLittleEndian)
4525             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4526                                  DAG.getConstant(32, MVT::i32));
4527
4528         // Non-final even elements are skipped; they will be handled
4529         // together the with subsequent argument on the next go-around.
4530         } else
4531           ArgVal = SDValue();
4532
4533         if (ArgVal.getNode())
4534           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4535       } else {
4536         // Single-precision floating-point values are mapped to the
4537         // second (rightmost) word of the stack doubleword.
4538         if (Arg.getValueType() == MVT::f32 &&
4539             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4540           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4541           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4542         }
4543
4544         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4545                          true, isTailCall, false, MemOpChains,
4546                          TailCallArguments, dl);
4547       }
4548       // When passing an array of floats, the array occupies consecutive
4549       // space in the argument area; only round up to the next doubleword
4550       // at the end of the array.  Otherwise, each float takes 8 bytes.
4551       ArgOffset += (Arg.getValueType() == MVT::f32 &&
4552                     Flags.isInConsecutiveRegs()) ? 4 : 8;
4553       if (Flags.isInConsecutiveRegsLast())
4554         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4555       break;
4556     }
4557     case MVT::v4f32:
4558     case MVT::v4i32:
4559     case MVT::v8i16:
4560     case MVT::v16i8:
4561     case MVT::v2f64:
4562     case MVT::v2i64:
4563       // These can be scalar arguments or elements of a vector array type
4564       // passed directly.  The latter are used to implement ELFv2 homogenous
4565       // vector aggregates.
4566
4567       // For a varargs call, named arguments go into VRs or on the stack as
4568       // usual; unnamed arguments always go to the stack or the corresponding
4569       // GPRs when within range.  For now, we always put the value in both
4570       // locations (or even all three).
4571       if (isVarArg) {
4572         // We could elide this store in the case where the object fits
4573         // entirely in R registers.  Maybe later.
4574         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4575                                      MachinePointerInfo(), false, false, 0);
4576         MemOpChains.push_back(Store);
4577         if (VR_idx != NumVRs) {
4578           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4579                                      MachinePointerInfo(),
4580                                      false, false, false, 0);
4581           MemOpChains.push_back(Load.getValue(1));
4582
4583           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4584                            Arg.getSimpleValueType() == MVT::v2i64) ?
4585                           VSRH[VR_idx] : VR[VR_idx];
4586           ++VR_idx;
4587
4588           RegsToPass.push_back(std::make_pair(VReg, Load));
4589         }
4590         ArgOffset += 16;
4591         for (unsigned i=0; i<16; i+=PtrByteSize) {
4592           if (GPR_idx == NumGPRs)
4593             break;
4594           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4595                                   DAG.getConstant(i, PtrVT));
4596           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4597                                      false, false, false, 0);
4598           MemOpChains.push_back(Load.getValue(1));
4599           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4600         }
4601         break;
4602       }
4603
4604       // Non-varargs Altivec params go into VRs or on the stack.
4605       if (VR_idx != NumVRs) {
4606         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4607                          Arg.getSimpleValueType() == MVT::v2i64) ?
4608                         VSRH[VR_idx] : VR[VR_idx];
4609         ++VR_idx;
4610
4611         RegsToPass.push_back(std::make_pair(VReg, Arg));
4612       } else {
4613         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4614                          true, isTailCall, true, MemOpChains,
4615                          TailCallArguments, dl);
4616       }
4617       ArgOffset += 16;
4618       break;
4619     }
4620   }
4621
4622   assert(NumBytesActuallyUsed == ArgOffset);
4623   (void)NumBytesActuallyUsed;
4624
4625   if (!MemOpChains.empty())
4626     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4627
4628   // Check if this is an indirect call (MTCTR/BCTRL).
4629   // See PrepareCall() for more information about calls through function
4630   // pointers in the 64-bit SVR4 ABI.
4631   if (!isTailCall &&
4632       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4633       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4634     // Load r2 into a virtual register and store it to the TOC save area.
4635     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4636     // TOC save area offset.
4637     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4638     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4639     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4640     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4641                          false, false, 0);
4642     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4643     // This does not mean the MTCTR instruction must use R12; it's easier
4644     // to model this as an extra parameter, so do that.
4645     if (isELFv2ABI)
4646       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4647   }
4648
4649   // Build a sequence of copy-to-reg nodes chained together with token chain
4650   // and flag operands which copy the outgoing args into the appropriate regs.
4651   SDValue InFlag;
4652   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4653     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4654                              RegsToPass[i].second, InFlag);
4655     InFlag = Chain.getValue(1);
4656   }
4657
4658   if (isTailCall)
4659     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4660                     FPOp, true, TailCallArguments);
4661
4662   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4663                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4664                     Ins, InVals);
4665 }
4666
4667 SDValue
4668 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4669                                     CallingConv::ID CallConv, bool isVarArg,
4670                                     bool isTailCall,
4671                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4672                                     const SmallVectorImpl<SDValue> &OutVals,
4673                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4674                                     SDLoc dl, SelectionDAG &DAG,
4675                                     SmallVectorImpl<SDValue> &InVals) const {
4676
4677   unsigned NumOps = Outs.size();
4678
4679   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4680   bool isPPC64 = PtrVT == MVT::i64;
4681   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4682
4683   MachineFunction &MF = DAG.getMachineFunction();
4684
4685   // Mark this function as potentially containing a function that contains a
4686   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4687   // and restoring the callers stack pointer in this functions epilog. This is
4688   // done because by tail calling the called function might overwrite the value
4689   // in this function's (MF) stack pointer stack slot 0(SP).
4690   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4691       CallConv == CallingConv::Fast)
4692     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4693
4694   // Count how many bytes are to be pushed on the stack, including the linkage
4695   // area, and parameter passing area.  We start with 24/48 bytes, which is
4696   // prereserved space for [SP][CR][LR][3 x unused].
4697   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4698                                                           false);
4699   unsigned NumBytes = LinkageSize;
4700
4701   // Add up all the space actually used.
4702   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4703   // they all go in registers, but we must reserve stack space for them for
4704   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4705   // assigned stack space in order, with padding so Altivec parameters are
4706   // 16-byte aligned.
4707   unsigned nAltivecParamsAtEnd = 0;
4708   for (unsigned i = 0; i != NumOps; ++i) {
4709     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4710     EVT ArgVT = Outs[i].VT;
4711     // Varargs Altivec parameters are padded to a 16 byte boundary.
4712     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4713         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4714         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4715       if (!isVarArg && !isPPC64) {
4716         // Non-varargs Altivec parameters go after all the non-Altivec
4717         // parameters; handle those later so we know how much padding we need.
4718         nAltivecParamsAtEnd++;
4719         continue;
4720       }
4721       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4722       NumBytes = ((NumBytes+15)/16)*16;
4723     }
4724     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4725   }
4726
4727   // Allow for Altivec parameters at the end, if needed.
4728   if (nAltivecParamsAtEnd) {
4729     NumBytes = ((NumBytes+15)/16)*16;
4730     NumBytes += 16*nAltivecParamsAtEnd;
4731   }
4732
4733   // The prolog code of the callee may store up to 8 GPR argument registers to
4734   // the stack, allowing va_start to index over them in memory if its varargs.
4735   // Because we cannot tell if this is needed on the caller side, we have to
4736   // conservatively assume that it is needed.  As such, make sure we have at
4737   // least enough stack space for the caller to store the 8 GPRs.
4738   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4739
4740   // Tail call needs the stack to be aligned.
4741   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4742       CallConv == CallingConv::Fast)
4743     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4744
4745   // Calculate by how many bytes the stack has to be adjusted in case of tail
4746   // call optimization.
4747   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4748
4749   // To protect arguments on the stack from being clobbered in a tail call,
4750   // force all the loads to happen before doing any other lowering.
4751   if (isTailCall)
4752     Chain = DAG.getStackArgumentTokenFactor(Chain);
4753
4754   // Adjust the stack pointer for the new arguments...
4755   // These operations are automatically eliminated by the prolog/epilog pass
4756   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4757                                dl);
4758   SDValue CallSeqStart = Chain;
4759
4760   // Load the return address and frame pointer so it can be move somewhere else
4761   // later.
4762   SDValue LROp, FPOp;
4763   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4764                                        dl);
4765
4766   // Set up a copy of the stack pointer for use loading and storing any
4767   // arguments that may not fit in the registers available for argument
4768   // passing.
4769   SDValue StackPtr;
4770   if (isPPC64)
4771     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4772   else
4773     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4774
4775   // Figure out which arguments are going to go in registers, and which in
4776   // memory.  Also, if this is a vararg function, floating point operations
4777   // must be stored to our stack, and loaded into integer regs as well, if
4778   // any integer regs are available for argument passing.
4779   unsigned ArgOffset = LinkageSize;
4780   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4781
4782   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4783     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4784     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4785   };
4786   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4787     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4788     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4789   };
4790   static const MCPhysReg *FPR = GetFPR();
4791
4792   static const MCPhysReg VR[] = {
4793     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4794     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4795   };
4796   const unsigned NumGPRs = array_lengthof(GPR_32);
4797   const unsigned NumFPRs = 13;
4798   const unsigned NumVRs  = array_lengthof(VR);
4799
4800   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4801
4802   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4803   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4804
4805   SmallVector<SDValue, 8> MemOpChains;
4806   for (unsigned i = 0; i != NumOps; ++i) {
4807     SDValue Arg = OutVals[i];
4808     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4809
4810     // PtrOff will be used to store the current argument to the stack if a
4811     // register cannot be found for it.
4812     SDValue PtrOff;
4813
4814     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4815
4816     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4817
4818     // On PPC64, promote integers to 64-bit values.
4819     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4820       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4821       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4822       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4823     }
4824
4825     // FIXME memcpy is used way more than necessary.  Correctness first.
4826     // Note: "by value" is code for passing a structure by value, not
4827     // basic types.
4828     if (Flags.isByVal()) {
4829       unsigned Size = Flags.getByValSize();
4830       // Very small objects are passed right-justified.  Everything else is
4831       // passed left-justified.
4832       if (Size==1 || Size==2) {
4833         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4834         if (GPR_idx != NumGPRs) {
4835           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4836                                         MachinePointerInfo(), VT,
4837                                         false, false, false, 0);
4838           MemOpChains.push_back(Load.getValue(1));
4839           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4840
4841           ArgOffset += PtrByteSize;
4842         } else {
4843           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4844                                           PtrOff.getValueType());
4845           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4846           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4847                                                             CallSeqStart,
4848                                                             Flags, DAG, dl);
4849           ArgOffset += PtrByteSize;
4850         }
4851         continue;
4852       }
4853       // Copy entire object into memory.  There are cases where gcc-generated
4854       // code assumes it is there, even if it could be put entirely into
4855       // registers.  (This is not what the doc says.)
4856       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4857                                                         CallSeqStart,
4858                                                         Flags, DAG, dl);
4859
4860       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4861       // copy the pieces of the object that fit into registers from the
4862       // parameter save area.
4863       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4864         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4865         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4866         if (GPR_idx != NumGPRs) {
4867           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4868                                      MachinePointerInfo(),
4869                                      false, false, false, 0);
4870           MemOpChains.push_back(Load.getValue(1));
4871           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4872           ArgOffset += PtrByteSize;
4873         } else {
4874           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4875           break;
4876         }
4877       }
4878       continue;
4879     }
4880
4881     switch (Arg.getSimpleValueType().SimpleTy) {
4882     default: llvm_unreachable("Unexpected ValueType for argument!");
4883     case MVT::i1:
4884     case MVT::i32:
4885     case MVT::i64:
4886       if (GPR_idx != NumGPRs) {
4887         if (Arg.getValueType() == MVT::i1)
4888           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4889
4890         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4891       } else {
4892         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4893                          isPPC64, isTailCall, false, MemOpChains,
4894                          TailCallArguments, dl);
4895       }
4896       ArgOffset += PtrByteSize;
4897       break;
4898     case MVT::f32:
4899     case MVT::f64:
4900       if (FPR_idx != NumFPRs) {
4901         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4902
4903         if (isVarArg) {
4904           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4905                                        MachinePointerInfo(), false, false, 0);
4906           MemOpChains.push_back(Store);
4907
4908           // Float varargs are always shadowed in available integer registers
4909           if (GPR_idx != NumGPRs) {
4910             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4911                                        MachinePointerInfo(), false, false,
4912                                        false, 0);
4913             MemOpChains.push_back(Load.getValue(1));
4914             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4915           }
4916           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4917             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4918             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4919             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4920                                        MachinePointerInfo(),
4921                                        false, false, false, 0);
4922             MemOpChains.push_back(Load.getValue(1));
4923             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4924           }
4925         } else {
4926           // If we have any FPRs remaining, we may also have GPRs remaining.
4927           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4928           // GPRs.
4929           if (GPR_idx != NumGPRs)
4930             ++GPR_idx;
4931           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4932               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4933             ++GPR_idx;
4934         }
4935       } else
4936         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4937                          isPPC64, isTailCall, false, MemOpChains,
4938                          TailCallArguments, dl);
4939       if (isPPC64)
4940         ArgOffset += 8;
4941       else
4942         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4943       break;
4944     case MVT::v4f32:
4945     case MVT::v4i32:
4946     case MVT::v8i16:
4947     case MVT::v16i8:
4948       if (isVarArg) {
4949         // These go aligned on the stack, or in the corresponding R registers
4950         // when within range.  The Darwin PPC ABI doc claims they also go in
4951         // V registers; in fact gcc does this only for arguments that are
4952         // prototyped, not for those that match the ...  We do it for all
4953         // arguments, seems to work.
4954         while (ArgOffset % 16 !=0) {
4955           ArgOffset += PtrByteSize;
4956           if (GPR_idx != NumGPRs)
4957             GPR_idx++;
4958         }
4959         // We could elide this store in the case where the object fits
4960         // entirely in R registers.  Maybe later.
4961         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4962                             DAG.getConstant(ArgOffset, PtrVT));
4963         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4964                                      MachinePointerInfo(), false, false, 0);
4965         MemOpChains.push_back(Store);
4966         if (VR_idx != NumVRs) {
4967           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4968                                      MachinePointerInfo(),
4969                                      false, false, false, 0);
4970           MemOpChains.push_back(Load.getValue(1));
4971           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4972         }
4973         ArgOffset += 16;
4974         for (unsigned i=0; i<16; i+=PtrByteSize) {
4975           if (GPR_idx == NumGPRs)
4976             break;
4977           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4978                                   DAG.getConstant(i, PtrVT));
4979           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4980                                      false, false, false, 0);
4981           MemOpChains.push_back(Load.getValue(1));
4982           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4983         }
4984         break;
4985       }
4986
4987       // Non-varargs Altivec params generally go in registers, but have
4988       // stack space allocated at the end.
4989       if (VR_idx != NumVRs) {
4990         // Doesn't have GPR space allocated.
4991         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4992       } else if (nAltivecParamsAtEnd==0) {
4993         // We are emitting Altivec params in order.
4994         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4995                          isPPC64, isTailCall, true, MemOpChains,
4996                          TailCallArguments, dl);
4997         ArgOffset += 16;
4998       }
4999       break;
5000     }
5001   }
5002   // If all Altivec parameters fit in registers, as they usually do,
5003   // they get stack space following the non-Altivec parameters.  We
5004   // don't track this here because nobody below needs it.
5005   // If there are more Altivec parameters than fit in registers emit
5006   // the stores here.
5007   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5008     unsigned j = 0;
5009     // Offset is aligned; skip 1st 12 params which go in V registers.
5010     ArgOffset = ((ArgOffset+15)/16)*16;
5011     ArgOffset += 12*16;
5012     for (unsigned i = 0; i != NumOps; ++i) {
5013       SDValue Arg = OutVals[i];
5014       EVT ArgType = Outs[i].VT;
5015       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5016           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5017         if (++j > NumVRs) {
5018           SDValue PtrOff;
5019           // We are emitting Altivec params in order.
5020           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5021                            isPPC64, isTailCall, true, MemOpChains,
5022                            TailCallArguments, dl);
5023           ArgOffset += 16;
5024         }
5025       }
5026     }
5027   }
5028
5029   if (!MemOpChains.empty())
5030     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5031
5032   // On Darwin, R12 must contain the address of an indirect callee.  This does
5033   // not mean the MTCTR instruction must use R12; it's easier to model this as
5034   // an extra parameter, so do that.
5035   if (!isTailCall &&
5036       !dyn_cast<GlobalAddressSDNode>(Callee) &&
5037       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5038       !isBLACompatibleAddress(Callee, DAG))
5039     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5040                                                    PPC::R12), Callee));
5041
5042   // Build a sequence of copy-to-reg nodes chained together with token chain
5043   // and flag operands which copy the outgoing args into the appropriate regs.
5044   SDValue InFlag;
5045   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5046     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5047                              RegsToPass[i].second, InFlag);
5048     InFlag = Chain.getValue(1);
5049   }
5050
5051   if (isTailCall)
5052     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5053                     FPOp, true, TailCallArguments);
5054
5055   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5056                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5057                     Ins, InVals);
5058 }
5059
5060 bool
5061 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5062                                   MachineFunction &MF, bool isVarArg,
5063                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5064                                   LLVMContext &Context) const {
5065   SmallVector<CCValAssign, 16> RVLocs;
5066   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5067   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5068 }
5069
5070 SDValue
5071 PPCTargetLowering::LowerReturn(SDValue Chain,
5072                                CallingConv::ID CallConv, bool isVarArg,
5073                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5074                                const SmallVectorImpl<SDValue> &OutVals,
5075                                SDLoc dl, SelectionDAG &DAG) const {
5076
5077   SmallVector<CCValAssign, 16> RVLocs;
5078   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5079                  *DAG.getContext());
5080   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5081
5082   SDValue Flag;
5083   SmallVector<SDValue, 4> RetOps(1, Chain);
5084
5085   // Copy the result values into the output registers.
5086   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5087     CCValAssign &VA = RVLocs[i];
5088     assert(VA.isRegLoc() && "Can only return in registers!");
5089
5090     SDValue Arg = OutVals[i];
5091
5092     switch (VA.getLocInfo()) {
5093     default: llvm_unreachable("Unknown loc info!");
5094     case CCValAssign::Full: break;
5095     case CCValAssign::AExt:
5096       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5097       break;
5098     case CCValAssign::ZExt:
5099       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5100       break;
5101     case CCValAssign::SExt:
5102       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5103       break;
5104     }
5105
5106     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5107     Flag = Chain.getValue(1);
5108     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5109   }
5110
5111   RetOps[0] = Chain;  // Update chain.
5112
5113   // Add the flag if we have it.
5114   if (Flag.getNode())
5115     RetOps.push_back(Flag);
5116
5117   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5118 }
5119
5120 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5121                                    const PPCSubtarget &Subtarget) const {
5122   // When we pop the dynamic allocation we need to restore the SP link.
5123   SDLoc dl(Op);
5124
5125   // Get the corect type for pointers.
5126   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5127
5128   // Construct the stack pointer operand.
5129   bool isPPC64 = Subtarget.isPPC64();
5130   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5131   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5132
5133   // Get the operands for the STACKRESTORE.
5134   SDValue Chain = Op.getOperand(0);
5135   SDValue SaveSP = Op.getOperand(1);
5136
5137   // Load the old link SP.
5138   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5139                                    MachinePointerInfo(),
5140                                    false, false, false, 0);
5141
5142   // Restore the stack pointer.
5143   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5144
5145   // Store the old link SP.
5146   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5147                       false, false, 0);
5148 }
5149
5150
5151
5152 SDValue
5153 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5154   MachineFunction &MF = DAG.getMachineFunction();
5155   bool isPPC64 = Subtarget.isPPC64();
5156   bool isDarwinABI = Subtarget.isDarwinABI();
5157   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5158
5159   // Get current frame pointer save index.  The users of this index will be
5160   // primarily DYNALLOC instructions.
5161   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5162   int RASI = FI->getReturnAddrSaveIndex();
5163
5164   // If the frame pointer save index hasn't been defined yet.
5165   if (!RASI) {
5166     // Find out what the fix offset of the frame pointer save area.
5167     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5168     // Allocate the frame index for frame pointer save area.
5169     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
5170     // Save the result.
5171     FI->setReturnAddrSaveIndex(RASI);
5172   }
5173   return DAG.getFrameIndex(RASI, PtrVT);
5174 }
5175
5176 SDValue
5177 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5178   MachineFunction &MF = DAG.getMachineFunction();
5179   bool isPPC64 = Subtarget.isPPC64();
5180   bool isDarwinABI = Subtarget.isDarwinABI();
5181   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5182
5183   // Get current frame pointer save index.  The users of this index will be
5184   // primarily DYNALLOC instructions.
5185   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5186   int FPSI = FI->getFramePointerSaveIndex();
5187
5188   // If the frame pointer save index hasn't been defined yet.
5189   if (!FPSI) {
5190     // Find out what the fix offset of the frame pointer save area.
5191     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5192                                                            isDarwinABI);
5193
5194     // Allocate the frame index for frame pointer save area.
5195     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5196     // Save the result.
5197     FI->setFramePointerSaveIndex(FPSI);
5198   }
5199   return DAG.getFrameIndex(FPSI, PtrVT);
5200 }
5201
5202 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5203                                          SelectionDAG &DAG,
5204                                          const PPCSubtarget &Subtarget) const {
5205   // Get the inputs.
5206   SDValue Chain = Op.getOperand(0);
5207   SDValue Size  = Op.getOperand(1);
5208   SDLoc dl(Op);
5209
5210   // Get the corect type for pointers.
5211   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5212   // Negate the size.
5213   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5214                                   DAG.getConstant(0, PtrVT), Size);
5215   // Construct a node for the frame pointer save index.
5216   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5217   // Build a DYNALLOC node.
5218   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5219   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5220   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5221 }
5222
5223 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5224                                                SelectionDAG &DAG) const {
5225   SDLoc DL(Op);
5226   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5227                      DAG.getVTList(MVT::i32, MVT::Other),
5228                      Op.getOperand(0), Op.getOperand(1));
5229 }
5230
5231 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5232                                                 SelectionDAG &DAG) const {
5233   SDLoc DL(Op);
5234   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5235                      Op.getOperand(0), Op.getOperand(1));
5236 }
5237
5238 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5239   assert(Op.getValueType() == MVT::i1 &&
5240          "Custom lowering only for i1 loads");
5241
5242   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5243
5244   SDLoc dl(Op);
5245   LoadSDNode *LD = cast<LoadSDNode>(Op);
5246
5247   SDValue Chain = LD->getChain();
5248   SDValue BasePtr = LD->getBasePtr();
5249   MachineMemOperand *MMO = LD->getMemOperand();
5250
5251   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5252                                  BasePtr, MVT::i8, MMO);
5253   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5254
5255   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5256   return DAG.getMergeValues(Ops, dl);
5257 }
5258
5259 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5260   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5261          "Custom lowering only for i1 stores");
5262
5263   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5264
5265   SDLoc dl(Op);
5266   StoreSDNode *ST = cast<StoreSDNode>(Op);
5267
5268   SDValue Chain = ST->getChain();
5269   SDValue BasePtr = ST->getBasePtr();
5270   SDValue Value = ST->getValue();
5271   MachineMemOperand *MMO = ST->getMemOperand();
5272
5273   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5274   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5275 }
5276
5277 // FIXME: Remove this once the ANDI glue bug is fixed:
5278 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5279   assert(Op.getValueType() == MVT::i1 &&
5280          "Custom lowering only for i1 results");
5281
5282   SDLoc DL(Op);
5283   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5284                      Op.getOperand(0));
5285 }
5286
5287 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5288 /// possible.
5289 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5290   // Not FP? Not a fsel.
5291   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5292       !Op.getOperand(2).getValueType().isFloatingPoint())
5293     return Op;
5294
5295   // We might be able to do better than this under some circumstances, but in
5296   // general, fsel-based lowering of select is a finite-math-only optimization.
5297   // For more information, see section F.3 of the 2.06 ISA specification.
5298   if (!DAG.getTarget().Options.NoInfsFPMath ||
5299       !DAG.getTarget().Options.NoNaNsFPMath)
5300     return Op;
5301
5302   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5303
5304   EVT ResVT = Op.getValueType();
5305   EVT CmpVT = Op.getOperand(0).getValueType();
5306   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5307   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5308   SDLoc dl(Op);
5309
5310   // If the RHS of the comparison is a 0.0, we don't need to do the
5311   // subtraction at all.
5312   SDValue Sel1;
5313   if (isFloatingPointZero(RHS))
5314     switch (CC) {
5315     default: break;       // SETUO etc aren't handled by fsel.
5316     case ISD::SETNE:
5317       std::swap(TV, FV);
5318     case ISD::SETEQ:
5319       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5320         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5321       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5322       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5323         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5324       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5325                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5326     case ISD::SETULT:
5327     case ISD::SETLT:
5328       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5329     case ISD::SETOGE:
5330     case ISD::SETGE:
5331       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5332         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5333       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5334     case ISD::SETUGT:
5335     case ISD::SETGT:
5336       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5337     case ISD::SETOLE:
5338     case ISD::SETLE:
5339       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5340         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5341       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5342                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5343     }
5344
5345   SDValue Cmp;
5346   switch (CC) {
5347   default: break;       // SETUO etc aren't handled by fsel.
5348   case ISD::SETNE:
5349     std::swap(TV, FV);
5350   case ISD::SETEQ:
5351     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5352     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5353       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5354     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5355     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5356       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5357     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5358                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5359   case ISD::SETULT:
5360   case ISD::SETLT:
5361     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5362     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5363       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5364     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5365   case ISD::SETOGE:
5366   case ISD::SETGE:
5367     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5368     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5369       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5370     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5371   case ISD::SETUGT:
5372   case ISD::SETGT:
5373     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5374     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5375       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5376     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5377   case ISD::SETOLE:
5378   case ISD::SETLE:
5379     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5380     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5381       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5382     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5383   }
5384   return Op;
5385 }
5386
5387 // FIXME: Split this code up when LegalizeDAGTypes lands.
5388 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5389                                            SDLoc dl) const {
5390   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5391   SDValue Src = Op.getOperand(0);
5392   if (Src.getValueType() == MVT::f32)
5393     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5394
5395   SDValue Tmp;
5396   switch (Op.getSimpleValueType().SimpleTy) {
5397   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5398   case MVT::i32:
5399     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5400                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5401                                                    PPCISD::FCTIDZ),
5402                       dl, MVT::f64, Src);
5403     break;
5404   case MVT::i64:
5405     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5406            "i64 FP_TO_UINT is supported only with FPCVT");
5407     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5408                                                         PPCISD::FCTIDUZ,
5409                       dl, MVT::f64, Src);
5410     break;
5411   }
5412
5413   // Convert the FP value to an int value through memory.
5414   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5415     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5416   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5417   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5418   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5419
5420   // Emit a store to the stack slot.
5421   SDValue Chain;
5422   if (i32Stack) {
5423     MachineFunction &MF = DAG.getMachineFunction();
5424     MachineMemOperand *MMO =
5425       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5426     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5427     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5428               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5429   } else
5430     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5431                          MPI, false, false, 0);
5432
5433   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5434   // add in a bias.
5435   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5436     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5437                         DAG.getConstant(4, FIPtr.getValueType()));
5438     MPI = MachinePointerInfo();
5439   }
5440
5441   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5442                      false, false, false, 0);
5443 }
5444
5445 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5446                                            SelectionDAG &DAG) const {
5447   SDLoc dl(Op);
5448   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5449   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5450     return SDValue();
5451
5452   if (Op.getOperand(0).getValueType() == MVT::i1)
5453     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5454                        DAG.getConstantFP(1.0, Op.getValueType()),
5455                        DAG.getConstantFP(0.0, Op.getValueType()));
5456
5457   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5458          "UINT_TO_FP is supported only with FPCVT");
5459
5460   // If we have FCFIDS, then use it when converting to single-precision.
5461   // Otherwise, convert to double-precision and then round.
5462   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5463                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5464                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5465                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5466                     PPCISD::FCFIDU : PPCISD::FCFID);
5467   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5468                    MVT::f32 : MVT::f64;
5469
5470   if (Op.getOperand(0).getValueType() == MVT::i64) {
5471     SDValue SINT = Op.getOperand(0);
5472     // When converting to single-precision, we actually need to convert
5473     // to double-precision first and then round to single-precision.
5474     // To avoid double-rounding effects during that operation, we have
5475     // to prepare the input operand.  Bits that might be truncated when
5476     // converting to double-precision are replaced by a bit that won't
5477     // be lost at this stage, but is below the single-precision rounding
5478     // position.
5479     //
5480     // However, if -enable-unsafe-fp-math is in effect, accept double
5481     // rounding to avoid the extra overhead.
5482     if (Op.getValueType() == MVT::f32 &&
5483         !Subtarget.hasFPCVT() &&
5484         !DAG.getTarget().Options.UnsafeFPMath) {
5485
5486       // Twiddle input to make sure the low 11 bits are zero.  (If this
5487       // is the case, we are guaranteed the value will fit into the 53 bit
5488       // mantissa of an IEEE double-precision value without rounding.)
5489       // If any of those low 11 bits were not zero originally, make sure
5490       // bit 12 (value 2048) is set instead, so that the final rounding
5491       // to single-precision gets the correct result.
5492       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5493                                   SINT, DAG.getConstant(2047, MVT::i64));
5494       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5495                           Round, DAG.getConstant(2047, MVT::i64));
5496       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5497       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5498                           Round, DAG.getConstant(-2048, MVT::i64));
5499
5500       // However, we cannot use that value unconditionally: if the magnitude
5501       // of the input value is small, the bit-twiddling we did above might
5502       // end up visibly changing the output.  Fortunately, in that case, we
5503       // don't need to twiddle bits since the original input will convert
5504       // exactly to double-precision floating-point already.  Therefore,
5505       // construct a conditional to use the original value if the top 11
5506       // bits are all sign-bit copies, and use the rounded value computed
5507       // above otherwise.
5508       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5509                                  SINT, DAG.getConstant(53, MVT::i32));
5510       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5511                          Cond, DAG.getConstant(1, MVT::i64));
5512       Cond = DAG.getSetCC(dl, MVT::i32,
5513                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5514
5515       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5516     }
5517
5518     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5519     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5520
5521     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5522       FP = DAG.getNode(ISD::FP_ROUND, dl,
5523                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5524     return FP;
5525   }
5526
5527   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5528          "Unhandled INT_TO_FP type in custom expander!");
5529   // Since we only generate this in 64-bit mode, we can take advantage of
5530   // 64-bit registers.  In particular, sign extend the input value into the
5531   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5532   // then lfd it and fcfid it.
5533   MachineFunction &MF = DAG.getMachineFunction();
5534   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5535   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5536
5537   SDValue Ld;
5538   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5539     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5540     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5541
5542     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5543                                  MachinePointerInfo::getFixedStack(FrameIdx),
5544                                  false, false, 0);
5545
5546     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5547            "Expected an i32 store");
5548     MachineMemOperand *MMO =
5549       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5550                               MachineMemOperand::MOLoad, 4, 4);
5551     SDValue Ops[] = { Store, FIdx };
5552     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5553                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5554                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5555                                  Ops, MVT::i32, MMO);
5556   } else {
5557     assert(Subtarget.isPPC64() &&
5558            "i32->FP without LFIWAX supported only on PPC64");
5559
5560     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5561     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5562
5563     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5564                                 Op.getOperand(0));
5565
5566     // STD the extended value into the stack slot.
5567     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5568                                  MachinePointerInfo::getFixedStack(FrameIdx),
5569                                  false, false, 0);
5570
5571     // Load the value as a double.
5572     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5573                      MachinePointerInfo::getFixedStack(FrameIdx),
5574                      false, false, false, 0);
5575   }
5576
5577   // FCFID it and return it.
5578   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5579   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5580     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5581   return FP;
5582 }
5583
5584 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5585                                             SelectionDAG &DAG) const {
5586   SDLoc dl(Op);
5587   /*
5588    The rounding mode is in bits 30:31 of FPSR, and has the following
5589    settings:
5590      00 Round to nearest
5591      01 Round to 0
5592      10 Round to +inf
5593      11 Round to -inf
5594
5595   FLT_ROUNDS, on the other hand, expects the following:
5596     -1 Undefined
5597      0 Round to 0
5598      1 Round to nearest
5599      2 Round to +inf
5600      3 Round to -inf
5601
5602   To perform the conversion, we do:
5603     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5604   */
5605
5606   MachineFunction &MF = DAG.getMachineFunction();
5607   EVT VT = Op.getValueType();
5608   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5609
5610   // Save FP Control Word to register
5611   EVT NodeTys[] = {
5612     MVT::f64,    // return register
5613     MVT::Glue    // unused in this context
5614   };
5615   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5616
5617   // Save FP register to stack slot
5618   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5619   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5620   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5621                                StackSlot, MachinePointerInfo(), false, false,0);
5622
5623   // Load FP Control Word from low 32 bits of stack slot.
5624   SDValue Four = DAG.getConstant(4, PtrVT);
5625   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5626   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5627                             false, false, false, 0);
5628
5629   // Transform as necessary
5630   SDValue CWD1 =
5631     DAG.getNode(ISD::AND, dl, MVT::i32,
5632                 CWD, DAG.getConstant(3, MVT::i32));
5633   SDValue CWD2 =
5634     DAG.getNode(ISD::SRL, dl, MVT::i32,
5635                 DAG.getNode(ISD::AND, dl, MVT::i32,
5636                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5637                                         CWD, DAG.getConstant(3, MVT::i32)),
5638                             DAG.getConstant(3, MVT::i32)),
5639                 DAG.getConstant(1, MVT::i32));
5640
5641   SDValue RetVal =
5642     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5643
5644   return DAG.getNode((VT.getSizeInBits() < 16 ?
5645                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5646 }
5647
5648 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5649   EVT VT = Op.getValueType();
5650   unsigned BitWidth = VT.getSizeInBits();
5651   SDLoc dl(Op);
5652   assert(Op.getNumOperands() == 3 &&
5653          VT == Op.getOperand(1).getValueType() &&
5654          "Unexpected SHL!");
5655
5656   // Expand into a bunch of logical ops.  Note that these ops
5657   // depend on the PPC behavior for oversized shift amounts.
5658   SDValue Lo = Op.getOperand(0);
5659   SDValue Hi = Op.getOperand(1);
5660   SDValue Amt = Op.getOperand(2);
5661   EVT AmtVT = Amt.getValueType();
5662
5663   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5664                              DAG.getConstant(BitWidth, AmtVT), Amt);
5665   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5666   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5667   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5668   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5669                              DAG.getConstant(-BitWidth, AmtVT));
5670   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5671   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5672   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5673   SDValue OutOps[] = { OutLo, OutHi };
5674   return DAG.getMergeValues(OutOps, dl);
5675 }
5676
5677 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5678   EVT VT = Op.getValueType();
5679   SDLoc dl(Op);
5680   unsigned BitWidth = VT.getSizeInBits();
5681   assert(Op.getNumOperands() == 3 &&
5682          VT == Op.getOperand(1).getValueType() &&
5683          "Unexpected SRL!");
5684
5685   // Expand into a bunch of logical ops.  Note that these ops
5686   // depend on the PPC behavior for oversized shift amounts.
5687   SDValue Lo = Op.getOperand(0);
5688   SDValue Hi = Op.getOperand(1);
5689   SDValue Amt = Op.getOperand(2);
5690   EVT AmtVT = Amt.getValueType();
5691
5692   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5693                              DAG.getConstant(BitWidth, AmtVT), Amt);
5694   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5695   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5696   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5697   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5698                              DAG.getConstant(-BitWidth, AmtVT));
5699   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5700   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5701   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5702   SDValue OutOps[] = { OutLo, OutHi };
5703   return DAG.getMergeValues(OutOps, dl);
5704 }
5705
5706 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5707   SDLoc dl(Op);
5708   EVT VT = Op.getValueType();
5709   unsigned BitWidth = VT.getSizeInBits();
5710   assert(Op.getNumOperands() == 3 &&
5711          VT == Op.getOperand(1).getValueType() &&
5712          "Unexpected SRA!");
5713
5714   // Expand into a bunch of logical ops, followed by a select_cc.
5715   SDValue Lo = Op.getOperand(0);
5716   SDValue Hi = Op.getOperand(1);
5717   SDValue Amt = Op.getOperand(2);
5718   EVT AmtVT = Amt.getValueType();
5719
5720   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5721                              DAG.getConstant(BitWidth, AmtVT), Amt);
5722   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5723   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5724   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5725   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5726                              DAG.getConstant(-BitWidth, AmtVT));
5727   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5728   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5729   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5730                                   Tmp4, Tmp6, ISD::SETLE);
5731   SDValue OutOps[] = { OutLo, OutHi };
5732   return DAG.getMergeValues(OutOps, dl);
5733 }
5734
5735 //===----------------------------------------------------------------------===//
5736 // Vector related lowering.
5737 //
5738
5739 /// BuildSplatI - Build a canonical splati of Val with an element size of
5740 /// SplatSize.  Cast the result to VT.
5741 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5742                              SelectionDAG &DAG, SDLoc dl) {
5743   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5744
5745   static const EVT VTys[] = { // canonical VT to use for each size.
5746     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5747   };
5748
5749   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5750
5751   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5752   if (Val == -1)
5753     SplatSize = 1;
5754
5755   EVT CanonicalVT = VTys[SplatSize-1];
5756
5757   // Build a canonical splat for this value.
5758   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5759   SmallVector<SDValue, 8> Ops;
5760   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5761   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5762   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5763 }
5764
5765 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5766 /// specified intrinsic ID.
5767 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5768                                 SelectionDAG &DAG, SDLoc dl,
5769                                 EVT DestVT = MVT::Other) {
5770   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5771   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5772                      DAG.getConstant(IID, MVT::i32), Op);
5773 }
5774
5775 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5776 /// specified intrinsic ID.
5777 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5778                                 SelectionDAG &DAG, SDLoc dl,
5779                                 EVT DestVT = MVT::Other) {
5780   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5781   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5782                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5783 }
5784
5785 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5786 /// specified intrinsic ID.
5787 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5788                                 SDValue Op2, SelectionDAG &DAG,
5789                                 SDLoc dl, EVT DestVT = MVT::Other) {
5790   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5791   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5792                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5793 }
5794
5795
5796 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5797 /// amount.  The result has the specified value type.
5798 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5799                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5800   // Force LHS/RHS to be the right type.
5801   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5802   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5803
5804   int Ops[16];
5805   for (unsigned i = 0; i != 16; ++i)
5806     Ops[i] = i + Amt;
5807   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5808   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5809 }
5810
5811 // If this is a case we can't handle, return null and let the default
5812 // expansion code take care of it.  If we CAN select this case, and if it
5813 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5814 // this case more efficiently than a constant pool load, lower it to the
5815 // sequence of ops that should be used.
5816 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5817                                              SelectionDAG &DAG) const {
5818   SDLoc dl(Op);
5819   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5820   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5821
5822   // Check if this is a splat of a constant value.
5823   APInt APSplatBits, APSplatUndef;
5824   unsigned SplatBitSize;
5825   bool HasAnyUndefs;
5826   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5827                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5828     return SDValue();
5829
5830   unsigned SplatBits = APSplatBits.getZExtValue();
5831   unsigned SplatUndef = APSplatUndef.getZExtValue();
5832   unsigned SplatSize = SplatBitSize / 8;
5833
5834   // First, handle single instruction cases.
5835
5836   // All zeros?
5837   if (SplatBits == 0) {
5838     // Canonicalize all zero vectors to be v4i32.
5839     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5840       SDValue Z = DAG.getConstant(0, MVT::i32);
5841       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5842       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5843     }
5844     return Op;
5845   }
5846
5847   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5848   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5849                     (32-SplatBitSize));
5850   if (SextVal >= -16 && SextVal <= 15)
5851     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5852
5853
5854   // Two instruction sequences.
5855
5856   // If this value is in the range [-32,30] and is even, use:
5857   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5858   // If this value is in the range [17,31] and is odd, use:
5859   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5860   // If this value is in the range [-31,-17] and is odd, use:
5861   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5862   // Note the last two are three-instruction sequences.
5863   if (SextVal >= -32 && SextVal <= 31) {
5864     // To avoid having these optimizations undone by constant folding,
5865     // we convert to a pseudo that will be expanded later into one of
5866     // the above forms.
5867     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5868     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5869               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5870     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5871     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5872     if (VT == Op.getValueType())
5873       return RetVal;
5874     else
5875       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5876   }
5877
5878   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5879   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5880   // for fneg/fabs.
5881   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5882     // Make -1 and vspltisw -1:
5883     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5884
5885     // Make the VSLW intrinsic, computing 0x8000_0000.
5886     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5887                                    OnesV, DAG, dl);
5888
5889     // xor by OnesV to invert it.
5890     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5891     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5892   }
5893
5894   // The remaining cases assume either big endian element order or
5895   // a splat-size that equates to the element size of the vector
5896   // to be built.  An example that doesn't work for little endian is
5897   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5898   // and a vector element size of 16 bits.  The code below will
5899   // produce the vector in big endian element order, which for little
5900   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5901
5902   // For now, just avoid these optimizations in that case.
5903   // FIXME: Develop correct optimizations for LE with mismatched
5904   // splat and element sizes.
5905
5906   if (Subtarget.isLittleEndian() &&
5907       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5908     return SDValue();
5909
5910   // Check to see if this is a wide variety of vsplti*, binop self cases.
5911   static const signed char SplatCsts[] = {
5912     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5913     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5914   };
5915
5916   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5917     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5918     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5919     int i = SplatCsts[idx];
5920
5921     // Figure out what shift amount will be used by altivec if shifted by i in
5922     // this splat size.
5923     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5924
5925     // vsplti + shl self.
5926     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5927       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5928       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5929         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5930         Intrinsic::ppc_altivec_vslw
5931       };
5932       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5933       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5934     }
5935
5936     // vsplti + srl self.
5937     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5938       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5939       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5940         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5941         Intrinsic::ppc_altivec_vsrw
5942       };
5943       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5944       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5945     }
5946
5947     // vsplti + sra self.
5948     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5949       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5950       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5951         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5952         Intrinsic::ppc_altivec_vsraw
5953       };
5954       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5955       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5956     }
5957
5958     // vsplti + rol self.
5959     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5960                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5961       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5962       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5963         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5964         Intrinsic::ppc_altivec_vrlw
5965       };
5966       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5967       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5968     }
5969
5970     // t = vsplti c, result = vsldoi t, t, 1
5971     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5972       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5973       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5974     }
5975     // t = vsplti c, result = vsldoi t, t, 2
5976     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5977       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5978       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5979     }
5980     // t = vsplti c, result = vsldoi t, t, 3
5981     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5982       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5983       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5984     }
5985   }
5986
5987   return SDValue();
5988 }
5989
5990 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5991 /// the specified operations to build the shuffle.
5992 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5993                                       SDValue RHS, SelectionDAG &DAG,
5994                                       SDLoc dl) {
5995   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5996   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5997   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5998
5999   enum {
6000     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6001     OP_VMRGHW,
6002     OP_VMRGLW,
6003     OP_VSPLTISW0,
6004     OP_VSPLTISW1,
6005     OP_VSPLTISW2,
6006     OP_VSPLTISW3,
6007     OP_VSLDOI4,
6008     OP_VSLDOI8,
6009     OP_VSLDOI12
6010   };
6011
6012   if (OpNum == OP_COPY) {
6013     if (LHSID == (1*9+2)*9+3) return LHS;
6014     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6015     return RHS;
6016   }
6017
6018   SDValue OpLHS, OpRHS;
6019   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6020   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6021
6022   int ShufIdxs[16];
6023   switch (OpNum) {
6024   default: llvm_unreachable("Unknown i32 permute!");
6025   case OP_VMRGHW:
6026     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6027     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6028     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6029     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6030     break;
6031   case OP_VMRGLW:
6032     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6033     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6034     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6035     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6036     break;
6037   case OP_VSPLTISW0:
6038     for (unsigned i = 0; i != 16; ++i)
6039       ShufIdxs[i] = (i&3)+0;
6040     break;
6041   case OP_VSPLTISW1:
6042     for (unsigned i = 0; i != 16; ++i)
6043       ShufIdxs[i] = (i&3)+4;
6044     break;
6045   case OP_VSPLTISW2:
6046     for (unsigned i = 0; i != 16; ++i)
6047       ShufIdxs[i] = (i&3)+8;
6048     break;
6049   case OP_VSPLTISW3:
6050     for (unsigned i = 0; i != 16; ++i)
6051       ShufIdxs[i] = (i&3)+12;
6052     break;
6053   case OP_VSLDOI4:
6054     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6055   case OP_VSLDOI8:
6056     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6057   case OP_VSLDOI12:
6058     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6059   }
6060   EVT VT = OpLHS.getValueType();
6061   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6062   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6063   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6064   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6065 }
6066
6067 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6068 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6069 /// return the code it can be lowered into.  Worst case, it can always be
6070 /// lowered into a vperm.
6071 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6072                                                SelectionDAG &DAG) const {
6073   SDLoc dl(Op);
6074   SDValue V1 = Op.getOperand(0);
6075   SDValue V2 = Op.getOperand(1);
6076   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6077   EVT VT = Op.getValueType();
6078   bool isLittleEndian = Subtarget.isLittleEndian();
6079
6080   // Cases that are handled by instructions that take permute immediates
6081   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6082   // selected by the instruction selector.
6083   if (V2.getOpcode() == ISD::UNDEF) {
6084     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6085         PPC::isSplatShuffleMask(SVOp, 2) ||
6086         PPC::isSplatShuffleMask(SVOp, 4) ||
6087         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6088         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6089         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6090         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6091         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6092         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6093         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6094         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6095         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6096       return Op;
6097     }
6098   }
6099
6100   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6101   // and produce a fixed permutation.  If any of these match, do not lower to
6102   // VPERM.
6103   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6104   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6105       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6106       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6107       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6108       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6109       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6110       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6111       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6112       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6113     return Op;
6114
6115   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6116   // perfect shuffle table to emit an optimal matching sequence.
6117   ArrayRef<int> PermMask = SVOp->getMask();
6118
6119   unsigned PFIndexes[4];
6120   bool isFourElementShuffle = true;
6121   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6122     unsigned EltNo = 8;   // Start out undef.
6123     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6124       if (PermMask[i*4+j] < 0)
6125         continue;   // Undef, ignore it.
6126
6127       unsigned ByteSource = PermMask[i*4+j];
6128       if ((ByteSource & 3) != j) {
6129         isFourElementShuffle = false;
6130         break;
6131       }
6132
6133       if (EltNo == 8) {
6134         EltNo = ByteSource/4;
6135       } else if (EltNo != ByteSource/4) {
6136         isFourElementShuffle = false;
6137         break;
6138       }
6139     }
6140     PFIndexes[i] = EltNo;
6141   }
6142
6143   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6144   // perfect shuffle vector to determine if it is cost effective to do this as
6145   // discrete instructions, or whether we should use a vperm.
6146   // For now, we skip this for little endian until such time as we have a
6147   // little-endian perfect shuffle table.
6148   if (isFourElementShuffle && !isLittleEndian) {
6149     // Compute the index in the perfect shuffle table.
6150     unsigned PFTableIndex =
6151       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6152
6153     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6154     unsigned Cost  = (PFEntry >> 30);
6155
6156     // Determining when to avoid vperm is tricky.  Many things affect the cost
6157     // of vperm, particularly how many times the perm mask needs to be computed.
6158     // For example, if the perm mask can be hoisted out of a loop or is already
6159     // used (perhaps because there are multiple permutes with the same shuffle
6160     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6161     // the loop requires an extra register.
6162     //
6163     // As a compromise, we only emit discrete instructions if the shuffle can be
6164     // generated in 3 or fewer operations.  When we have loop information
6165     // available, if this block is within a loop, we should avoid using vperm
6166     // for 3-operation perms and use a constant pool load instead.
6167     if (Cost < 3)
6168       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6169   }
6170
6171   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6172   // vector that will get spilled to the constant pool.
6173   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6174
6175   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6176   // that it is in input element units, not in bytes.  Convert now.
6177
6178   // For little endian, the order of the input vectors is reversed, and
6179   // the permutation mask is complemented with respect to 31.  This is
6180   // necessary to produce proper semantics with the big-endian-biased vperm
6181   // instruction.
6182   EVT EltVT = V1.getValueType().getVectorElementType();
6183   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6184
6185   SmallVector<SDValue, 16> ResultMask;
6186   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6187     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6188
6189     for (unsigned j = 0; j != BytesPerElement; ++j)
6190       if (isLittleEndian)
6191         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6192                                              MVT::i32));
6193       else
6194         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6195                                              MVT::i32));
6196   }
6197
6198   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6199                                   ResultMask);
6200   if (isLittleEndian)
6201     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6202                        V2, V1, VPermMask);
6203   else
6204     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6205                        V1, V2, VPermMask);
6206 }
6207
6208 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6209 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6210 /// information about the intrinsic.
6211 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6212                                   bool &isDot) {
6213   unsigned IntrinsicID =
6214     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6215   CompareOpc = -1;
6216   isDot = false;
6217   switch (IntrinsicID) {
6218   default: return false;
6219     // Comparison predicates.
6220   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6221   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6222   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6223   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6224   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6225   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6226   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6227   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6228   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6229   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6230   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6231   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6232   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6233
6234     // Normal Comparisons.
6235   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6236   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6237   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6238   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6239   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6240   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6241   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6242   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6243   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6244   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6245   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6246   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6247   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6248   }
6249   return true;
6250 }
6251
6252 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6253 /// lower, do it, otherwise return null.
6254 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6255                                                    SelectionDAG &DAG) const {
6256   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6257   // opcode number of the comparison.
6258   SDLoc dl(Op);
6259   int CompareOpc;
6260   bool isDot;
6261   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6262     return SDValue();    // Don't custom lower most intrinsics.
6263
6264   // If this is a non-dot comparison, make the VCMP node and we are done.
6265   if (!isDot) {
6266     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6267                               Op.getOperand(1), Op.getOperand(2),
6268                               DAG.getConstant(CompareOpc, MVT::i32));
6269     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6270   }
6271
6272   // Create the PPCISD altivec 'dot' comparison node.
6273   SDValue Ops[] = {
6274     Op.getOperand(2),  // LHS
6275     Op.getOperand(3),  // RHS
6276     DAG.getConstant(CompareOpc, MVT::i32)
6277   };
6278   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6279   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6280
6281   // Now that we have the comparison, emit a copy from the CR to a GPR.
6282   // This is flagged to the above dot comparison.
6283   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6284                                 DAG.getRegister(PPC::CR6, MVT::i32),
6285                                 CompNode.getValue(1));
6286
6287   // Unpack the result based on how the target uses it.
6288   unsigned BitNo;   // Bit # of CR6.
6289   bool InvertBit;   // Invert result?
6290   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6291   default:  // Can't happen, don't crash on invalid number though.
6292   case 0:   // Return the value of the EQ bit of CR6.
6293     BitNo = 0; InvertBit = false;
6294     break;
6295   case 1:   // Return the inverted value of the EQ bit of CR6.
6296     BitNo = 0; InvertBit = true;
6297     break;
6298   case 2:   // Return the value of the LT bit of CR6.
6299     BitNo = 2; InvertBit = false;
6300     break;
6301   case 3:   // Return the inverted value of the LT bit of CR6.
6302     BitNo = 2; InvertBit = true;
6303     break;
6304   }
6305
6306   // Shift the bit into the low position.
6307   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6308                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6309   // Isolate the bit.
6310   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6311                       DAG.getConstant(1, MVT::i32));
6312
6313   // If we are supposed to, toggle the bit.
6314   if (InvertBit)
6315     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6316                         DAG.getConstant(1, MVT::i32));
6317   return Flags;
6318 }
6319
6320 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6321                                                   SelectionDAG &DAG) const {
6322   SDLoc dl(Op);
6323   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6324   // instructions), but for smaller types, we need to first extend up to v2i32
6325   // before doing going farther.
6326   if (Op.getValueType() == MVT::v2i64) {
6327     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6328     if (ExtVT != MVT::v2i32) {
6329       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6330       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6331                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6332                                         ExtVT.getVectorElementType(), 4)));
6333       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6334       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6335                        DAG.getValueType(MVT::v2i32));
6336     }
6337
6338     return Op;
6339   }
6340
6341   return SDValue();
6342 }
6343
6344 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6345                                                    SelectionDAG &DAG) const {
6346   SDLoc dl(Op);
6347   // Create a stack slot that is 16-byte aligned.
6348   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6349   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6350   EVT PtrVT = getPointerTy();
6351   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6352
6353   // Store the input value into Value#0 of the stack slot.
6354   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6355                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6356                                false, false, 0);
6357   // Load it out.
6358   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6359                      false, false, false, 0);
6360 }
6361
6362 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6363   SDLoc dl(Op);
6364   if (Op.getValueType() == MVT::v4i32) {
6365     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6366
6367     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6368     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6369
6370     SDValue RHSSwap =   // = vrlw RHS, 16
6371       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6372
6373     // Shrinkify inputs to v8i16.
6374     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6375     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6376     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6377
6378     // Low parts multiplied together, generating 32-bit results (we ignore the
6379     // top parts).
6380     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6381                                         LHS, RHS, DAG, dl, MVT::v4i32);
6382
6383     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6384                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6385     // Shift the high parts up 16 bits.
6386     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6387                               Neg16, DAG, dl);
6388     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6389   } else if (Op.getValueType() == MVT::v8i16) {
6390     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6391
6392     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6393
6394     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6395                             LHS, RHS, Zero, DAG, dl);
6396   } else if (Op.getValueType() == MVT::v16i8) {
6397     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6398     bool isLittleEndian = Subtarget.isLittleEndian();
6399
6400     // Multiply the even 8-bit parts, producing 16-bit sums.
6401     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6402                                            LHS, RHS, DAG, dl, MVT::v8i16);
6403     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6404
6405     // Multiply the odd 8-bit parts, producing 16-bit sums.
6406     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6407                                           LHS, RHS, DAG, dl, MVT::v8i16);
6408     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6409
6410     // Merge the results together.  Because vmuleub and vmuloub are
6411     // instructions with a big-endian bias, we must reverse the
6412     // element numbering and reverse the meaning of "odd" and "even"
6413     // when generating little endian code.
6414     int Ops[16];
6415     for (unsigned i = 0; i != 8; ++i) {
6416       if (isLittleEndian) {
6417         Ops[i*2  ] = 2*i;
6418         Ops[i*2+1] = 2*i+16;
6419       } else {
6420         Ops[i*2  ] = 2*i+1;
6421         Ops[i*2+1] = 2*i+1+16;
6422       }
6423     }
6424     if (isLittleEndian)
6425       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6426     else
6427       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6428   } else {
6429     llvm_unreachable("Unknown mul to lower!");
6430   }
6431 }
6432
6433 /// LowerOperation - Provide custom lowering hooks for some operations.
6434 ///
6435 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6436   switch (Op.getOpcode()) {
6437   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6438   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6439   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6440   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6441   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6442   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6443   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6444   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6445   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6446   case ISD::VASTART:
6447     return LowerVASTART(Op, DAG, Subtarget);
6448
6449   case ISD::VAARG:
6450     return LowerVAARG(Op, DAG, Subtarget);
6451
6452   case ISD::VACOPY:
6453     return LowerVACOPY(Op, DAG, Subtarget);
6454
6455   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6456   case ISD::DYNAMIC_STACKALLOC:
6457     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6458
6459   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6460   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6461
6462   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6463   case ISD::STORE:              return LowerSTORE(Op, DAG);
6464   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6465   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6466   case ISD::FP_TO_UINT:
6467   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6468                                                        SDLoc(Op));
6469   case ISD::UINT_TO_FP:
6470   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6471   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6472
6473   // Lower 64-bit shifts.
6474   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6475   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6476   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6477
6478   // Vector-related lowering.
6479   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6480   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6481   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6482   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6483   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6484   case ISD::MUL:                return LowerMUL(Op, DAG);
6485
6486   // For counter-based loop handling.
6487   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6488
6489   // Frame & Return address.
6490   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6491   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6492   }
6493 }
6494
6495 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6496                                            SmallVectorImpl<SDValue>&Results,
6497                                            SelectionDAG &DAG) const {
6498   const TargetMachine &TM = getTargetMachine();
6499   SDLoc dl(N);
6500   switch (N->getOpcode()) {
6501   default:
6502     llvm_unreachable("Do not know how to custom type legalize this operation!");
6503   case ISD::READCYCLECOUNTER: {
6504     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6505     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6506
6507     Results.push_back(RTB);
6508     Results.push_back(RTB.getValue(1));
6509     Results.push_back(RTB.getValue(2));
6510     break;
6511   }
6512   case ISD::INTRINSIC_W_CHAIN: {
6513     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6514         Intrinsic::ppc_is_decremented_ctr_nonzero)
6515       break;
6516
6517     assert(N->getValueType(0) == MVT::i1 &&
6518            "Unexpected result type for CTR decrement intrinsic");
6519     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6520     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6521     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6522                                  N->getOperand(1)); 
6523
6524     Results.push_back(NewInt);
6525     Results.push_back(NewInt.getValue(1));
6526     break;
6527   }
6528   case ISD::VAARG: {
6529     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6530         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6531       return;
6532
6533     EVT VT = N->getValueType(0);
6534
6535     if (VT == MVT::i64) {
6536       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6537
6538       Results.push_back(NewNode);
6539       Results.push_back(NewNode.getValue(1));
6540     }
6541     return;
6542   }
6543   case ISD::FP_ROUND_INREG: {
6544     assert(N->getValueType(0) == MVT::ppcf128);
6545     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6546     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6547                              MVT::f64, N->getOperand(0),
6548                              DAG.getIntPtrConstant(0));
6549     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6550                              MVT::f64, N->getOperand(0),
6551                              DAG.getIntPtrConstant(1));
6552
6553     // Add the two halves of the long double in round-to-zero mode.
6554     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6555
6556     // We know the low half is about to be thrown away, so just use something
6557     // convenient.
6558     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6559                                 FPreg, FPreg));
6560     return;
6561   }
6562   case ISD::FP_TO_SINT:
6563     // LowerFP_TO_INT() can only handle f32 and f64.
6564     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6565       return;
6566     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6567     return;
6568   }
6569 }
6570
6571
6572 //===----------------------------------------------------------------------===//
6573 //  Other Lowering Code
6574 //===----------------------------------------------------------------------===//
6575
6576 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6577   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6578   Function *Func = Intrinsic::getDeclaration(M, Id);
6579   return Builder.CreateCall(Func);
6580 }
6581
6582 // The mappings for emitLeading/TrailingFence is taken from
6583 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6584 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6585                                          AtomicOrdering Ord, bool IsStore,
6586                                          bool IsLoad) const {
6587   if (Ord == SequentiallyConsistent)
6588     return callIntrinsic(Builder, Intrinsic::ppc_sync);
6589   else if (isAtLeastRelease(Ord))
6590     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6591   else
6592     return nullptr;
6593 }
6594
6595 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6596                                           AtomicOrdering Ord, bool IsStore,
6597                                           bool IsLoad) const {
6598   if (IsLoad && isAtLeastAcquire(Ord))
6599     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6600   // FIXME: this is too conservative, a dependent branch + isync is enough.
6601   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6602   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6603   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6604   else
6605     return nullptr;
6606 }
6607
6608 MachineBasicBlock *
6609 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6610                                     bool is64bit, unsigned BinOpcode) const {
6611   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6612   const TargetInstrInfo *TII =
6613       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6614
6615   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6616   MachineFunction *F = BB->getParent();
6617   MachineFunction::iterator It = BB;
6618   ++It;
6619
6620   unsigned dest = MI->getOperand(0).getReg();
6621   unsigned ptrA = MI->getOperand(1).getReg();
6622   unsigned ptrB = MI->getOperand(2).getReg();
6623   unsigned incr = MI->getOperand(3).getReg();
6624   DebugLoc dl = MI->getDebugLoc();
6625
6626   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6627   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6628   F->insert(It, loopMBB);
6629   F->insert(It, exitMBB);
6630   exitMBB->splice(exitMBB->begin(), BB,
6631                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6632   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6633
6634   MachineRegisterInfo &RegInfo = F->getRegInfo();
6635   unsigned TmpReg = (!BinOpcode) ? incr :
6636     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6637                                            : &PPC::GPRCRegClass);
6638
6639   //  thisMBB:
6640   //   ...
6641   //   fallthrough --> loopMBB
6642   BB->addSuccessor(loopMBB);
6643
6644   //  loopMBB:
6645   //   l[wd]arx dest, ptr
6646   //   add r0, dest, incr
6647   //   st[wd]cx. r0, ptr
6648   //   bne- loopMBB
6649   //   fallthrough --> exitMBB
6650   BB = loopMBB;
6651   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6652     .addReg(ptrA).addReg(ptrB);
6653   if (BinOpcode)
6654     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6655   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6656     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6657   BuildMI(BB, dl, TII->get(PPC::BCC))
6658     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6659   BB->addSuccessor(loopMBB);
6660   BB->addSuccessor(exitMBB);
6661
6662   //  exitMBB:
6663   //   ...
6664   BB = exitMBB;
6665   return BB;
6666 }
6667
6668 MachineBasicBlock *
6669 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6670                                             MachineBasicBlock *BB,
6671                                             bool is8bit,    // operation
6672                                             unsigned BinOpcode) const {
6673   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6674   const TargetInstrInfo *TII =
6675       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6676   // In 64 bit mode we have to use 64 bits for addresses, even though the
6677   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6678   // registers without caring whether they're 32 or 64, but here we're
6679   // doing actual arithmetic on the addresses.
6680   bool is64bit = Subtarget.isPPC64();
6681   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6682
6683   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6684   MachineFunction *F = BB->getParent();
6685   MachineFunction::iterator It = BB;
6686   ++It;
6687
6688   unsigned dest = MI->getOperand(0).getReg();
6689   unsigned ptrA = MI->getOperand(1).getReg();
6690   unsigned ptrB = MI->getOperand(2).getReg();
6691   unsigned incr = MI->getOperand(3).getReg();
6692   DebugLoc dl = MI->getDebugLoc();
6693
6694   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6695   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6696   F->insert(It, loopMBB);
6697   F->insert(It, exitMBB);
6698   exitMBB->splice(exitMBB->begin(), BB,
6699                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6700   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6701
6702   MachineRegisterInfo &RegInfo = F->getRegInfo();
6703   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
6704                                           : &PPC::GPRCRegClass;
6705   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6706   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6707   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6708   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6709   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6710   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6711   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6712   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6713   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6714   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6715   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6716   unsigned Ptr1Reg;
6717   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6718
6719   //  thisMBB:
6720   //   ...
6721   //   fallthrough --> loopMBB
6722   BB->addSuccessor(loopMBB);
6723
6724   // The 4-byte load must be aligned, while a char or short may be
6725   // anywhere in the word.  Hence all this nasty bookkeeping code.
6726   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6727   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6728   //   xori shift, shift1, 24 [16]
6729   //   rlwinm ptr, ptr1, 0, 0, 29
6730   //   slw incr2, incr, shift
6731   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6732   //   slw mask, mask2, shift
6733   //  loopMBB:
6734   //   lwarx tmpDest, ptr
6735   //   add tmp, tmpDest, incr2
6736   //   andc tmp2, tmpDest, mask
6737   //   and tmp3, tmp, mask
6738   //   or tmp4, tmp3, tmp2
6739   //   stwcx. tmp4, ptr
6740   //   bne- loopMBB
6741   //   fallthrough --> exitMBB
6742   //   srw dest, tmpDest, shift
6743   if (ptrA != ZeroReg) {
6744     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6745     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6746       .addReg(ptrA).addReg(ptrB);
6747   } else {
6748     Ptr1Reg = ptrB;
6749   }
6750   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6751       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6752   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6753       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6754   if (is64bit)
6755     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6756       .addReg(Ptr1Reg).addImm(0).addImm(61);
6757   else
6758     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6759       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6760   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6761       .addReg(incr).addReg(ShiftReg);
6762   if (is8bit)
6763     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6764   else {
6765     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6766     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6767   }
6768   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6769       .addReg(Mask2Reg).addReg(ShiftReg);
6770
6771   BB = loopMBB;
6772   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6773     .addReg(ZeroReg).addReg(PtrReg);
6774   if (BinOpcode)
6775     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6776       .addReg(Incr2Reg).addReg(TmpDestReg);
6777   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6778     .addReg(TmpDestReg).addReg(MaskReg);
6779   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6780     .addReg(TmpReg).addReg(MaskReg);
6781   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6782     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6783   BuildMI(BB, dl, TII->get(PPC::STWCX))
6784     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6785   BuildMI(BB, dl, TII->get(PPC::BCC))
6786     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6787   BB->addSuccessor(loopMBB);
6788   BB->addSuccessor(exitMBB);
6789
6790   //  exitMBB:
6791   //   ...
6792   BB = exitMBB;
6793   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6794     .addReg(ShiftReg);
6795   return BB;
6796 }
6797
6798 llvm::MachineBasicBlock*
6799 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6800                                     MachineBasicBlock *MBB) const {
6801   DebugLoc DL = MI->getDebugLoc();
6802   const TargetInstrInfo *TII =
6803       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6804
6805   MachineFunction *MF = MBB->getParent();
6806   MachineRegisterInfo &MRI = MF->getRegInfo();
6807
6808   const BasicBlock *BB = MBB->getBasicBlock();
6809   MachineFunction::iterator I = MBB;
6810   ++I;
6811
6812   // Memory Reference
6813   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6814   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6815
6816   unsigned DstReg = MI->getOperand(0).getReg();
6817   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6818   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6819   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6820   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6821
6822   MVT PVT = getPointerTy();
6823   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6824          "Invalid Pointer Size!");
6825   // For v = setjmp(buf), we generate
6826   //
6827   // thisMBB:
6828   //  SjLjSetup mainMBB
6829   //  bl mainMBB
6830   //  v_restore = 1
6831   //  b sinkMBB
6832   //
6833   // mainMBB:
6834   //  buf[LabelOffset] = LR
6835   //  v_main = 0
6836   //
6837   // sinkMBB:
6838   //  v = phi(main, restore)
6839   //
6840
6841   MachineBasicBlock *thisMBB = MBB;
6842   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6843   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6844   MF->insert(I, mainMBB);
6845   MF->insert(I, sinkMBB);
6846
6847   MachineInstrBuilder MIB;
6848
6849   // Transfer the remainder of BB and its successor edges to sinkMBB.
6850   sinkMBB->splice(sinkMBB->begin(), MBB,
6851                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6852   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6853
6854   // Note that the structure of the jmp_buf used here is not compatible
6855   // with that used by libc, and is not designed to be. Specifically, it
6856   // stores only those 'reserved' registers that LLVM does not otherwise
6857   // understand how to spill. Also, by convention, by the time this
6858   // intrinsic is called, Clang has already stored the frame address in the
6859   // first slot of the buffer and stack address in the third. Following the
6860   // X86 target code, we'll store the jump address in the second slot. We also
6861   // need to save the TOC pointer (R2) to handle jumps between shared
6862   // libraries, and that will be stored in the fourth slot. The thread
6863   // identifier (R13) is not affected.
6864
6865   // thisMBB:
6866   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6867   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6868   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6869
6870   // Prepare IP either in reg.
6871   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6872   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6873   unsigned BufReg = MI->getOperand(1).getReg();
6874
6875   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6876     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6877             .addReg(PPC::X2)
6878             .addImm(TOCOffset)
6879             .addReg(BufReg);
6880     MIB.setMemRefs(MMOBegin, MMOEnd);
6881   }
6882
6883   // Naked functions never have a base pointer, and so we use r1. For all
6884   // other functions, this decision must be delayed until during PEI.
6885   unsigned BaseReg;
6886   if (MF->getFunction()->getAttributes().hasAttribute(
6887           AttributeSet::FunctionIndex, Attribute::Naked))
6888     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6889   else
6890     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6891
6892   MIB = BuildMI(*thisMBB, MI, DL,
6893                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6894           .addReg(BaseReg)
6895           .addImm(BPOffset)
6896           .addReg(BufReg);
6897   MIB.setMemRefs(MMOBegin, MMOEnd);
6898
6899   // Setup
6900   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6901   const PPCRegisterInfo *TRI =
6902       getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
6903   MIB.addRegMask(TRI->getNoPreservedMask());
6904
6905   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6906
6907   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6908           .addMBB(mainMBB);
6909   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6910
6911   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6912   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6913
6914   // mainMBB:
6915   //  mainDstReg = 0
6916   MIB = BuildMI(mainMBB, DL,
6917     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6918
6919   // Store IP
6920   if (Subtarget.isPPC64()) {
6921     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6922             .addReg(LabelReg)
6923             .addImm(LabelOffset)
6924             .addReg(BufReg);
6925   } else {
6926     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6927             .addReg(LabelReg)
6928             .addImm(LabelOffset)
6929             .addReg(BufReg);
6930   }
6931
6932   MIB.setMemRefs(MMOBegin, MMOEnd);
6933
6934   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6935   mainMBB->addSuccessor(sinkMBB);
6936
6937   // sinkMBB:
6938   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6939           TII->get(PPC::PHI), DstReg)
6940     .addReg(mainDstReg).addMBB(mainMBB)
6941     .addReg(restoreDstReg).addMBB(thisMBB);
6942
6943   MI->eraseFromParent();
6944   return sinkMBB;
6945 }
6946
6947 MachineBasicBlock *
6948 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6949                                      MachineBasicBlock *MBB) const {
6950   DebugLoc DL = MI->getDebugLoc();
6951   const TargetInstrInfo *TII =
6952       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6953
6954   MachineFunction *MF = MBB->getParent();
6955   MachineRegisterInfo &MRI = MF->getRegInfo();
6956
6957   // Memory Reference
6958   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6959   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6960
6961   MVT PVT = getPointerTy();
6962   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6963          "Invalid Pointer Size!");
6964
6965   const TargetRegisterClass *RC =
6966     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6967   unsigned Tmp = MRI.createVirtualRegister(RC);
6968   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6969   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6970   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6971   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
6972                   (Subtarget.isSVR4ABI() &&
6973                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6974                      PPC::R29 : PPC::R30);
6975
6976   MachineInstrBuilder MIB;
6977
6978   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6979   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6980   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6981   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6982
6983   unsigned BufReg = MI->getOperand(0).getReg();
6984
6985   // Reload FP (the jumped-to function may not have had a
6986   // frame pointer, and if so, then its r31 will be restored
6987   // as necessary).
6988   if (PVT == MVT::i64) {
6989     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6990             .addImm(0)
6991             .addReg(BufReg);
6992   } else {
6993     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6994             .addImm(0)
6995             .addReg(BufReg);
6996   }
6997   MIB.setMemRefs(MMOBegin, MMOEnd);
6998
6999   // Reload IP
7000   if (PVT == MVT::i64) {
7001     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7002             .addImm(LabelOffset)
7003             .addReg(BufReg);
7004   } else {
7005     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7006             .addImm(LabelOffset)
7007             .addReg(BufReg);
7008   }
7009   MIB.setMemRefs(MMOBegin, MMOEnd);
7010
7011   // Reload SP
7012   if (PVT == MVT::i64) {
7013     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7014             .addImm(SPOffset)
7015             .addReg(BufReg);
7016   } else {
7017     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7018             .addImm(SPOffset)
7019             .addReg(BufReg);
7020   }
7021   MIB.setMemRefs(MMOBegin, MMOEnd);
7022
7023   // Reload BP
7024   if (PVT == MVT::i64) {
7025     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7026             .addImm(BPOffset)
7027             .addReg(BufReg);
7028   } else {
7029     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7030             .addImm(BPOffset)
7031             .addReg(BufReg);
7032   }
7033   MIB.setMemRefs(MMOBegin, MMOEnd);
7034
7035   // Reload TOC
7036   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7037     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7038             .addImm(TOCOffset)
7039             .addReg(BufReg);
7040
7041     MIB.setMemRefs(MMOBegin, MMOEnd);
7042   }
7043
7044   // Jump
7045   BuildMI(*MBB, MI, DL,
7046           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7047   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7048
7049   MI->eraseFromParent();
7050   return MBB;
7051 }
7052
7053 MachineBasicBlock *
7054 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7055                                                MachineBasicBlock *BB) const {
7056   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7057       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7058     return emitEHSjLjSetJmp(MI, BB);
7059   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7060              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7061     return emitEHSjLjLongJmp(MI, BB);
7062   }
7063
7064   const TargetInstrInfo *TII =
7065       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7066
7067   // To "insert" these instructions we actually have to insert their
7068   // control-flow patterns.
7069   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7070   MachineFunction::iterator It = BB;
7071   ++It;
7072
7073   MachineFunction *F = BB->getParent();
7074
7075   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7076                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
7077                                  MI->getOpcode() == PPC::SELECT_I4 ||
7078                                  MI->getOpcode() == PPC::SELECT_I8)) {
7079     SmallVector<MachineOperand, 2> Cond;
7080     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7081         MI->getOpcode() == PPC::SELECT_CC_I8)
7082       Cond.push_back(MI->getOperand(4));
7083     else
7084       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7085     Cond.push_back(MI->getOperand(1));
7086
7087     DebugLoc dl = MI->getDebugLoc();
7088     const TargetInstrInfo *TII =
7089         getTargetMachine().getSubtargetImpl()->getInstrInfo();
7090     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7091                       Cond, MI->getOperand(2).getReg(),
7092                       MI->getOperand(3).getReg());
7093   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7094              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7095              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7096              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7097              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7098              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7099              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7100              MI->getOpcode() == PPC::SELECT_I4 ||
7101              MI->getOpcode() == PPC::SELECT_I8 ||
7102              MI->getOpcode() == PPC::SELECT_F4 ||
7103              MI->getOpcode() == PPC::SELECT_F8 ||
7104              MI->getOpcode() == PPC::SELECT_VRRC ||
7105              MI->getOpcode() == PPC::SELECT_VSFRC ||
7106              MI->getOpcode() == PPC::SELECT_VSRC) {
7107     // The incoming instruction knows the destination vreg to set, the
7108     // condition code register to branch on, the true/false values to
7109     // select between, and a branch opcode to use.
7110
7111     //  thisMBB:
7112     //  ...
7113     //   TrueVal = ...
7114     //   cmpTY ccX, r1, r2
7115     //   bCC copy1MBB
7116     //   fallthrough --> copy0MBB
7117     MachineBasicBlock *thisMBB = BB;
7118     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7119     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7120     DebugLoc dl = MI->getDebugLoc();
7121     F->insert(It, copy0MBB);
7122     F->insert(It, sinkMBB);
7123
7124     // Transfer the remainder of BB and its successor edges to sinkMBB.
7125     sinkMBB->splice(sinkMBB->begin(), BB,
7126                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7127     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7128
7129     // Next, add the true and fallthrough blocks as its successors.
7130     BB->addSuccessor(copy0MBB);
7131     BB->addSuccessor(sinkMBB);
7132
7133     if (MI->getOpcode() == PPC::SELECT_I4 ||
7134         MI->getOpcode() == PPC::SELECT_I8 ||
7135         MI->getOpcode() == PPC::SELECT_F4 ||
7136         MI->getOpcode() == PPC::SELECT_F8 ||
7137         MI->getOpcode() == PPC::SELECT_VRRC ||
7138         MI->getOpcode() == PPC::SELECT_VSFRC ||
7139         MI->getOpcode() == PPC::SELECT_VSRC) {
7140       BuildMI(BB, dl, TII->get(PPC::BC))
7141         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7142     } else {
7143       unsigned SelectPred = MI->getOperand(4).getImm();
7144       BuildMI(BB, dl, TII->get(PPC::BCC))
7145         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7146     }
7147
7148     //  copy0MBB:
7149     //   %FalseValue = ...
7150     //   # fallthrough to sinkMBB
7151     BB = copy0MBB;
7152
7153     // Update machine-CFG edges
7154     BB->addSuccessor(sinkMBB);
7155
7156     //  sinkMBB:
7157     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7158     //  ...
7159     BB = sinkMBB;
7160     BuildMI(*BB, BB->begin(), dl,
7161             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7162       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7163       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7164   } else if (MI->getOpcode() == PPC::ReadTB) {
7165     // To read the 64-bit time-base register on a 32-bit target, we read the
7166     // two halves. Should the counter have wrapped while it was being read, we
7167     // need to try again.
7168     // ...
7169     // readLoop:
7170     // mfspr Rx,TBU # load from TBU
7171     // mfspr Ry,TB  # load from TB
7172     // mfspr Rz,TBU # load from TBU
7173     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
7174     // bne readLoop   # branch if they're not equal
7175     // ...
7176
7177     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7178     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7179     DebugLoc dl = MI->getDebugLoc();
7180     F->insert(It, readMBB);
7181     F->insert(It, sinkMBB);
7182
7183     // Transfer the remainder of BB and its successor edges to sinkMBB.
7184     sinkMBB->splice(sinkMBB->begin(), BB,
7185                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7186     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7187
7188     BB->addSuccessor(readMBB);
7189     BB = readMBB;
7190
7191     MachineRegisterInfo &RegInfo = F->getRegInfo();
7192     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7193     unsigned LoReg = MI->getOperand(0).getReg();
7194     unsigned HiReg = MI->getOperand(1).getReg();
7195
7196     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7197     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7198     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7199
7200     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7201
7202     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7203       .addReg(HiReg).addReg(ReadAgainReg);
7204     BuildMI(BB, dl, TII->get(PPC::BCC))
7205       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7206
7207     BB->addSuccessor(readMBB);
7208     BB->addSuccessor(sinkMBB);
7209   }
7210   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7211     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7212   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7213     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7214   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7215     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7216   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7217     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7218
7219   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7220     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7221   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7222     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7223   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7224     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7225   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7226     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7227
7228   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7229     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7230   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7231     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7232   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7233     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7234   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7235     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7236
7237   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7238     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7239   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7240     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7241   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7242     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7243   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7244     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7245
7246   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7247     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7248   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7249     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7250   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7251     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7252   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7253     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7254
7255   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7256     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7257   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7258     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7259   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7260     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7261   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7262     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7263
7264   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7265     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7266   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7267     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7268   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7269     BB = EmitAtomicBinary(MI, BB, false, 0);
7270   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7271     BB = EmitAtomicBinary(MI, BB, true, 0);
7272
7273   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7274            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7275     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7276
7277     unsigned dest   = MI->getOperand(0).getReg();
7278     unsigned ptrA   = MI->getOperand(1).getReg();
7279     unsigned ptrB   = MI->getOperand(2).getReg();
7280     unsigned oldval = MI->getOperand(3).getReg();
7281     unsigned newval = MI->getOperand(4).getReg();
7282     DebugLoc dl     = MI->getDebugLoc();
7283
7284     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7285     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7286     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7287     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7288     F->insert(It, loop1MBB);
7289     F->insert(It, loop2MBB);
7290     F->insert(It, midMBB);
7291     F->insert(It, exitMBB);
7292     exitMBB->splice(exitMBB->begin(), BB,
7293                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7294     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7295
7296     //  thisMBB:
7297     //   ...
7298     //   fallthrough --> loopMBB
7299     BB->addSuccessor(loop1MBB);
7300
7301     // loop1MBB:
7302     //   l[wd]arx dest, ptr
7303     //   cmp[wd] dest, oldval
7304     //   bne- midMBB
7305     // loop2MBB:
7306     //   st[wd]cx. newval, ptr
7307     //   bne- loopMBB
7308     //   b exitBB
7309     // midMBB:
7310     //   st[wd]cx. dest, ptr
7311     // exitBB:
7312     BB = loop1MBB;
7313     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7314       .addReg(ptrA).addReg(ptrB);
7315     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7316       .addReg(oldval).addReg(dest);
7317     BuildMI(BB, dl, TII->get(PPC::BCC))
7318       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7319     BB->addSuccessor(loop2MBB);
7320     BB->addSuccessor(midMBB);
7321
7322     BB = loop2MBB;
7323     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7324       .addReg(newval).addReg(ptrA).addReg(ptrB);
7325     BuildMI(BB, dl, TII->get(PPC::BCC))
7326       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7327     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7328     BB->addSuccessor(loop1MBB);
7329     BB->addSuccessor(exitMBB);
7330
7331     BB = midMBB;
7332     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7333       .addReg(dest).addReg(ptrA).addReg(ptrB);
7334     BB->addSuccessor(exitMBB);
7335
7336     //  exitMBB:
7337     //   ...
7338     BB = exitMBB;
7339   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7340              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7341     // We must use 64-bit registers for addresses when targeting 64-bit,
7342     // since we're actually doing arithmetic on them.  Other registers
7343     // can be 32-bit.
7344     bool is64bit = Subtarget.isPPC64();
7345     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7346
7347     unsigned dest   = MI->getOperand(0).getReg();
7348     unsigned ptrA   = MI->getOperand(1).getReg();
7349     unsigned ptrB   = MI->getOperand(2).getReg();
7350     unsigned oldval = MI->getOperand(3).getReg();
7351     unsigned newval = MI->getOperand(4).getReg();
7352     DebugLoc dl     = MI->getDebugLoc();
7353
7354     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7355     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7356     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7357     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7358     F->insert(It, loop1MBB);
7359     F->insert(It, loop2MBB);
7360     F->insert(It, midMBB);
7361     F->insert(It, exitMBB);
7362     exitMBB->splice(exitMBB->begin(), BB,
7363                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7364     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7365
7366     MachineRegisterInfo &RegInfo = F->getRegInfo();
7367     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7368                                             : &PPC::GPRCRegClass;
7369     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7370     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7371     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7372     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7373     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7374     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7375     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7376     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7377     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7378     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7379     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7380     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7381     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7382     unsigned Ptr1Reg;
7383     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7384     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7385     //  thisMBB:
7386     //   ...
7387     //   fallthrough --> loopMBB
7388     BB->addSuccessor(loop1MBB);
7389
7390     // The 4-byte load must be aligned, while a char or short may be
7391     // anywhere in the word.  Hence all this nasty bookkeeping code.
7392     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7393     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7394     //   xori shift, shift1, 24 [16]
7395     //   rlwinm ptr, ptr1, 0, 0, 29
7396     //   slw newval2, newval, shift
7397     //   slw oldval2, oldval,shift
7398     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7399     //   slw mask, mask2, shift
7400     //   and newval3, newval2, mask
7401     //   and oldval3, oldval2, mask
7402     // loop1MBB:
7403     //   lwarx tmpDest, ptr
7404     //   and tmp, tmpDest, mask
7405     //   cmpw tmp, oldval3
7406     //   bne- midMBB
7407     // loop2MBB:
7408     //   andc tmp2, tmpDest, mask
7409     //   or tmp4, tmp2, newval3
7410     //   stwcx. tmp4, ptr
7411     //   bne- loop1MBB
7412     //   b exitBB
7413     // midMBB:
7414     //   stwcx. tmpDest, ptr
7415     // exitBB:
7416     //   srw dest, tmpDest, shift
7417     if (ptrA != ZeroReg) {
7418       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7419       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7420         .addReg(ptrA).addReg(ptrB);
7421     } else {
7422       Ptr1Reg = ptrB;
7423     }
7424     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7425         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7426     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7427         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7428     if (is64bit)
7429       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7430         .addReg(Ptr1Reg).addImm(0).addImm(61);
7431     else
7432       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7433         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7434     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7435         .addReg(newval).addReg(ShiftReg);
7436     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7437         .addReg(oldval).addReg(ShiftReg);
7438     if (is8bit)
7439       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7440     else {
7441       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7442       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7443         .addReg(Mask3Reg).addImm(65535);
7444     }
7445     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7446         .addReg(Mask2Reg).addReg(ShiftReg);
7447     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7448         .addReg(NewVal2Reg).addReg(MaskReg);
7449     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7450         .addReg(OldVal2Reg).addReg(MaskReg);
7451
7452     BB = loop1MBB;
7453     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7454         .addReg(ZeroReg).addReg(PtrReg);
7455     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7456         .addReg(TmpDestReg).addReg(MaskReg);
7457     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7458         .addReg(TmpReg).addReg(OldVal3Reg);
7459     BuildMI(BB, dl, TII->get(PPC::BCC))
7460         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7461     BB->addSuccessor(loop2MBB);
7462     BB->addSuccessor(midMBB);
7463
7464     BB = loop2MBB;
7465     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7466         .addReg(TmpDestReg).addReg(MaskReg);
7467     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7468         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7469     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7470         .addReg(ZeroReg).addReg(PtrReg);
7471     BuildMI(BB, dl, TII->get(PPC::BCC))
7472       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7473     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7474     BB->addSuccessor(loop1MBB);
7475     BB->addSuccessor(exitMBB);
7476
7477     BB = midMBB;
7478     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7479       .addReg(ZeroReg).addReg(PtrReg);
7480     BB->addSuccessor(exitMBB);
7481
7482     //  exitMBB:
7483     //   ...
7484     BB = exitMBB;
7485     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7486       .addReg(ShiftReg);
7487   } else if (MI->getOpcode() == PPC::FADDrtz) {
7488     // This pseudo performs an FADD with rounding mode temporarily forced
7489     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7490     // is not modeled at the SelectionDAG level.
7491     unsigned Dest = MI->getOperand(0).getReg();
7492     unsigned Src1 = MI->getOperand(1).getReg();
7493     unsigned Src2 = MI->getOperand(2).getReg();
7494     DebugLoc dl   = MI->getDebugLoc();
7495
7496     MachineRegisterInfo &RegInfo = F->getRegInfo();
7497     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7498
7499     // Save FPSCR value.
7500     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7501
7502     // Set rounding mode to round-to-zero.
7503     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7504     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7505
7506     // Perform addition.
7507     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7508
7509     // Restore FPSCR value.
7510     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7511   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7512              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7513              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7514              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7515     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7516                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7517                       PPC::ANDIo8 : PPC::ANDIo;
7518     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7519                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7520
7521     MachineRegisterInfo &RegInfo = F->getRegInfo();
7522     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7523                                                   &PPC::GPRCRegClass :
7524                                                   &PPC::G8RCRegClass);
7525
7526     DebugLoc dl   = MI->getDebugLoc();
7527     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7528       .addReg(MI->getOperand(1).getReg()).addImm(1);
7529     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7530             MI->getOperand(0).getReg())
7531       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7532   } else {
7533     llvm_unreachable("Unexpected instr type to insert");
7534   }
7535
7536   MI->eraseFromParent();   // The pseudo instruction is gone now.
7537   return BB;
7538 }
7539
7540 //===----------------------------------------------------------------------===//
7541 // Target Optimization Hooks
7542 //===----------------------------------------------------------------------===//
7543
7544 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7545                                             DAGCombinerInfo &DCI,
7546                                             unsigned &RefinementSteps,
7547                                             bool &UseOneConstNR) const {
7548   EVT VT = Operand.getValueType();
7549   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7550       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7551       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7552       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7553     // Convergence is quadratic, so we essentially double the number of digits
7554     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7555     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7556     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7557     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7558     if (VT.getScalarType() == MVT::f64)
7559       ++RefinementSteps;
7560     UseOneConstNR = true;
7561     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7562   }
7563   return SDValue();
7564 }
7565
7566 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7567                                             DAGCombinerInfo &DCI,
7568                                             unsigned &RefinementSteps) const {
7569   EVT VT = Operand.getValueType();
7570   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7571       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7572       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7573       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7574     // Convergence is quadratic, so we essentially double the number of digits
7575     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7576     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7577     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7578     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7579     if (VT.getScalarType() == MVT::f64)
7580       ++RefinementSteps;
7581     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7582   }
7583   return SDValue();
7584 }
7585
7586 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7587   // Note: This functionality is used only when unsafe-fp-math is enabled, and
7588   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7589   // enabled for division), this functionality is redundant with the default
7590   // combiner logic (once the division -> reciprocal/multiply transformation
7591   // has taken place). As a result, this matters more for older cores than for
7592   // newer ones.
7593
7594   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7595   // reciprocal if there are two or more FDIVs (for embedded cores with only
7596   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7597   switch (Subtarget.getDarwinDirective()) {
7598   default:
7599     return NumUsers > 2;
7600   case PPC::DIR_440:
7601   case PPC::DIR_A2:
7602   case PPC::DIR_E500mc:
7603   case PPC::DIR_E5500:
7604     return NumUsers > 1;
7605   }
7606 }
7607
7608 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7609                             unsigned Bytes, int Dist,
7610                             SelectionDAG &DAG) {
7611   if (VT.getSizeInBits() / 8 != Bytes)
7612     return false;
7613
7614   SDValue BaseLoc = Base->getBasePtr();
7615   if (Loc.getOpcode() == ISD::FrameIndex) {
7616     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7617       return false;
7618     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7619     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7620     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7621     int FS  = MFI->getObjectSize(FI);
7622     int BFS = MFI->getObjectSize(BFI);
7623     if (FS != BFS || FS != (int)Bytes) return false;
7624     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7625   }
7626
7627   // Handle X+C
7628   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7629       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7630     return true;
7631
7632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7633   const GlobalValue *GV1 = nullptr;
7634   const GlobalValue *GV2 = nullptr;
7635   int64_t Offset1 = 0;
7636   int64_t Offset2 = 0;
7637   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7638   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7639   if (isGA1 && isGA2 && GV1 == GV2)
7640     return Offset1 == (Offset2 + Dist*Bytes);
7641   return false;
7642 }
7643
7644 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7645 // not enforce equality of the chain operands.
7646 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7647                             unsigned Bytes, int Dist,
7648                             SelectionDAG &DAG) {
7649   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7650     EVT VT = LS->getMemoryVT();
7651     SDValue Loc = LS->getBasePtr();
7652     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7653   }
7654
7655   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7656     EVT VT;
7657     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7658     default: return false;
7659     case Intrinsic::ppc_altivec_lvx:
7660     case Intrinsic::ppc_altivec_lvxl:
7661     case Intrinsic::ppc_vsx_lxvw4x:
7662       VT = MVT::v4i32;
7663       break;
7664     case Intrinsic::ppc_vsx_lxvd2x:
7665       VT = MVT::v2f64;
7666       break;
7667     case Intrinsic::ppc_altivec_lvebx:
7668       VT = MVT::i8;
7669       break;
7670     case Intrinsic::ppc_altivec_lvehx:
7671       VT = MVT::i16;
7672       break;
7673     case Intrinsic::ppc_altivec_lvewx:
7674       VT = MVT::i32;
7675       break;
7676     }
7677
7678     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7679   }
7680
7681   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7682     EVT VT;
7683     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7684     default: return false;
7685     case Intrinsic::ppc_altivec_stvx:
7686     case Intrinsic::ppc_altivec_stvxl:
7687     case Intrinsic::ppc_vsx_stxvw4x:
7688       VT = MVT::v4i32;
7689       break;
7690     case Intrinsic::ppc_vsx_stxvd2x:
7691       VT = MVT::v2f64;
7692       break;
7693     case Intrinsic::ppc_altivec_stvebx:
7694       VT = MVT::i8;
7695       break;
7696     case Intrinsic::ppc_altivec_stvehx:
7697       VT = MVT::i16;
7698       break;
7699     case Intrinsic::ppc_altivec_stvewx:
7700       VT = MVT::i32;
7701       break;
7702     }
7703
7704     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7705   }
7706
7707   return false;
7708 }
7709
7710 // Return true is there is a nearyby consecutive load to the one provided
7711 // (regardless of alignment). We search up and down the chain, looking though
7712 // token factors and other loads (but nothing else). As a result, a true result
7713 // indicates that it is safe to create a new consecutive load adjacent to the
7714 // load provided.
7715 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7716   SDValue Chain = LD->getChain();
7717   EVT VT = LD->getMemoryVT();
7718
7719   SmallSet<SDNode *, 16> LoadRoots;
7720   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7721   SmallSet<SDNode *, 16> Visited;
7722
7723   // First, search up the chain, branching to follow all token-factor operands.
7724   // If we find a consecutive load, then we're done, otherwise, record all
7725   // nodes just above the top-level loads and token factors.
7726   while (!Queue.empty()) {
7727     SDNode *ChainNext = Queue.pop_back_val();
7728     if (!Visited.insert(ChainNext).second)
7729       continue;
7730
7731     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7732       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7733         return true;
7734
7735       if (!Visited.count(ChainLD->getChain().getNode()))
7736         Queue.push_back(ChainLD->getChain().getNode());
7737     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7738       for (const SDUse &O : ChainNext->ops())
7739         if (!Visited.count(O.getNode()))
7740           Queue.push_back(O.getNode());
7741     } else
7742       LoadRoots.insert(ChainNext);
7743   }
7744
7745   // Second, search down the chain, starting from the top-level nodes recorded
7746   // in the first phase. These top-level nodes are the nodes just above all
7747   // loads and token factors. Starting with their uses, recursively look though
7748   // all loads (just the chain uses) and token factors to find a consecutive
7749   // load.
7750   Visited.clear();
7751   Queue.clear();
7752
7753   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7754        IE = LoadRoots.end(); I != IE; ++I) {
7755     Queue.push_back(*I);
7756        
7757     while (!Queue.empty()) {
7758       SDNode *LoadRoot = Queue.pop_back_val();
7759       if (!Visited.insert(LoadRoot).second)
7760         continue;
7761
7762       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7763         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7764           return true;
7765
7766       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7767            UE = LoadRoot->use_end(); UI != UE; ++UI)
7768         if (((isa<MemSDNode>(*UI) &&
7769             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7770             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7771           Queue.push_back(*UI);
7772     }
7773   }
7774
7775   return false;
7776 }
7777
7778 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7779                                                   DAGCombinerInfo &DCI) const {
7780   SelectionDAG &DAG = DCI.DAG;
7781   SDLoc dl(N);
7782
7783   assert(Subtarget.useCRBits() &&
7784          "Expecting to be tracking CR bits");
7785   // If we're tracking CR bits, we need to be careful that we don't have:
7786   //   trunc(binary-ops(zext(x), zext(y)))
7787   // or
7788   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7789   // such that we're unnecessarily moving things into GPRs when it would be
7790   // better to keep them in CR bits.
7791
7792   // Note that trunc here can be an actual i1 trunc, or can be the effective
7793   // truncation that comes from a setcc or select_cc.
7794   if (N->getOpcode() == ISD::TRUNCATE &&
7795       N->getValueType(0) != MVT::i1)
7796     return SDValue();
7797
7798   if (N->getOperand(0).getValueType() != MVT::i32 &&
7799       N->getOperand(0).getValueType() != MVT::i64)
7800     return SDValue();
7801
7802   if (N->getOpcode() == ISD::SETCC ||
7803       N->getOpcode() == ISD::SELECT_CC) {
7804     // If we're looking at a comparison, then we need to make sure that the
7805     // high bits (all except for the first) don't matter the result.
7806     ISD::CondCode CC =
7807       cast<CondCodeSDNode>(N->getOperand(
7808         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7809     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7810
7811     if (ISD::isSignedIntSetCC(CC)) {
7812       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7813           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7814         return SDValue();
7815     } else if (ISD::isUnsignedIntSetCC(CC)) {
7816       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7817                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7818           !DAG.MaskedValueIsZero(N->getOperand(1),
7819                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7820         return SDValue();
7821     } else {
7822       // This is neither a signed nor an unsigned comparison, just make sure
7823       // that the high bits are equal.
7824       APInt Op1Zero, Op1One;
7825       APInt Op2Zero, Op2One;
7826       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7827       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7828
7829       // We don't really care about what is known about the first bit (if
7830       // anything), so clear it in all masks prior to comparing them.
7831       Op1Zero.clearBit(0); Op1One.clearBit(0);
7832       Op2Zero.clearBit(0); Op2One.clearBit(0);
7833
7834       if (Op1Zero != Op2Zero || Op1One != Op2One)
7835         return SDValue();
7836     }
7837   }
7838
7839   // We now know that the higher-order bits are irrelevant, we just need to
7840   // make sure that all of the intermediate operations are bit operations, and
7841   // all inputs are extensions.
7842   if (N->getOperand(0).getOpcode() != ISD::AND &&
7843       N->getOperand(0).getOpcode() != ISD::OR  &&
7844       N->getOperand(0).getOpcode() != ISD::XOR &&
7845       N->getOperand(0).getOpcode() != ISD::SELECT &&
7846       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7847       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7848       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7849       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7850       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7851     return SDValue();
7852
7853   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7854       N->getOperand(1).getOpcode() != ISD::AND &&
7855       N->getOperand(1).getOpcode() != ISD::OR  &&
7856       N->getOperand(1).getOpcode() != ISD::XOR &&
7857       N->getOperand(1).getOpcode() != ISD::SELECT &&
7858       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7859       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7860       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7861       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7862       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7863     return SDValue();
7864
7865   SmallVector<SDValue, 4> Inputs;
7866   SmallVector<SDValue, 8> BinOps, PromOps;
7867   SmallPtrSet<SDNode *, 16> Visited;
7868
7869   for (unsigned i = 0; i < 2; ++i) {
7870     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7871           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7872           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7873           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7874         isa<ConstantSDNode>(N->getOperand(i)))
7875       Inputs.push_back(N->getOperand(i));
7876     else
7877       BinOps.push_back(N->getOperand(i));
7878
7879     if (N->getOpcode() == ISD::TRUNCATE)
7880       break;
7881   }
7882
7883   // Visit all inputs, collect all binary operations (and, or, xor and
7884   // select) that are all fed by extensions. 
7885   while (!BinOps.empty()) {
7886     SDValue BinOp = BinOps.back();
7887     BinOps.pop_back();
7888
7889     if (!Visited.insert(BinOp.getNode()).second)
7890       continue;
7891
7892     PromOps.push_back(BinOp);
7893
7894     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7895       // The condition of the select is not promoted.
7896       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7897         continue;
7898       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7899         continue;
7900
7901       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7902             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7903             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7904            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7905           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7906         Inputs.push_back(BinOp.getOperand(i)); 
7907       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7908                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7909                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7910                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7911                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7912                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7913                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7914                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7915                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7916         BinOps.push_back(BinOp.getOperand(i));
7917       } else {
7918         // We have an input that is not an extension or another binary
7919         // operation; we'll abort this transformation.
7920         return SDValue();
7921       }
7922     }
7923   }
7924
7925   // Make sure that this is a self-contained cluster of operations (which
7926   // is not quite the same thing as saying that everything has only one
7927   // use).
7928   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7929     if (isa<ConstantSDNode>(Inputs[i]))
7930       continue;
7931
7932     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7933                               UE = Inputs[i].getNode()->use_end();
7934          UI != UE; ++UI) {
7935       SDNode *User = *UI;
7936       if (User != N && !Visited.count(User))
7937         return SDValue();
7938
7939       // Make sure that we're not going to promote the non-output-value
7940       // operand(s) or SELECT or SELECT_CC.
7941       // FIXME: Although we could sometimes handle this, and it does occur in
7942       // practice that one of the condition inputs to the select is also one of
7943       // the outputs, we currently can't deal with this.
7944       if (User->getOpcode() == ISD::SELECT) {
7945         if (User->getOperand(0) == Inputs[i])
7946           return SDValue();
7947       } else if (User->getOpcode() == ISD::SELECT_CC) {
7948         if (User->getOperand(0) == Inputs[i] ||
7949             User->getOperand(1) == Inputs[i])
7950           return SDValue();
7951       }
7952     }
7953   }
7954
7955   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7956     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7957                               UE = PromOps[i].getNode()->use_end();
7958          UI != UE; ++UI) {
7959       SDNode *User = *UI;
7960       if (User != N && !Visited.count(User))
7961         return SDValue();
7962
7963       // Make sure that we're not going to promote the non-output-value
7964       // operand(s) or SELECT or SELECT_CC.
7965       // FIXME: Although we could sometimes handle this, and it does occur in
7966       // practice that one of the condition inputs to the select is also one of
7967       // the outputs, we currently can't deal with this.
7968       if (User->getOpcode() == ISD::SELECT) {
7969         if (User->getOperand(0) == PromOps[i])
7970           return SDValue();
7971       } else if (User->getOpcode() == ISD::SELECT_CC) {
7972         if (User->getOperand(0) == PromOps[i] ||
7973             User->getOperand(1) == PromOps[i])
7974           return SDValue();
7975       }
7976     }
7977   }
7978
7979   // Replace all inputs with the extension operand.
7980   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7981     // Constants may have users outside the cluster of to-be-promoted nodes,
7982     // and so we need to replace those as we do the promotions.
7983     if (isa<ConstantSDNode>(Inputs[i]))
7984       continue;
7985     else
7986       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
7987   }
7988
7989   // Replace all operations (these are all the same, but have a different
7990   // (i1) return type). DAG.getNode will validate that the types of
7991   // a binary operator match, so go through the list in reverse so that
7992   // we've likely promoted both operands first. Any intermediate truncations or
7993   // extensions disappear.
7994   while (!PromOps.empty()) {
7995     SDValue PromOp = PromOps.back();
7996     PromOps.pop_back();
7997
7998     if (PromOp.getOpcode() == ISD::TRUNCATE ||
7999         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8000         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8001         PromOp.getOpcode() == ISD::ANY_EXTEND) {
8002       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8003           PromOp.getOperand(0).getValueType() != MVT::i1) {
8004         // The operand is not yet ready (see comment below).
8005         PromOps.insert(PromOps.begin(), PromOp);
8006         continue;
8007       }
8008
8009       SDValue RepValue = PromOp.getOperand(0);
8010       if (isa<ConstantSDNode>(RepValue))
8011         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8012
8013       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8014       continue;
8015     }
8016
8017     unsigned C;
8018     switch (PromOp.getOpcode()) {
8019     default:             C = 0; break;
8020     case ISD::SELECT:    C = 1; break;
8021     case ISD::SELECT_CC: C = 2; break;
8022     }
8023
8024     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8025          PromOp.getOperand(C).getValueType() != MVT::i1) ||
8026         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8027          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8028       // The to-be-promoted operands of this node have not yet been
8029       // promoted (this should be rare because we're going through the
8030       // list backward, but if one of the operands has several users in
8031       // this cluster of to-be-promoted nodes, it is possible).
8032       PromOps.insert(PromOps.begin(), PromOp);
8033       continue;
8034     }
8035
8036     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8037                                 PromOp.getNode()->op_end());
8038
8039     // If there are any constant inputs, make sure they're replaced now.
8040     for (unsigned i = 0; i < 2; ++i)
8041       if (isa<ConstantSDNode>(Ops[C+i]))
8042         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8043
8044     DAG.ReplaceAllUsesOfValueWith(PromOp,
8045       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8046   }
8047
8048   // Now we're left with the initial truncation itself.
8049   if (N->getOpcode() == ISD::TRUNCATE)
8050     return N->getOperand(0);
8051
8052   // Otherwise, this is a comparison. The operands to be compared have just
8053   // changed type (to i1), but everything else is the same.
8054   return SDValue(N, 0);
8055 }
8056
8057 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8058                                                   DAGCombinerInfo &DCI) const {
8059   SelectionDAG &DAG = DCI.DAG;
8060   SDLoc dl(N);
8061
8062   // If we're tracking CR bits, we need to be careful that we don't have:
8063   //   zext(binary-ops(trunc(x), trunc(y)))
8064   // or
8065   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8066   // such that we're unnecessarily moving things into CR bits that can more
8067   // efficiently stay in GPRs. Note that if we're not certain that the high
8068   // bits are set as required by the final extension, we still may need to do
8069   // some masking to get the proper behavior.
8070
8071   // This same functionality is important on PPC64 when dealing with
8072   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8073   // the return values of functions. Because it is so similar, it is handled
8074   // here as well.
8075
8076   if (N->getValueType(0) != MVT::i32 &&
8077       N->getValueType(0) != MVT::i64)
8078     return SDValue();
8079
8080   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8081         Subtarget.useCRBits()) ||
8082        (N->getOperand(0).getValueType() == MVT::i32 &&
8083         Subtarget.isPPC64())))
8084     return SDValue();
8085
8086   if (N->getOperand(0).getOpcode() != ISD::AND &&
8087       N->getOperand(0).getOpcode() != ISD::OR  &&
8088       N->getOperand(0).getOpcode() != ISD::XOR &&
8089       N->getOperand(0).getOpcode() != ISD::SELECT &&
8090       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8091     return SDValue();
8092
8093   SmallVector<SDValue, 4> Inputs;
8094   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8095   SmallPtrSet<SDNode *, 16> Visited;
8096
8097   // Visit all inputs, collect all binary operations (and, or, xor and
8098   // select) that are all fed by truncations. 
8099   while (!BinOps.empty()) {
8100     SDValue BinOp = BinOps.back();
8101     BinOps.pop_back();
8102
8103     if (!Visited.insert(BinOp.getNode()).second)
8104       continue;
8105
8106     PromOps.push_back(BinOp);
8107
8108     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8109       // The condition of the select is not promoted.
8110       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8111         continue;
8112       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8113         continue;
8114
8115       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8116           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8117         Inputs.push_back(BinOp.getOperand(i)); 
8118       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8119                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8120                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8121                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8122                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8123         BinOps.push_back(BinOp.getOperand(i));
8124       } else {
8125         // We have an input that is not a truncation or another binary
8126         // operation; we'll abort this transformation.
8127         return SDValue();
8128       }
8129     }
8130   }
8131
8132   // Make sure that this is a self-contained cluster of operations (which
8133   // is not quite the same thing as saying that everything has only one
8134   // use).
8135   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8136     if (isa<ConstantSDNode>(Inputs[i]))
8137       continue;
8138
8139     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8140                               UE = Inputs[i].getNode()->use_end();
8141          UI != UE; ++UI) {
8142       SDNode *User = *UI;
8143       if (User != N && !Visited.count(User))
8144         return SDValue();
8145
8146       // Make sure that we're not going to promote the non-output-value
8147       // operand(s) or SELECT or SELECT_CC.
8148       // FIXME: Although we could sometimes handle this, and it does occur in
8149       // practice that one of the condition inputs to the select is also one of
8150       // the outputs, we currently can't deal with this.
8151       if (User->getOpcode() == ISD::SELECT) {
8152         if (User->getOperand(0) == Inputs[i])
8153           return SDValue();
8154       } else if (User->getOpcode() == ISD::SELECT_CC) {
8155         if (User->getOperand(0) == Inputs[i] ||
8156             User->getOperand(1) == Inputs[i])
8157           return SDValue();
8158       }
8159     }
8160   }
8161
8162   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8163     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8164                               UE = PromOps[i].getNode()->use_end();
8165          UI != UE; ++UI) {
8166       SDNode *User = *UI;
8167       if (User != N && !Visited.count(User))
8168         return SDValue();
8169
8170       // Make sure that we're not going to promote the non-output-value
8171       // operand(s) or SELECT or SELECT_CC.
8172       // FIXME: Although we could sometimes handle this, and it does occur in
8173       // practice that one of the condition inputs to the select is also one of
8174       // the outputs, we currently can't deal with this.
8175       if (User->getOpcode() == ISD::SELECT) {
8176         if (User->getOperand(0) == PromOps[i])
8177           return SDValue();
8178       } else if (User->getOpcode() == ISD::SELECT_CC) {
8179         if (User->getOperand(0) == PromOps[i] ||
8180             User->getOperand(1) == PromOps[i])
8181           return SDValue();
8182       }
8183     }
8184   }
8185
8186   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8187   bool ReallyNeedsExt = false;
8188   if (N->getOpcode() != ISD::ANY_EXTEND) {
8189     // If all of the inputs are not already sign/zero extended, then
8190     // we'll still need to do that at the end.
8191     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8192       if (isa<ConstantSDNode>(Inputs[i]))
8193         continue;
8194
8195       unsigned OpBits =
8196         Inputs[i].getOperand(0).getValueSizeInBits();
8197       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8198
8199       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8200            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8201                                   APInt::getHighBitsSet(OpBits,
8202                                                         OpBits-PromBits))) ||
8203           (N->getOpcode() == ISD::SIGN_EXTEND &&
8204            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8205              (OpBits-(PromBits-1)))) {
8206         ReallyNeedsExt = true;
8207         break;
8208       }
8209     }
8210   }
8211
8212   // Replace all inputs, either with the truncation operand, or a
8213   // truncation or extension to the final output type.
8214   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8215     // Constant inputs need to be replaced with the to-be-promoted nodes that
8216     // use them because they might have users outside of the cluster of
8217     // promoted nodes.
8218     if (isa<ConstantSDNode>(Inputs[i]))
8219       continue;
8220
8221     SDValue InSrc = Inputs[i].getOperand(0);
8222     if (Inputs[i].getValueType() == N->getValueType(0))
8223       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8224     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8225       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8226         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8227     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8228       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8229         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8230     else
8231       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8232         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8233   }
8234
8235   // Replace all operations (these are all the same, but have a different
8236   // (promoted) return type). DAG.getNode will validate that the types of
8237   // a binary operator match, so go through the list in reverse so that
8238   // we've likely promoted both operands first.
8239   while (!PromOps.empty()) {
8240     SDValue PromOp = PromOps.back();
8241     PromOps.pop_back();
8242
8243     unsigned C;
8244     switch (PromOp.getOpcode()) {
8245     default:             C = 0; break;
8246     case ISD::SELECT:    C = 1; break;
8247     case ISD::SELECT_CC: C = 2; break;
8248     }
8249
8250     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8251          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8252         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8253          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8254       // The to-be-promoted operands of this node have not yet been
8255       // promoted (this should be rare because we're going through the
8256       // list backward, but if one of the operands has several users in
8257       // this cluster of to-be-promoted nodes, it is possible).
8258       PromOps.insert(PromOps.begin(), PromOp);
8259       continue;
8260     }
8261
8262     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8263                                 PromOp.getNode()->op_end());
8264
8265     // If this node has constant inputs, then they'll need to be promoted here.
8266     for (unsigned i = 0; i < 2; ++i) {
8267       if (!isa<ConstantSDNode>(Ops[C+i]))
8268         continue;
8269       if (Ops[C+i].getValueType() == N->getValueType(0))
8270         continue;
8271
8272       if (N->getOpcode() == ISD::SIGN_EXTEND)
8273         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8274       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8275         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8276       else
8277         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8278     }
8279
8280     DAG.ReplaceAllUsesOfValueWith(PromOp,
8281       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8282   }
8283
8284   // Now we're left with the initial extension itself.
8285   if (!ReallyNeedsExt)
8286     return N->getOperand(0);
8287
8288   // To zero extend, just mask off everything except for the first bit (in the
8289   // i1 case).
8290   if (N->getOpcode() == ISD::ZERO_EXTEND)
8291     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8292                        DAG.getConstant(APInt::getLowBitsSet(
8293                                          N->getValueSizeInBits(0), PromBits),
8294                                        N->getValueType(0)));
8295
8296   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8297          "Invalid extension type");
8298   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8299   SDValue ShiftCst =
8300     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8301   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8302                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8303                                  N->getOperand(0), ShiftCst), ShiftCst);
8304 }
8305
8306 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8307 // builtins) into loads with swaps.
8308 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8309                                               DAGCombinerInfo &DCI) const {
8310   SelectionDAG &DAG = DCI.DAG;
8311   SDLoc dl(N);
8312   SDValue Chain;
8313   SDValue Base;
8314   MachineMemOperand *MMO;
8315
8316   switch (N->getOpcode()) {
8317   default:
8318     llvm_unreachable("Unexpected opcode for little endian VSX load");
8319   case ISD::LOAD: {
8320     LoadSDNode *LD = cast<LoadSDNode>(N);
8321     Chain = LD->getChain();
8322     Base = LD->getBasePtr();
8323     MMO = LD->getMemOperand();
8324     // If the MMO suggests this isn't a load of a full vector, leave
8325     // things alone.  For a built-in, we have to make the change for
8326     // correctness, so if there is a size problem that will be a bug.
8327     if (MMO->getSize() < 16)
8328       return SDValue();
8329     break;
8330   }
8331   case ISD::INTRINSIC_W_CHAIN: {
8332     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8333     Chain = Intrin->getChain();
8334     Base = Intrin->getBasePtr();
8335     MMO = Intrin->getMemOperand();
8336     break;
8337   }
8338   }
8339
8340   MVT VecTy = N->getValueType(0).getSimpleVT();
8341   SDValue LoadOps[] = { Chain, Base };
8342   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8343                                          DAG.getVTList(VecTy, MVT::Other),
8344                                          LoadOps, VecTy, MMO);
8345   DCI.AddToWorklist(Load.getNode());
8346   Chain = Load.getValue(1);
8347   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8348                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8349   DCI.AddToWorklist(Swap.getNode());
8350   return Swap;
8351 }
8352
8353 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8354 // builtins) into stores with swaps.
8355 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8356                                                DAGCombinerInfo &DCI) const {
8357   SelectionDAG &DAG = DCI.DAG;
8358   SDLoc dl(N);
8359   SDValue Chain;
8360   SDValue Base;
8361   unsigned SrcOpnd;
8362   MachineMemOperand *MMO;
8363
8364   switch (N->getOpcode()) {
8365   default:
8366     llvm_unreachable("Unexpected opcode for little endian VSX store");
8367   case ISD::STORE: {
8368     StoreSDNode *ST = cast<StoreSDNode>(N);
8369     Chain = ST->getChain();
8370     Base = ST->getBasePtr();
8371     MMO = ST->getMemOperand();
8372     SrcOpnd = 1;
8373     // If the MMO suggests this isn't a store of a full vector, leave
8374     // things alone.  For a built-in, we have to make the change for
8375     // correctness, so if there is a size problem that will be a bug.
8376     if (MMO->getSize() < 16)
8377       return SDValue();
8378     break;
8379   }
8380   case ISD::INTRINSIC_VOID: {
8381     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8382     Chain = Intrin->getChain();
8383     // Intrin->getBasePtr() oddly does not get what we want.
8384     Base = Intrin->getOperand(3);
8385     MMO = Intrin->getMemOperand();
8386     SrcOpnd = 2;
8387     break;
8388   }
8389   }
8390
8391   SDValue Src = N->getOperand(SrcOpnd);
8392   MVT VecTy = Src.getValueType().getSimpleVT();
8393   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8394                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8395   DCI.AddToWorklist(Swap.getNode());
8396   Chain = Swap.getValue(1);
8397   SDValue StoreOps[] = { Chain, Swap, Base };
8398   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8399                                           DAG.getVTList(MVT::Other),
8400                                           StoreOps, VecTy, MMO);
8401   DCI.AddToWorklist(Store.getNode());
8402   return Store;
8403 }
8404
8405 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8406                                              DAGCombinerInfo &DCI) const {
8407   const TargetMachine &TM = getTargetMachine();
8408   SelectionDAG &DAG = DCI.DAG;
8409   SDLoc dl(N);
8410   switch (N->getOpcode()) {
8411   default: break;
8412   case PPCISD::SHL:
8413     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8414       if (C->isNullValue())   // 0 << V -> 0.
8415         return N->getOperand(0);
8416     }
8417     break;
8418   case PPCISD::SRL:
8419     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8420       if (C->isNullValue())   // 0 >>u V -> 0.
8421         return N->getOperand(0);
8422     }
8423     break;
8424   case PPCISD::SRA:
8425     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8426       if (C->isNullValue() ||   //  0 >>s V -> 0.
8427           C->isAllOnesValue())    // -1 >>s V -> -1.
8428         return N->getOperand(0);
8429     }
8430     break;
8431   case ISD::SIGN_EXTEND:
8432   case ISD::ZERO_EXTEND:
8433   case ISD::ANY_EXTEND: 
8434     return DAGCombineExtBoolTrunc(N, DCI);
8435   case ISD::TRUNCATE:
8436   case ISD::SETCC:
8437   case ISD::SELECT_CC:
8438     return DAGCombineTruncBoolExt(N, DCI);
8439   case ISD::SINT_TO_FP:
8440     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8441       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8442         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8443         // We allow the src/dst to be either f32/f64, but the intermediate
8444         // type must be i64.
8445         if (N->getOperand(0).getValueType() == MVT::i64 &&
8446             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8447           SDValue Val = N->getOperand(0).getOperand(0);
8448           if (Val.getValueType() == MVT::f32) {
8449             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8450             DCI.AddToWorklist(Val.getNode());
8451           }
8452
8453           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8454           DCI.AddToWorklist(Val.getNode());
8455           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8456           DCI.AddToWorklist(Val.getNode());
8457           if (N->getValueType(0) == MVT::f32) {
8458             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8459                               DAG.getIntPtrConstant(0));
8460             DCI.AddToWorklist(Val.getNode());
8461           }
8462           return Val;
8463         } else if (N->getOperand(0).getValueType() == MVT::i32) {
8464           // If the intermediate type is i32, we can avoid the load/store here
8465           // too.
8466         }
8467       }
8468     }
8469     break;
8470   case ISD::STORE: {
8471     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8472     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8473         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8474         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8475         N->getOperand(1).getValueType() == MVT::i32 &&
8476         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8477       SDValue Val = N->getOperand(1).getOperand(0);
8478       if (Val.getValueType() == MVT::f32) {
8479         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8480         DCI.AddToWorklist(Val.getNode());
8481       }
8482       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8483       DCI.AddToWorklist(Val.getNode());
8484
8485       SDValue Ops[] = {
8486         N->getOperand(0), Val, N->getOperand(2),
8487         DAG.getValueType(N->getOperand(1).getValueType())
8488       };
8489
8490       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8491               DAG.getVTList(MVT::Other), Ops,
8492               cast<StoreSDNode>(N)->getMemoryVT(),
8493               cast<StoreSDNode>(N)->getMemOperand());
8494       DCI.AddToWorklist(Val.getNode());
8495       return Val;
8496     }
8497
8498     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8499     if (cast<StoreSDNode>(N)->isUnindexed() &&
8500         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8501         N->getOperand(1).getNode()->hasOneUse() &&
8502         (N->getOperand(1).getValueType() == MVT::i32 ||
8503          N->getOperand(1).getValueType() == MVT::i16 ||
8504          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8505           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8506           N->getOperand(1).getValueType() == MVT::i64))) {
8507       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8508       // Do an any-extend to 32-bits if this is a half-word input.
8509       if (BSwapOp.getValueType() == MVT::i16)
8510         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8511
8512       SDValue Ops[] = {
8513         N->getOperand(0), BSwapOp, N->getOperand(2),
8514         DAG.getValueType(N->getOperand(1).getValueType())
8515       };
8516       return
8517         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8518                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8519                                 cast<StoreSDNode>(N)->getMemOperand());
8520     }
8521
8522     // For little endian, VSX stores require generating xxswapd/lxvd2x.
8523     EVT VT = N->getOperand(1).getValueType();
8524     if (VT.isSimple()) {
8525       MVT StoreVT = VT.getSimpleVT();
8526       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8527           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8528           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8529            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8530         return expandVSXStoreForLE(N, DCI);
8531     }
8532     break;
8533   }
8534   case ISD::LOAD: {
8535     LoadSDNode *LD = cast<LoadSDNode>(N);
8536     EVT VT = LD->getValueType(0);
8537
8538     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8539     if (VT.isSimple()) {
8540       MVT LoadVT = VT.getSimpleVT();
8541       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8542           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8543           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8544            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8545         return expandVSXLoadForLE(N, DCI);
8546     }
8547
8548     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8549     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8550     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8551         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8552         // P8 and later hardware should just use LOAD.
8553         !TM.getSubtarget<PPCSubtarget>().hasP8Vector() &&
8554         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8555          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8556         LD->getAlignment() < ABIAlignment) {
8557       // This is a type-legal unaligned Altivec load.
8558       SDValue Chain = LD->getChain();
8559       SDValue Ptr = LD->getBasePtr();
8560       bool isLittleEndian = Subtarget.isLittleEndian();
8561
8562       // This implements the loading of unaligned vectors as described in
8563       // the venerable Apple Velocity Engine overview. Specifically:
8564       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8565       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8566       //
8567       // The general idea is to expand a sequence of one or more unaligned
8568       // loads into an alignment-based permutation-control instruction (lvsl
8569       // or lvsr), a series of regular vector loads (which always truncate
8570       // their input address to an aligned address), and a series of
8571       // permutations.  The results of these permutations are the requested
8572       // loaded values.  The trick is that the last "extra" load is not taken
8573       // from the address you might suspect (sizeof(vector) bytes after the
8574       // last requested load), but rather sizeof(vector) - 1 bytes after the
8575       // last requested vector. The point of this is to avoid a page fault if
8576       // the base address happened to be aligned. This works because if the
8577       // base address is aligned, then adding less than a full vector length
8578       // will cause the last vector in the sequence to be (re)loaded.
8579       // Otherwise, the next vector will be fetched as you might suspect was
8580       // necessary.
8581
8582       // We might be able to reuse the permutation generation from
8583       // a different base address offset from this one by an aligned amount.
8584       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8585       // optimization later.
8586       Intrinsic::ID Intr = (isLittleEndian ?
8587                             Intrinsic::ppc_altivec_lvsr :
8588                             Intrinsic::ppc_altivec_lvsl);
8589       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8590
8591       // Create the new MMO for the new base load. It is like the original MMO,
8592       // but represents an area in memory almost twice the vector size centered
8593       // on the original address. If the address is unaligned, we might start
8594       // reading up to (sizeof(vector)-1) bytes below the address of the
8595       // original unaligned load.
8596       MachineFunction &MF = DAG.getMachineFunction();
8597       MachineMemOperand *BaseMMO =
8598         MF.getMachineMemOperand(LD->getMemOperand(),
8599                                 -LD->getMemoryVT().getStoreSize()+1,
8600                                 2*LD->getMemoryVT().getStoreSize()-1);
8601
8602       // Create the new base load.
8603       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8604                                                getPointerTy());
8605       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8606       SDValue BaseLoad =
8607         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8608                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8609                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8610
8611       // Note that the value of IncOffset (which is provided to the next
8612       // load's pointer info offset value, and thus used to calculate the
8613       // alignment), and the value of IncValue (which is actually used to
8614       // increment the pointer value) are different! This is because we
8615       // require the next load to appear to be aligned, even though it
8616       // is actually offset from the base pointer by a lesser amount.
8617       int IncOffset = VT.getSizeInBits() / 8;
8618       int IncValue = IncOffset;
8619
8620       // Walk (both up and down) the chain looking for another load at the real
8621       // (aligned) offset (the alignment of the other load does not matter in
8622       // this case). If found, then do not use the offset reduction trick, as
8623       // that will prevent the loads from being later combined (as they would
8624       // otherwise be duplicates).
8625       if (!findConsecutiveLoad(LD, DAG))
8626         --IncValue;
8627
8628       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8629       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8630
8631       MachineMemOperand *ExtraMMO =
8632         MF.getMachineMemOperand(LD->getMemOperand(),
8633                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
8634       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8635       SDValue ExtraLoad =
8636         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8637                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8638                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8639
8640       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8641         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8642
8643       // Because vperm has a big-endian bias, we must reverse the order
8644       // of the input vectors and complement the permute control vector
8645       // when generating little endian code.  We have already handled the
8646       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8647       // and ExtraLoad here.
8648       SDValue Perm;
8649       if (isLittleEndian)
8650         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8651                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8652       else
8653         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8654                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8655
8656       if (VT != MVT::v4i32)
8657         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8658
8659       // The output of the permutation is our loaded result, the TokenFactor is
8660       // our new chain.
8661       DCI.CombineTo(N, Perm, TF);
8662       return SDValue(N, 0);
8663     }
8664     }
8665     break;
8666   case ISD::INTRINSIC_WO_CHAIN: {
8667     bool isLittleEndian = Subtarget.isLittleEndian();
8668     Intrinsic::ID Intr = (isLittleEndian ?
8669                           Intrinsic::ppc_altivec_lvsr :
8670                           Intrinsic::ppc_altivec_lvsl);
8671     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8672         N->getOperand(1)->getOpcode() == ISD::ADD) {
8673       SDValue Add = N->getOperand(1);
8674
8675       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8676             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8677               Add.getValueType().getScalarType().getSizeInBits()))) {
8678         SDNode *BasePtr = Add->getOperand(0).getNode();
8679         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8680              UE = BasePtr->use_end(); UI != UE; ++UI) {
8681           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8682               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8683                 Intr) {
8684             // We've found another LVSL/LVSR, and this address is an aligned
8685             // multiple of that one. The results will be the same, so use the
8686             // one we've just found instead.
8687
8688             return SDValue(*UI, 0);
8689           }
8690         }
8691       }
8692     }
8693     }
8694
8695     break;
8696   case ISD::INTRINSIC_W_CHAIN: {
8697     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8698     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8699         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8700       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8701       default:
8702         break;
8703       case Intrinsic::ppc_vsx_lxvw4x:
8704       case Intrinsic::ppc_vsx_lxvd2x:
8705         return expandVSXLoadForLE(N, DCI);
8706       }
8707     }
8708     break;
8709   }
8710   case ISD::INTRINSIC_VOID: {
8711     // For little endian, VSX stores require generating xxswapd/stxvd2x.
8712     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8713         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8714       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8715       default:
8716         break;
8717       case Intrinsic::ppc_vsx_stxvw4x:
8718       case Intrinsic::ppc_vsx_stxvd2x:
8719         return expandVSXStoreForLE(N, DCI);
8720       }
8721     }
8722     break;
8723   }
8724   case ISD::BSWAP:
8725     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8726     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8727         N->getOperand(0).hasOneUse() &&
8728         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8729          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8730           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8731           N->getValueType(0) == MVT::i64))) {
8732       SDValue Load = N->getOperand(0);
8733       LoadSDNode *LD = cast<LoadSDNode>(Load);
8734       // Create the byte-swapping load.
8735       SDValue Ops[] = {
8736         LD->getChain(),    // Chain
8737         LD->getBasePtr(),  // Ptr
8738         DAG.getValueType(N->getValueType(0)) // VT
8739       };
8740       SDValue BSLoad =
8741         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8742                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8743                                               MVT::i64 : MVT::i32, MVT::Other),
8744                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8745
8746       // If this is an i16 load, insert the truncate.
8747       SDValue ResVal = BSLoad;
8748       if (N->getValueType(0) == MVT::i16)
8749         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8750
8751       // First, combine the bswap away.  This makes the value produced by the
8752       // load dead.
8753       DCI.CombineTo(N, ResVal);
8754
8755       // Next, combine the load away, we give it a bogus result value but a real
8756       // chain result.  The result value is dead because the bswap is dead.
8757       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8758
8759       // Return N so it doesn't get rechecked!
8760       return SDValue(N, 0);
8761     }
8762
8763     break;
8764   case PPCISD::VCMP: {
8765     // If a VCMPo node already exists with exactly the same operands as this
8766     // node, use its result instead of this node (VCMPo computes both a CR6 and
8767     // a normal output).
8768     //
8769     if (!N->getOperand(0).hasOneUse() &&
8770         !N->getOperand(1).hasOneUse() &&
8771         !N->getOperand(2).hasOneUse()) {
8772
8773       // Scan all of the users of the LHS, looking for VCMPo's that match.
8774       SDNode *VCMPoNode = nullptr;
8775
8776       SDNode *LHSN = N->getOperand(0).getNode();
8777       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8778            UI != E; ++UI)
8779         if (UI->getOpcode() == PPCISD::VCMPo &&
8780             UI->getOperand(1) == N->getOperand(1) &&
8781             UI->getOperand(2) == N->getOperand(2) &&
8782             UI->getOperand(0) == N->getOperand(0)) {
8783           VCMPoNode = *UI;
8784           break;
8785         }
8786
8787       // If there is no VCMPo node, or if the flag value has a single use, don't
8788       // transform this.
8789       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8790         break;
8791
8792       // Look at the (necessarily single) use of the flag value.  If it has a
8793       // chain, this transformation is more complex.  Note that multiple things
8794       // could use the value result, which we should ignore.
8795       SDNode *FlagUser = nullptr;
8796       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8797            FlagUser == nullptr; ++UI) {
8798         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8799         SDNode *User = *UI;
8800         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8801           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8802             FlagUser = User;
8803             break;
8804           }
8805         }
8806       }
8807
8808       // If the user is a MFOCRF instruction, we know this is safe.
8809       // Otherwise we give up for right now.
8810       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8811         return SDValue(VCMPoNode, 0);
8812     }
8813     break;
8814   }
8815   case ISD::BRCOND: {
8816     SDValue Cond = N->getOperand(1);
8817     SDValue Target = N->getOperand(2);
8818  
8819     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8820         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8821           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8822
8823       // We now need to make the intrinsic dead (it cannot be instruction
8824       // selected).
8825       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8826       assert(Cond.getNode()->hasOneUse() &&
8827              "Counter decrement has more than one use");
8828
8829       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8830                          N->getOperand(0), Target);
8831     }
8832   }
8833   break;
8834   case ISD::BR_CC: {
8835     // If this is a branch on an altivec predicate comparison, lower this so
8836     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8837     // lowering is done pre-legalize, because the legalizer lowers the predicate
8838     // compare down to code that is difficult to reassemble.
8839     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8840     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8841
8842     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8843     // value. If so, pass-through the AND to get to the intrinsic.
8844     if (LHS.getOpcode() == ISD::AND &&
8845         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8846         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8847           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8848         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8849         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8850           isZero())
8851       LHS = LHS.getOperand(0);
8852
8853     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8854         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8855           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8856         isa<ConstantSDNode>(RHS)) {
8857       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8858              "Counter decrement comparison is not EQ or NE");
8859
8860       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8861       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8862                     (CC == ISD::SETNE && !Val);
8863
8864       // We now need to make the intrinsic dead (it cannot be instruction
8865       // selected).
8866       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8867       assert(LHS.getNode()->hasOneUse() &&
8868              "Counter decrement has more than one use");
8869
8870       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8871                          N->getOperand(0), N->getOperand(4));
8872     }
8873
8874     int CompareOpc;
8875     bool isDot;
8876
8877     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8878         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8879         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8880       assert(isDot && "Can't compare against a vector result!");
8881
8882       // If this is a comparison against something other than 0/1, then we know
8883       // that the condition is never/always true.
8884       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8885       if (Val != 0 && Val != 1) {
8886         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8887           return N->getOperand(0);
8888         // Always !=, turn it into an unconditional branch.
8889         return DAG.getNode(ISD::BR, dl, MVT::Other,
8890                            N->getOperand(0), N->getOperand(4));
8891       }
8892
8893       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8894
8895       // Create the PPCISD altivec 'dot' comparison node.
8896       SDValue Ops[] = {
8897         LHS.getOperand(2),  // LHS of compare
8898         LHS.getOperand(3),  // RHS of compare
8899         DAG.getConstant(CompareOpc, MVT::i32)
8900       };
8901       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8902       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8903
8904       // Unpack the result based on how the target uses it.
8905       PPC::Predicate CompOpc;
8906       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8907       default:  // Can't happen, don't crash on invalid number though.
8908       case 0:   // Branch on the value of the EQ bit of CR6.
8909         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8910         break;
8911       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8912         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8913         break;
8914       case 2:   // Branch on the value of the LT bit of CR6.
8915         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8916         break;
8917       case 3:   // Branch on the inverted value of the LT bit of CR6.
8918         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8919         break;
8920       }
8921
8922       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8923                          DAG.getConstant(CompOpc, MVT::i32),
8924                          DAG.getRegister(PPC::CR6, MVT::i32),
8925                          N->getOperand(4), CompNode.getValue(1));
8926     }
8927     break;
8928   }
8929   }
8930
8931   return SDValue();
8932 }
8933
8934 //===----------------------------------------------------------------------===//
8935 // Inline Assembly Support
8936 //===----------------------------------------------------------------------===//
8937
8938 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8939                                                       APInt &KnownZero,
8940                                                       APInt &KnownOne,
8941                                                       const SelectionDAG &DAG,
8942                                                       unsigned Depth) const {
8943   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8944   switch (Op.getOpcode()) {
8945   default: break;
8946   case PPCISD::LBRX: {
8947     // lhbrx is known to have the top bits cleared out.
8948     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8949       KnownZero = 0xFFFF0000;
8950     break;
8951   }
8952   case ISD::INTRINSIC_WO_CHAIN: {
8953     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8954     default: break;
8955     case Intrinsic::ppc_altivec_vcmpbfp_p:
8956     case Intrinsic::ppc_altivec_vcmpeqfp_p:
8957     case Intrinsic::ppc_altivec_vcmpequb_p:
8958     case Intrinsic::ppc_altivec_vcmpequh_p:
8959     case Intrinsic::ppc_altivec_vcmpequw_p:
8960     case Intrinsic::ppc_altivec_vcmpgefp_p:
8961     case Intrinsic::ppc_altivec_vcmpgtfp_p:
8962     case Intrinsic::ppc_altivec_vcmpgtsb_p:
8963     case Intrinsic::ppc_altivec_vcmpgtsh_p:
8964     case Intrinsic::ppc_altivec_vcmpgtsw_p:
8965     case Intrinsic::ppc_altivec_vcmpgtub_p:
8966     case Intrinsic::ppc_altivec_vcmpgtuh_p:
8967     case Intrinsic::ppc_altivec_vcmpgtuw_p:
8968       KnownZero = ~1U;  // All bits but the low one are known to be zero.
8969       break;
8970     }
8971   }
8972   }
8973 }
8974
8975
8976 /// getConstraintType - Given a constraint, return the type of
8977 /// constraint it is for this target.
8978 PPCTargetLowering::ConstraintType
8979 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8980   if (Constraint.size() == 1) {
8981     switch (Constraint[0]) {
8982     default: break;
8983     case 'b':
8984     case 'r':
8985     case 'f':
8986     case 'v':
8987     case 'y':
8988       return C_RegisterClass;
8989     case 'Z':
8990       // FIXME: While Z does indicate a memory constraint, it specifically
8991       // indicates an r+r address (used in conjunction with the 'y' modifier
8992       // in the replacement string). Currently, we're forcing the base
8993       // register to be r0 in the asm printer (which is interpreted as zero)
8994       // and forming the complete address in the second register. This is
8995       // suboptimal.
8996       return C_Memory;
8997     }
8998   } else if (Constraint == "wc") { // individual CR bits.
8999     return C_RegisterClass;
9000   } else if (Constraint == "wa" || Constraint == "wd" ||
9001              Constraint == "wf" || Constraint == "ws") {
9002     return C_RegisterClass; // VSX registers.
9003   }
9004   return TargetLowering::getConstraintType(Constraint);
9005 }
9006
9007 /// Examine constraint type and operand type and determine a weight value.
9008 /// This object must already have been set up with the operand type
9009 /// and the current alternative constraint selected.
9010 TargetLowering::ConstraintWeight
9011 PPCTargetLowering::getSingleConstraintMatchWeight(
9012     AsmOperandInfo &info, const char *constraint) const {
9013   ConstraintWeight weight = CW_Invalid;
9014   Value *CallOperandVal = info.CallOperandVal;
9015     // If we don't have a value, we can't do a match,
9016     // but allow it at the lowest weight.
9017   if (!CallOperandVal)
9018     return CW_Default;
9019   Type *type = CallOperandVal->getType();
9020
9021   // Look at the constraint type.
9022   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9023     return CW_Register; // an individual CR bit.
9024   else if ((StringRef(constraint) == "wa" ||
9025             StringRef(constraint) == "wd" ||
9026             StringRef(constraint) == "wf") &&
9027            type->isVectorTy())
9028     return CW_Register;
9029   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9030     return CW_Register;
9031
9032   switch (*constraint) {
9033   default:
9034     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9035     break;
9036   case 'b':
9037     if (type->isIntegerTy())
9038       weight = CW_Register;
9039     break;
9040   case 'f':
9041     if (type->isFloatTy())
9042       weight = CW_Register;
9043     break;
9044   case 'd':
9045     if (type->isDoubleTy())
9046       weight = CW_Register;
9047     break;
9048   case 'v':
9049     if (type->isVectorTy())
9050       weight = CW_Register;
9051     break;
9052   case 'y':
9053     weight = CW_Register;
9054     break;
9055   case 'Z':
9056     weight = CW_Memory;
9057     break;
9058   }
9059   return weight;
9060 }
9061
9062 std::pair<unsigned, const TargetRegisterClass*>
9063 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9064                                                 MVT VT) const {
9065   if (Constraint.size() == 1) {
9066     // GCC RS6000 Constraint Letters
9067     switch (Constraint[0]) {
9068     case 'b':   // R1-R31
9069       if (VT == MVT::i64 && Subtarget.isPPC64())
9070         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9071       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9072     case 'r':   // R0-R31
9073       if (VT == MVT::i64 && Subtarget.isPPC64())
9074         return std::make_pair(0U, &PPC::G8RCRegClass);
9075       return std::make_pair(0U, &PPC::GPRCRegClass);
9076     case 'f':
9077       if (VT == MVT::f32 || VT == MVT::i32)
9078         return std::make_pair(0U, &PPC::F4RCRegClass);
9079       if (VT == MVT::f64 || VT == MVT::i64)
9080         return std::make_pair(0U, &PPC::F8RCRegClass);
9081       break;
9082     case 'v':
9083       return std::make_pair(0U, &PPC::VRRCRegClass);
9084     case 'y':   // crrc
9085       return std::make_pair(0U, &PPC::CRRCRegClass);
9086     }
9087   } else if (Constraint == "wc") { // an individual CR bit.
9088     return std::make_pair(0U, &PPC::CRBITRCRegClass);
9089   } else if (Constraint == "wa" || Constraint == "wd" ||
9090              Constraint == "wf") {
9091     return std::make_pair(0U, &PPC::VSRCRegClass);
9092   } else if (Constraint == "ws") {
9093     return std::make_pair(0U, &PPC::VSFRCRegClass);
9094   }
9095
9096   std::pair<unsigned, const TargetRegisterClass*> R =
9097     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9098
9099   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9100   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9101   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9102   // register.
9103   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9104   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9105   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9106       PPC::GPRCRegClass.contains(R.first)) {
9107     const TargetRegisterInfo *TRI =
9108         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
9109     return std::make_pair(TRI->getMatchingSuperReg(R.first,
9110                             PPC::sub_32, &PPC::G8RCRegClass),
9111                           &PPC::G8RCRegClass);
9112   }
9113
9114   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9115   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9116     R.first = PPC::CR0;
9117     R.second = &PPC::CRRCRegClass;
9118   }
9119
9120   return R;
9121 }
9122
9123
9124 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9125 /// vector.  If it is invalid, don't add anything to Ops.
9126 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9127                                                      std::string &Constraint,
9128                                                      std::vector<SDValue>&Ops,
9129                                                      SelectionDAG &DAG) const {
9130   SDValue Result;
9131
9132   // Only support length 1 constraints.
9133   if (Constraint.length() > 1) return;
9134
9135   char Letter = Constraint[0];
9136   switch (Letter) {
9137   default: break;
9138   case 'I':
9139   case 'J':
9140   case 'K':
9141   case 'L':
9142   case 'M':
9143   case 'N':
9144   case 'O':
9145   case 'P': {
9146     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9147     if (!CST) return; // Must be an immediate to match.
9148     int64_t Value = CST->getSExtValue();
9149     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9150                          // numbers are printed as such.
9151     switch (Letter) {
9152     default: llvm_unreachable("Unknown constraint letter!");
9153     case 'I':  // "I" is a signed 16-bit constant.
9154       if (isInt<16>(Value))
9155         Result = DAG.getTargetConstant(Value, TCVT);
9156       break;
9157     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9158       if (isShiftedUInt<16, 16>(Value))
9159         Result = DAG.getTargetConstant(Value, TCVT);
9160       break;
9161     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9162       if (isShiftedInt<16, 16>(Value))
9163         Result = DAG.getTargetConstant(Value, TCVT);
9164       break;
9165     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9166       if (isUInt<16>(Value))
9167         Result = DAG.getTargetConstant(Value, TCVT);
9168       break;
9169     case 'M':  // "M" is a constant that is greater than 31.
9170       if (Value > 31)
9171         Result = DAG.getTargetConstant(Value, TCVT);
9172       break;
9173     case 'N':  // "N" is a positive constant that is an exact power of two.
9174       if (Value > 0 && isPowerOf2_64(Value))
9175         Result = DAG.getTargetConstant(Value, TCVT);
9176       break;
9177     case 'O':  // "O" is the constant zero.
9178       if (Value == 0)
9179         Result = DAG.getTargetConstant(Value, TCVT);
9180       break;
9181     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9182       if (isInt<16>(-Value))
9183         Result = DAG.getTargetConstant(Value, TCVT);
9184       break;
9185     }
9186     break;
9187   }
9188   }
9189
9190   if (Result.getNode()) {
9191     Ops.push_back(Result);
9192     return;
9193   }
9194
9195   // Handle standard constraint letters.
9196   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9197 }
9198
9199 // isLegalAddressingMode - Return true if the addressing mode represented
9200 // by AM is legal for this target, for a load/store of the specified type.
9201 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9202                                               Type *Ty) const {
9203   // FIXME: PPC does not allow r+i addressing modes for vectors!
9204
9205   // PPC allows a sign-extended 16-bit immediate field.
9206   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9207     return false;
9208
9209   // No global is ever allowed as a base.
9210   if (AM.BaseGV)
9211     return false;
9212
9213   // PPC only support r+r,
9214   switch (AM.Scale) {
9215   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9216     break;
9217   case 1:
9218     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9219       return false;
9220     // Otherwise we have r+r or r+i.
9221     break;
9222   case 2:
9223     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9224       return false;
9225     // Allow 2*r as r+r.
9226     break;
9227   default:
9228     // No other scales are supported.
9229     return false;
9230   }
9231
9232   return true;
9233 }
9234
9235 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9236                                            SelectionDAG &DAG) const {
9237   MachineFunction &MF = DAG.getMachineFunction();
9238   MachineFrameInfo *MFI = MF.getFrameInfo();
9239   MFI->setReturnAddressIsTaken(true);
9240
9241   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9242     return SDValue();
9243
9244   SDLoc dl(Op);
9245   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9246
9247   // Make sure the function does not optimize away the store of the RA to
9248   // the stack.
9249   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9250   FuncInfo->setLRStoreRequired();
9251   bool isPPC64 = Subtarget.isPPC64();
9252   bool isDarwinABI = Subtarget.isDarwinABI();
9253
9254   if (Depth > 0) {
9255     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9256     SDValue Offset =
9257
9258       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9259                       isPPC64? MVT::i64 : MVT::i32);
9260     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9261                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9262                                    FrameAddr, Offset),
9263                        MachinePointerInfo(), false, false, false, 0);
9264   }
9265
9266   // Just load the return address off the stack.
9267   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9268   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9269                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9270 }
9271
9272 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9273                                           SelectionDAG &DAG) const {
9274   SDLoc dl(Op);
9275   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9276
9277   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9278   bool isPPC64 = PtrVT == MVT::i64;
9279
9280   MachineFunction &MF = DAG.getMachineFunction();
9281   MachineFrameInfo *MFI = MF.getFrameInfo();
9282   MFI->setFrameAddressIsTaken(true);
9283
9284   // Naked functions never have a frame pointer, and so we use r1. For all
9285   // other functions, this decision must be delayed until during PEI.
9286   unsigned FrameReg;
9287   if (MF.getFunction()->getAttributes().hasAttribute(
9288         AttributeSet::FunctionIndex, Attribute::Naked))
9289     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9290   else
9291     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9292
9293   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9294                                          PtrVT);
9295   while (Depth--)
9296     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9297                             FrameAddr, MachinePointerInfo(), false, false,
9298                             false, 0);
9299   return FrameAddr;
9300 }
9301
9302 // FIXME? Maybe this could be a TableGen attribute on some registers and
9303 // this table could be generated automatically from RegInfo.
9304 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9305                                               EVT VT) const {
9306   bool isPPC64 = Subtarget.isPPC64();
9307   bool isDarwinABI = Subtarget.isDarwinABI();
9308
9309   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9310       (!isPPC64 && VT != MVT::i32))
9311     report_fatal_error("Invalid register global variable type");
9312
9313   bool is64Bit = isPPC64 && VT == MVT::i64;
9314   unsigned Reg = StringSwitch<unsigned>(RegName)
9315                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9316                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9317                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9318                                   (is64Bit ? PPC::X13 : PPC::R13))
9319                    .Default(0);
9320
9321   if (Reg)
9322     return Reg;
9323   report_fatal_error("Invalid register name global variable");
9324 }
9325
9326 bool
9327 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9328   // The PowerPC target isn't yet aware of offsets.
9329   return false;
9330 }
9331
9332 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9333                                            const CallInst &I,
9334                                            unsigned Intrinsic) const {
9335
9336   switch (Intrinsic) {
9337   case Intrinsic::ppc_altivec_lvx:
9338   case Intrinsic::ppc_altivec_lvxl:
9339   case Intrinsic::ppc_altivec_lvebx:
9340   case Intrinsic::ppc_altivec_lvehx:
9341   case Intrinsic::ppc_altivec_lvewx:
9342   case Intrinsic::ppc_vsx_lxvd2x:
9343   case Intrinsic::ppc_vsx_lxvw4x: {
9344     EVT VT;
9345     switch (Intrinsic) {
9346     case Intrinsic::ppc_altivec_lvebx:
9347       VT = MVT::i8;
9348       break;
9349     case Intrinsic::ppc_altivec_lvehx:
9350       VT = MVT::i16;
9351       break;
9352     case Intrinsic::ppc_altivec_lvewx:
9353       VT = MVT::i32;
9354       break;
9355     case Intrinsic::ppc_vsx_lxvd2x:
9356       VT = MVT::v2f64;
9357       break;
9358     default:
9359       VT = MVT::v4i32;
9360       break;
9361     }
9362
9363     Info.opc = ISD::INTRINSIC_W_CHAIN;
9364     Info.memVT = VT;
9365     Info.ptrVal = I.getArgOperand(0);
9366     Info.offset = -VT.getStoreSize()+1;
9367     Info.size = 2*VT.getStoreSize()-1;
9368     Info.align = 1;
9369     Info.vol = false;
9370     Info.readMem = true;
9371     Info.writeMem = false;
9372     return true;
9373   }
9374   case Intrinsic::ppc_altivec_stvx:
9375   case Intrinsic::ppc_altivec_stvxl:
9376   case Intrinsic::ppc_altivec_stvebx:
9377   case Intrinsic::ppc_altivec_stvehx:
9378   case Intrinsic::ppc_altivec_stvewx:
9379   case Intrinsic::ppc_vsx_stxvd2x:
9380   case Intrinsic::ppc_vsx_stxvw4x: {
9381     EVT VT;
9382     switch (Intrinsic) {
9383     case Intrinsic::ppc_altivec_stvebx:
9384       VT = MVT::i8;
9385       break;
9386     case Intrinsic::ppc_altivec_stvehx:
9387       VT = MVT::i16;
9388       break;
9389     case Intrinsic::ppc_altivec_stvewx:
9390       VT = MVT::i32;
9391       break;
9392     case Intrinsic::ppc_vsx_stxvd2x:
9393       VT = MVT::v2f64;
9394       break;
9395     default:
9396       VT = MVT::v4i32;
9397       break;
9398     }
9399
9400     Info.opc = ISD::INTRINSIC_VOID;
9401     Info.memVT = VT;
9402     Info.ptrVal = I.getArgOperand(1);
9403     Info.offset = -VT.getStoreSize()+1;
9404     Info.size = 2*VT.getStoreSize()-1;
9405     Info.align = 1;
9406     Info.vol = false;
9407     Info.readMem = false;
9408     Info.writeMem = true;
9409     return true;
9410   }
9411   default:
9412     break;
9413   }
9414
9415   return false;
9416 }
9417
9418 /// getOptimalMemOpType - Returns the target specific optimal type for load
9419 /// and store operations as a result of memset, memcpy, and memmove
9420 /// lowering. If DstAlign is zero that means it's safe to destination
9421 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9422 /// means there isn't a need to check it against alignment requirement,
9423 /// probably because the source does not need to be loaded. If 'IsMemset' is
9424 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9425 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9426 /// source is constant so it does not need to be loaded.
9427 /// It returns EVT::Other if the type should be determined using generic
9428 /// target-independent logic.
9429 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9430                                            unsigned DstAlign, unsigned SrcAlign,
9431                                            bool IsMemset, bool ZeroMemset,
9432                                            bool MemcpyStrSrc,
9433                                            MachineFunction &MF) const {
9434   if (Subtarget.isPPC64()) {
9435     return MVT::i64;
9436   } else {
9437     return MVT::i32;
9438   }
9439 }
9440
9441 /// \brief Returns true if it is beneficial to convert a load of a constant
9442 /// to just the constant itself.
9443 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9444                                                           Type *Ty) const {
9445   assert(Ty->isIntegerTy());
9446
9447   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9448   if (BitSize == 0 || BitSize > 64)
9449     return false;
9450   return true;
9451 }
9452
9453 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9454   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9455     return false;
9456   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9457   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9458   return NumBits1 == 64 && NumBits2 == 32;
9459 }
9460
9461 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9462   if (!VT1.isInteger() || !VT2.isInteger())
9463     return false;
9464   unsigned NumBits1 = VT1.getSizeInBits();
9465   unsigned NumBits2 = VT2.getSizeInBits();
9466   return NumBits1 == 64 && NumBits2 == 32;
9467 }
9468
9469 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9470   return isInt<16>(Imm) || isUInt<16>(Imm);
9471 }
9472
9473 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9474   return isInt<16>(Imm) || isUInt<16>(Imm);
9475 }
9476
9477 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9478                                                        unsigned,
9479                                                        unsigned,
9480                                                        bool *Fast) const {
9481   if (DisablePPCUnaligned)
9482     return false;
9483
9484   // PowerPC supports unaligned memory access for simple non-vector types.
9485   // Although accessing unaligned addresses is not as efficient as accessing
9486   // aligned addresses, it is generally more efficient than manual expansion,
9487   // and generally only traps for software emulation when crossing page
9488   // boundaries.
9489
9490   if (!VT.isSimple())
9491     return false;
9492
9493   if (VT.getSimpleVT().isVector()) {
9494     if (Subtarget.hasVSX()) {
9495       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9496           VT != MVT::v4f32 && VT != MVT::v4i32)
9497         return false;
9498     } else {
9499       return false;
9500     }
9501   }
9502
9503   if (VT == MVT::ppcf128)
9504     return false;
9505
9506   if (Fast)
9507     *Fast = true;
9508
9509   return true;
9510 }
9511
9512 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9513   VT = VT.getScalarType();
9514
9515   if (!VT.isSimple())
9516     return false;
9517
9518   switch (VT.getSimpleVT().SimpleTy) {
9519   case MVT::f32:
9520   case MVT::f64:
9521     return true;
9522   default:
9523     break;
9524   }
9525
9526   return false;
9527 }
9528
9529 bool
9530 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9531                      EVT VT , unsigned DefinedValues) const {
9532   if (VT == MVT::v2i64)
9533     return false;
9534
9535   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9536 }
9537
9538 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9539   if (DisableILPPref || Subtarget.enableMachineScheduler())
9540     return TargetLowering::getSchedulingPreference(N);
9541
9542   return Sched::ILP;
9543 }
9544
9545 // Create a fast isel object.
9546 FastISel *
9547 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9548                                   const TargetLibraryInfo *LibInfo) const {
9549   return PPC::createFastISel(FuncInfo, LibInfo);
9550 }