[PowerPC] Fold [sz]ext with fp_to_int lowering where possible
[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/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetOptions.h"
41 using namespace llvm;
42
43 // FIXME: Remove this once soft-float is supported.
44 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
45 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
46
47 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
48 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
49
50 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
51 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
52
53 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
54 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
55
56 // FIXME: Remove this once the bug has been fixed!
57 extern cl::opt<bool> ANDIGlueBug;
58
59 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
60     : TargetLowering(TM),
61       Subtarget(*TM.getSubtargetImpl()) {
62   // Use _setjmp/_longjmp instead of setjmp/longjmp.
63   setUseUnderscoreSetJmp(true);
64   setUseUnderscoreLongJmp(true);
65
66   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
67   // arguments are at least 4/8 bytes aligned.
68   bool isPPC64 = Subtarget.isPPC64();
69   setMinStackArgumentAlignment(isPPC64 ? 8:4);
70
71   // Set up the register classes.
72   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
73   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
74   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
75
76   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
77   for (MVT VT : MVT::integer_valuetypes()) {
78     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
79     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
80   }
81
82   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
83
84   // PowerPC has pre-inc load and store's.
85   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
88   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
90   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
91   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
92   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
93   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
95
96   if (Subtarget.useCRBits()) {
97     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
98
99     if (isPPC64 || Subtarget.hasFPCVT()) {
100       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
101       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
102                          isPPC64 ? MVT::i64 : MVT::i32);
103       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
104       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
105                          isPPC64 ? MVT::i64 : MVT::i32);
106     } else {
107       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
108       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
109     }
110
111     // PowerPC does not support direct load / store of condition registers
112     setOperationAction(ISD::LOAD, MVT::i1, Custom);
113     setOperationAction(ISD::STORE, MVT::i1, Custom);
114
115     // FIXME: Remove this once the ANDI glue bug is fixed:
116     if (ANDIGlueBug)
117       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
118
119     for (MVT VT : MVT::integer_valuetypes()) {
120       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
121       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
122       setTruncStoreAction(VT, MVT::i1, Expand);
123     }
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 (MVT VT : MVT::vector_valuetypes()) {
399       // add/sub are legal for all supported vector VT's.
400       setOperationAction(ISD::ADD , VT, Legal);
401       setOperationAction(ISD::SUB , VT, Legal);
402
403       // We promote all shuffles to v16i8.
404       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
405       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
406
407       // We promote all non-typed operations to v4i32.
408       setOperationAction(ISD::AND   , VT, Promote);
409       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
410       setOperationAction(ISD::OR    , VT, Promote);
411       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
412       setOperationAction(ISD::XOR   , VT, Promote);
413       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
414       setOperationAction(ISD::LOAD  , VT, Promote);
415       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
416       setOperationAction(ISD::SELECT, VT, Promote);
417       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
418       setOperationAction(ISD::STORE, VT, Promote);
419       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
420
421       // No other operations are legal.
422       setOperationAction(ISD::MUL , VT, Expand);
423       setOperationAction(ISD::SDIV, VT, Expand);
424       setOperationAction(ISD::SREM, VT, Expand);
425       setOperationAction(ISD::UDIV, VT, Expand);
426       setOperationAction(ISD::UREM, VT, Expand);
427       setOperationAction(ISD::FDIV, VT, Expand);
428       setOperationAction(ISD::FREM, VT, Expand);
429       setOperationAction(ISD::FNEG, VT, Expand);
430       setOperationAction(ISD::FSQRT, VT, Expand);
431       setOperationAction(ISD::FLOG, VT, Expand);
432       setOperationAction(ISD::FLOG10, VT, Expand);
433       setOperationAction(ISD::FLOG2, VT, Expand);
434       setOperationAction(ISD::FEXP, VT, Expand);
435       setOperationAction(ISD::FEXP2, VT, Expand);
436       setOperationAction(ISD::FSIN, VT, Expand);
437       setOperationAction(ISD::FCOS, VT, Expand);
438       setOperationAction(ISD::FABS, VT, Expand);
439       setOperationAction(ISD::FPOWI, VT, Expand);
440       setOperationAction(ISD::FFLOOR, VT, Expand);
441       setOperationAction(ISD::FCEIL,  VT, Expand);
442       setOperationAction(ISD::FTRUNC, VT, Expand);
443       setOperationAction(ISD::FRINT,  VT, Expand);
444       setOperationAction(ISD::FNEARBYINT, VT, Expand);
445       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
446       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
447       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
448       setOperationAction(ISD::MULHU, VT, Expand);
449       setOperationAction(ISD::MULHS, VT, Expand);
450       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
451       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
452       setOperationAction(ISD::UDIVREM, VT, Expand);
453       setOperationAction(ISD::SDIVREM, VT, Expand);
454       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
455       setOperationAction(ISD::FPOW, VT, Expand);
456       setOperationAction(ISD::BSWAP, VT, Expand);
457       setOperationAction(ISD::CTPOP, VT, Expand);
458       setOperationAction(ISD::CTLZ, VT, Expand);
459       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
460       setOperationAction(ISD::CTTZ, VT, Expand);
461       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
462       setOperationAction(ISD::VSELECT, VT, Expand);
463       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
464
465       for (MVT InnerVT : MVT::vector_valuetypes()) {
466         setTruncStoreAction(VT, InnerVT, Expand);
467         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
468         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
469         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
470       }
471     }
472
473     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
474     // with merges, splats, etc.
475     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
476
477     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
478     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
479     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
480     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
481     setOperationAction(ISD::SELECT, MVT::v4i32,
482                        Subtarget.useCRBits() ? Legal : Expand);
483     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
484     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
485     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
486     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
487     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
488     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
489     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
490     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
491     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
492
493     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
494     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
495     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
496     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
497
498     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
499     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
500
501     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
502       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
503       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
504     }
505
506     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
507     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
508     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
509
510     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
511     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
512
513     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
514     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
515     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
516     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
517
518     // Altivec does not contain unordered floating-point compare instructions
519     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
520     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
521     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
522     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
523
524     if (Subtarget.hasVSX()) {
525       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
526       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
527
528       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
529       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
530       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
531       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
532       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
533
534       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
535
536       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
537       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
538
539       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
540       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
541
542       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
543       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
544       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
545       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
546       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
547
548       // Share the Altivec comparison restrictions.
549       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
550       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
551       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
552       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
553
554       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
555       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
556
557       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
558
559       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
560
561       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
562       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
563
564       // VSX v2i64 only supports non-arithmetic operations.
565       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
566       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
567
568       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
569       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
570       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
571
572       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
573
574       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
575       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
576       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
577       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
578
579       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
580
581       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
582       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
583       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
584       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
585
586       // Vector operation legalization checks the result type of
587       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
588       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
589       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
590       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
591       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
592
593       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
594     }
595   }
596
597   if (Subtarget.has64BitSupport())
598     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
599
600   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
601
602   if (!isPPC64) {
603     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
604     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
605   }
606
607   setBooleanContents(ZeroOrOneBooleanContent);
608   // Altivec instructions set fields to all zeros or all ones.
609   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
610
611   if (!isPPC64) {
612     // These libcalls are not available in 32-bit.
613     setLibcallName(RTLIB::SHL_I128, nullptr);
614     setLibcallName(RTLIB::SRL_I128, nullptr);
615     setLibcallName(RTLIB::SRA_I128, nullptr);
616   }
617
618   if (isPPC64) {
619     setStackPointerRegisterToSaveRestore(PPC::X1);
620     setExceptionPointerRegister(PPC::X3);
621     setExceptionSelectorRegister(PPC::X4);
622   } else {
623     setStackPointerRegisterToSaveRestore(PPC::R1);
624     setExceptionPointerRegister(PPC::R3);
625     setExceptionSelectorRegister(PPC::R4);
626   }
627
628   // We have target-specific dag combine patterns for the following nodes:
629   setTargetDAGCombine(ISD::SINT_TO_FP);
630   if (Subtarget.hasFPCVT())
631     setTargetDAGCombine(ISD::UINT_TO_FP);
632   setTargetDAGCombine(ISD::LOAD);
633   setTargetDAGCombine(ISD::STORE);
634   setTargetDAGCombine(ISD::BR_CC);
635   if (Subtarget.useCRBits())
636     setTargetDAGCombine(ISD::BRCOND);
637   setTargetDAGCombine(ISD::BSWAP);
638   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
639   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
640   setTargetDAGCombine(ISD::INTRINSIC_VOID);
641
642   setTargetDAGCombine(ISD::SIGN_EXTEND);
643   setTargetDAGCombine(ISD::ZERO_EXTEND);
644   setTargetDAGCombine(ISD::ANY_EXTEND);
645
646   if (Subtarget.useCRBits()) {
647     setTargetDAGCombine(ISD::TRUNCATE);
648     setTargetDAGCombine(ISD::SETCC);
649     setTargetDAGCombine(ISD::SELECT_CC);
650   }
651
652   // Use reciprocal estimates.
653   if (TM.Options.UnsafeFPMath) {
654     setTargetDAGCombine(ISD::FDIV);
655     setTargetDAGCombine(ISD::FSQRT);
656   }
657
658   // Darwin long double math library functions have $LDBL128 appended.
659   if (Subtarget.isDarwin()) {
660     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
661     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
662     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
663     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
664     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
665     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
666     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
667     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
668     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
669     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
670   }
671
672   // With 32 condition bits, we don't need to sink (and duplicate) compares
673   // aggressively in CodeGenPrep.
674   if (Subtarget.useCRBits())
675     setHasMultipleConditionRegisters();
676
677   setMinFunctionAlignment(2);
678   if (Subtarget.isDarwin())
679     setPrefFunctionAlignment(4);
680
681   switch (Subtarget.getDarwinDirective()) {
682   default: break;
683   case PPC::DIR_970:
684   case PPC::DIR_A2:
685   case PPC::DIR_E500mc:
686   case PPC::DIR_E5500:
687   case PPC::DIR_PWR4:
688   case PPC::DIR_PWR5:
689   case PPC::DIR_PWR5X:
690   case PPC::DIR_PWR6:
691   case PPC::DIR_PWR6X:
692   case PPC::DIR_PWR7:
693   case PPC::DIR_PWR8:
694     setPrefFunctionAlignment(4);
695     setPrefLoopAlignment(4);
696     break;
697   }
698
699   setInsertFencesForAtomic(true);
700
701   if (Subtarget.enableMachineScheduler())
702     setSchedulingPreference(Sched::Source);
703   else
704     setSchedulingPreference(Sched::Hybrid);
705
706   computeRegisterProperties();
707
708   // The Freescale cores do better with aggressive inlining of memcpy and
709   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
710   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
711       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
712     MaxStoresPerMemset = 32;
713     MaxStoresPerMemsetOptSize = 16;
714     MaxStoresPerMemcpy = 32;
715     MaxStoresPerMemcpyOptSize = 8;
716     MaxStoresPerMemmove = 32;
717     MaxStoresPerMemmoveOptSize = 8;
718   }
719 }
720
721 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
722 /// the desired ByVal argument alignment.
723 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
724                              unsigned MaxMaxAlign) {
725   if (MaxAlign == MaxMaxAlign)
726     return;
727   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
728     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
729       MaxAlign = 32;
730     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
731       MaxAlign = 16;
732   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
733     unsigned EltAlign = 0;
734     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
735     if (EltAlign > MaxAlign)
736       MaxAlign = EltAlign;
737   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
738     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
739       unsigned EltAlign = 0;
740       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
741       if (EltAlign > MaxAlign)
742         MaxAlign = EltAlign;
743       if (MaxAlign == MaxMaxAlign)
744         break;
745     }
746   }
747 }
748
749 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
750 /// function arguments in the caller parameter area.
751 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
752   // Darwin passes everything on 4 byte boundary.
753   if (Subtarget.isDarwin())
754     return 4;
755
756   // 16byte and wider vectors are passed on 16byte boundary.
757   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
758   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
759   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
760     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
761   return Align;
762 }
763
764 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
765   switch (Opcode) {
766   default: return nullptr;
767   case PPCISD::FSEL:            return "PPCISD::FSEL";
768   case PPCISD::FCFID:           return "PPCISD::FCFID";
769   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
770   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
771   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
772   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
773   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
774   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
775   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
776   case PPCISD::FRE:             return "PPCISD::FRE";
777   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
778   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
779   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
780   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
781   case PPCISD::VPERM:           return "PPCISD::VPERM";
782   case PPCISD::CMPB:            return "PPCISD::CMPB";
783   case PPCISD::Hi:              return "PPCISD::Hi";
784   case PPCISD::Lo:              return "PPCISD::Lo";
785   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
786   case PPCISD::LOAD:            return "PPCISD::LOAD";
787   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
788   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
789   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
790   case PPCISD::SRL:             return "PPCISD::SRL";
791   case PPCISD::SRA:             return "PPCISD::SRA";
792   case PPCISD::SHL:             return "PPCISD::SHL";
793   case PPCISD::CALL:            return "PPCISD::CALL";
794   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
795   case PPCISD::CALL_TLS:        return "PPCISD::CALL_TLS";
796   case PPCISD::CALL_NOP_TLS:    return "PPCISD::CALL_NOP_TLS";
797   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
798   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
799   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
800   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
801   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
802   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
803   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
804   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
805   case PPCISD::VCMP:            return "PPCISD::VCMP";
806   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
807   case PPCISD::LBRX:            return "PPCISD::LBRX";
808   case PPCISD::STBRX:           return "PPCISD::STBRX";
809   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
810   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
811   case PPCISD::LARX:            return "PPCISD::LARX";
812   case PPCISD::STCX:            return "PPCISD::STCX";
813   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
814   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
815   case PPCISD::BDZ:             return "PPCISD::BDZ";
816   case PPCISD::MFFS:            return "PPCISD::MFFS";
817   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
818   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
819   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
820   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
821   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
822   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
823   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
824   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
825   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
826   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
827   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
828   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
829   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
830   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
831   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
832   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
833   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
834   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
835   case PPCISD::SC:              return "PPCISD::SC";
836   }
837 }
838
839 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
840   if (!VT.isVector())
841     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
842   return VT.changeVectorElementTypeToInteger();
843 }
844
845 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
846   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
847   return true;
848 }
849
850 //===----------------------------------------------------------------------===//
851 // Node matching predicates, for use by the tblgen matching code.
852 //===----------------------------------------------------------------------===//
853
854 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
855 static bool isFloatingPointZero(SDValue Op) {
856   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
857     return CFP->getValueAPF().isZero();
858   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
859     // Maybe this has already been legalized into the constant pool?
860     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
861       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
862         return CFP->getValueAPF().isZero();
863   }
864   return false;
865 }
866
867 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
868 /// true if Op is undef or if it matches the specified value.
869 static bool isConstantOrUndef(int Op, int Val) {
870   return Op < 0 || Op == Val;
871 }
872
873 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
874 /// VPKUHUM instruction.
875 /// The ShuffleKind distinguishes between big-endian operations with
876 /// two different inputs (0), either-endian operations with two identical
877 /// inputs (1), and little-endian operantion with two different inputs (2).
878 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
879 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
880                                SelectionDAG &DAG) {
881   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
882   if (ShuffleKind == 0) {
883     if (IsLE)
884       return false;
885     for (unsigned i = 0; i != 16; ++i)
886       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
887         return false;
888   } else if (ShuffleKind == 2) {
889     if (!IsLE)
890       return false;
891     for (unsigned i = 0; i != 16; ++i)
892       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
893         return false;
894   } else if (ShuffleKind == 1) {
895     unsigned j = IsLE ? 0 : 1;
896     for (unsigned i = 0; i != 8; ++i)
897       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
898           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
899         return false;
900   }
901   return true;
902 }
903
904 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
905 /// VPKUWUM instruction.
906 /// The ShuffleKind distinguishes between big-endian operations with
907 /// two different inputs (0), either-endian operations with two identical
908 /// inputs (1), and little-endian operantion with two different inputs (2).
909 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
910 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
911                                SelectionDAG &DAG) {
912   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
913   if (ShuffleKind == 0) {
914     if (IsLE)
915       return false;
916     for (unsigned i = 0; i != 16; i += 2)
917       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
918           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
919         return false;
920   } else if (ShuffleKind == 2) {
921     if (!IsLE)
922       return false;
923     for (unsigned i = 0; i != 16; i += 2)
924       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
925           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
926         return false;
927   } else if (ShuffleKind == 1) {
928     unsigned j = IsLE ? 0 : 2;
929     for (unsigned i = 0; i != 8; i += 2)
930       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
931           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
932           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
933           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
934         return false;
935   }
936   return true;
937 }
938
939 /// isVMerge - Common function, used to match vmrg* shuffles.
940 ///
941 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
942                      unsigned LHSStart, unsigned RHSStart) {
943   if (N->getValueType(0) != MVT::v16i8)
944     return false;
945   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
946          "Unsupported merge size!");
947
948   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
949     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
950       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
951                              LHSStart+j+i*UnitSize) ||
952           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
953                              RHSStart+j+i*UnitSize))
954         return false;
955     }
956   return true;
957 }
958
959 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
960 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
961 /// The ShuffleKind distinguishes between big-endian merges with two 
962 /// different inputs (0), either-endian merges with two identical inputs (1),
963 /// and little-endian merges with two different inputs (2).  For the latter,
964 /// the input operands are swapped (see PPCInstrAltivec.td).
965 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
966                              unsigned ShuffleKind, SelectionDAG &DAG) {
967   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
968     if (ShuffleKind == 1) // unary
969       return isVMerge(N, UnitSize, 0, 0);
970     else if (ShuffleKind == 2) // swapped
971       return isVMerge(N, UnitSize, 0, 16);
972     else
973       return false;
974   } else {
975     if (ShuffleKind == 1) // unary
976       return isVMerge(N, UnitSize, 8, 8);
977     else if (ShuffleKind == 0) // normal
978       return isVMerge(N, UnitSize, 8, 24);
979     else
980       return false;
981   }
982 }
983
984 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
985 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
986 /// The ShuffleKind distinguishes between big-endian merges with two 
987 /// different inputs (0), either-endian merges with two identical inputs (1),
988 /// and little-endian merges with two different inputs (2).  For the latter,
989 /// the input operands are swapped (see PPCInstrAltivec.td).
990 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
991                              unsigned ShuffleKind, SelectionDAG &DAG) {
992   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
993     if (ShuffleKind == 1) // unary
994       return isVMerge(N, UnitSize, 8, 8);
995     else if (ShuffleKind == 2) // swapped
996       return isVMerge(N, UnitSize, 8, 24);
997     else
998       return false;
999   } else {
1000     if (ShuffleKind == 1) // unary
1001       return isVMerge(N, UnitSize, 0, 0);
1002     else if (ShuffleKind == 0) // normal
1003       return isVMerge(N, UnitSize, 0, 16);
1004     else
1005       return false;
1006   }
1007 }
1008
1009
1010 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1011 /// amount, otherwise return -1.
1012 /// The ShuffleKind distinguishes between big-endian operations with two 
1013 /// different inputs (0), either-endian operations with two identical inputs
1014 /// (1), and little-endian operations with two different inputs (2).  For the
1015 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1016 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1017                              SelectionDAG &DAG) {
1018   if (N->getValueType(0) != MVT::v16i8)
1019     return -1;
1020
1021   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1022
1023   // Find the first non-undef value in the shuffle mask.
1024   unsigned i;
1025   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1026     /*search*/;
1027
1028   if (i == 16) return -1;  // all undef.
1029
1030   // Otherwise, check to see if the rest of the elements are consecutively
1031   // numbered from this value.
1032   unsigned ShiftAmt = SVOp->getMaskElt(i);
1033   if (ShiftAmt < i) return -1;
1034
1035   ShiftAmt -= i;
1036   bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1037     isLittleEndian();
1038
1039   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1040     // Check the rest of the elements to see if they are consecutive.
1041     for (++i; i != 16; ++i)
1042       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1043         return -1;
1044   } else if (ShuffleKind == 1) {
1045     // Check the rest of the elements to see if they are consecutive.
1046     for (++i; i != 16; ++i)
1047       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1048         return -1;
1049   } else
1050     return -1;
1051
1052   if (ShuffleKind == 2 && isLE)
1053     ShiftAmt = 16 - ShiftAmt;
1054
1055   return ShiftAmt;
1056 }
1057
1058 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1059 /// specifies a splat of a single element that is suitable for input to
1060 /// VSPLTB/VSPLTH/VSPLTW.
1061 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1062   assert(N->getValueType(0) == MVT::v16i8 &&
1063          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1064
1065   // This is a splat operation if each element of the permute is the same, and
1066   // if the value doesn't reference the second vector.
1067   unsigned ElementBase = N->getMaskElt(0);
1068
1069   // FIXME: Handle UNDEF elements too!
1070   if (ElementBase >= 16)
1071     return false;
1072
1073   // Check that the indices are consecutive, in the case of a multi-byte element
1074   // splatted with a v16i8 mask.
1075   for (unsigned i = 1; i != EltSize; ++i)
1076     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1077       return false;
1078
1079   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1080     if (N->getMaskElt(i) < 0) continue;
1081     for (unsigned j = 0; j != EltSize; ++j)
1082       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1083         return false;
1084   }
1085   return true;
1086 }
1087
1088 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1089 /// are -0.0.
1090 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1091   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1092
1093   APInt APVal, APUndef;
1094   unsigned BitSize;
1095   bool HasAnyUndefs;
1096
1097   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1098     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1099       return CFP->getValueAPF().isNegZero();
1100
1101   return false;
1102 }
1103
1104 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1105 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1106 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1107                                 SelectionDAG &DAG) {
1108   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1109   assert(isSplatShuffleMask(SVOp, EltSize));
1110   if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1111     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1112   else
1113     return SVOp->getMaskElt(0) / EltSize;
1114 }
1115
1116 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1117 /// by using a vspltis[bhw] instruction of the specified element size, return
1118 /// the constant being splatted.  The ByteSize field indicates the number of
1119 /// bytes of each element [124] -> [bhw].
1120 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1121   SDValue OpVal(nullptr, 0);
1122
1123   // If ByteSize of the splat is bigger than the element size of the
1124   // build_vector, then we have a case where we are checking for a splat where
1125   // multiple elements of the buildvector are folded together into a single
1126   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1127   unsigned EltSize = 16/N->getNumOperands();
1128   if (EltSize < ByteSize) {
1129     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1130     SDValue UniquedVals[4];
1131     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1132
1133     // See if all of the elements in the buildvector agree across.
1134     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1135       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1136       // If the element isn't a constant, bail fully out.
1137       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1138
1139
1140       if (!UniquedVals[i&(Multiple-1)].getNode())
1141         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1142       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1143         return SDValue();  // no match.
1144     }
1145
1146     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1147     // either constant or undef values that are identical for each chunk.  See
1148     // if these chunks can form into a larger vspltis*.
1149
1150     // Check to see if all of the leading entries are either 0 or -1.  If
1151     // neither, then this won't fit into the immediate field.
1152     bool LeadingZero = true;
1153     bool LeadingOnes = true;
1154     for (unsigned i = 0; i != Multiple-1; ++i) {
1155       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1156
1157       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1158       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1159     }
1160     // Finally, check the least significant entry.
1161     if (LeadingZero) {
1162       if (!UniquedVals[Multiple-1].getNode())
1163         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1164       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1165       if (Val < 16)
1166         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1167     }
1168     if (LeadingOnes) {
1169       if (!UniquedVals[Multiple-1].getNode())
1170         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1171       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1172       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1173         return DAG.getTargetConstant(Val, MVT::i32);
1174     }
1175
1176     return SDValue();
1177   }
1178
1179   // Check to see if this buildvec has a single non-undef value in its elements.
1180   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1181     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1182     if (!OpVal.getNode())
1183       OpVal = N->getOperand(i);
1184     else if (OpVal != N->getOperand(i))
1185       return SDValue();
1186   }
1187
1188   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1189
1190   unsigned ValSizeInBytes = EltSize;
1191   uint64_t Value = 0;
1192   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1193     Value = CN->getZExtValue();
1194   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1195     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1196     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1197   }
1198
1199   // If the splat value is larger than the element value, then we can never do
1200   // this splat.  The only case that we could fit the replicated bits into our
1201   // immediate field for would be zero, and we prefer to use vxor for it.
1202   if (ValSizeInBytes < ByteSize) return SDValue();
1203
1204   // If the element value is larger than the splat value, cut it in half and
1205   // check to see if the two halves are equal.  Continue doing this until we
1206   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1207   while (ValSizeInBytes > ByteSize) {
1208     ValSizeInBytes >>= 1;
1209
1210     // If the top half equals the bottom half, we're still ok.
1211     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1212          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1213       return SDValue();
1214   }
1215
1216   // Properly sign extend the value.
1217   int MaskVal = SignExtend32(Value, ByteSize * 8);
1218
1219   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1220   if (MaskVal == 0) return SDValue();
1221
1222   // Finally, if this value fits in a 5 bit sext field, return it
1223   if (SignExtend32<5>(MaskVal) == MaskVal)
1224     return DAG.getTargetConstant(MaskVal, MVT::i32);
1225   return SDValue();
1226 }
1227
1228 //===----------------------------------------------------------------------===//
1229 //  Addressing Mode Selection
1230 //===----------------------------------------------------------------------===//
1231
1232 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1233 /// or 64-bit immediate, and if the value can be accurately represented as a
1234 /// sign extension from a 16-bit value.  If so, this returns true and the
1235 /// immediate.
1236 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1237   if (!isa<ConstantSDNode>(N))
1238     return false;
1239
1240   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1241   if (N->getValueType(0) == MVT::i32)
1242     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1243   else
1244     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1245 }
1246 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1247   return isIntS16Immediate(Op.getNode(), Imm);
1248 }
1249
1250
1251 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1252 /// can be represented as an indexed [r+r] operation.  Returns false if it
1253 /// can be more efficiently represented with [r+imm].
1254 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1255                                             SDValue &Index,
1256                                             SelectionDAG &DAG) const {
1257   short imm = 0;
1258   if (N.getOpcode() == ISD::ADD) {
1259     if (isIntS16Immediate(N.getOperand(1), imm))
1260       return false;    // r+i
1261     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1262       return false;    // r+i
1263
1264     Base = N.getOperand(0);
1265     Index = N.getOperand(1);
1266     return true;
1267   } else if (N.getOpcode() == ISD::OR) {
1268     if (isIntS16Immediate(N.getOperand(1), imm))
1269       return false;    // r+i can fold it if we can.
1270
1271     // If this is an or of disjoint bitfields, we can codegen this as an add
1272     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1273     // disjoint.
1274     APInt LHSKnownZero, LHSKnownOne;
1275     APInt RHSKnownZero, RHSKnownOne;
1276     DAG.computeKnownBits(N.getOperand(0),
1277                          LHSKnownZero, LHSKnownOne);
1278
1279     if (LHSKnownZero.getBoolValue()) {
1280       DAG.computeKnownBits(N.getOperand(1),
1281                            RHSKnownZero, RHSKnownOne);
1282       // If all of the bits are known zero on the LHS or RHS, the add won't
1283       // carry.
1284       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1285         Base = N.getOperand(0);
1286         Index = N.getOperand(1);
1287         return true;
1288       }
1289     }
1290   }
1291
1292   return false;
1293 }
1294
1295 // If we happen to be doing an i64 load or store into a stack slot that has
1296 // less than a 4-byte alignment, then the frame-index elimination may need to
1297 // use an indexed load or store instruction (because the offset may not be a
1298 // multiple of 4). The extra register needed to hold the offset comes from the
1299 // register scavenger, and it is possible that the scavenger will need to use
1300 // an emergency spill slot. As a result, we need to make sure that a spill slot
1301 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1302 // stack slot.
1303 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1304   // FIXME: This does not handle the LWA case.
1305   if (VT != MVT::i64)
1306     return;
1307
1308   // NOTE: We'll exclude negative FIs here, which come from argument
1309   // lowering, because there are no known test cases triggering this problem
1310   // using packed structures (or similar). We can remove this exclusion if
1311   // we find such a test case. The reason why this is so test-case driven is
1312   // because this entire 'fixup' is only to prevent crashes (from the
1313   // register scavenger) on not-really-valid inputs. For example, if we have:
1314   //   %a = alloca i1
1315   //   %b = bitcast i1* %a to i64*
1316   //   store i64* a, i64 b
1317   // then the store should really be marked as 'align 1', but is not. If it
1318   // were marked as 'align 1' then the indexed form would have been
1319   // instruction-selected initially, and the problem this 'fixup' is preventing
1320   // won't happen regardless.
1321   if (FrameIdx < 0)
1322     return;
1323
1324   MachineFunction &MF = DAG.getMachineFunction();
1325   MachineFrameInfo *MFI = MF.getFrameInfo();
1326
1327   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1328   if (Align >= 4)
1329     return;
1330
1331   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1332   FuncInfo->setHasNonRISpills();
1333 }
1334
1335 /// Returns true if the address N can be represented by a base register plus
1336 /// a signed 16-bit displacement [r+imm], and if it is not better
1337 /// represented as reg+reg.  If Aligned is true, only accept displacements
1338 /// suitable for STD and friends, i.e. multiples of 4.
1339 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1340                                             SDValue &Base,
1341                                             SelectionDAG &DAG,
1342                                             bool Aligned) const {
1343   // FIXME dl should come from parent load or store, not from address
1344   SDLoc dl(N);
1345   // If this can be more profitably realized as r+r, fail.
1346   if (SelectAddressRegReg(N, Disp, Base, DAG))
1347     return false;
1348
1349   if (N.getOpcode() == ISD::ADD) {
1350     short imm = 0;
1351     if (isIntS16Immediate(N.getOperand(1), imm) &&
1352         (!Aligned || (imm & 3) == 0)) {
1353       Disp = DAG.getTargetConstant(imm, N.getValueType());
1354       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1355         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1356         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1357       } else {
1358         Base = N.getOperand(0);
1359       }
1360       return true; // [r+i]
1361     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1362       // Match LOAD (ADD (X, Lo(G))).
1363       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1364              && "Cannot handle constant offsets yet!");
1365       Disp = N.getOperand(1).getOperand(0);  // The global address.
1366       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1367              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1368              Disp.getOpcode() == ISD::TargetConstantPool ||
1369              Disp.getOpcode() == ISD::TargetJumpTable);
1370       Base = N.getOperand(0);
1371       return true;  // [&g+r]
1372     }
1373   } else if (N.getOpcode() == ISD::OR) {
1374     short imm = 0;
1375     if (isIntS16Immediate(N.getOperand(1), imm) &&
1376         (!Aligned || (imm & 3) == 0)) {
1377       // If this is an or of disjoint bitfields, we can codegen this as an add
1378       // (for better address arithmetic) if the LHS and RHS of the OR are
1379       // provably disjoint.
1380       APInt LHSKnownZero, LHSKnownOne;
1381       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1382
1383       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1384         // If all of the bits are known zero on the LHS or RHS, the add won't
1385         // carry.
1386         if (FrameIndexSDNode *FI =
1387               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1388           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1389           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1390         } else {
1391           Base = N.getOperand(0);
1392         }
1393         Disp = DAG.getTargetConstant(imm, N.getValueType());
1394         return true;
1395       }
1396     }
1397   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1398     // Loading from a constant address.
1399
1400     // If this address fits entirely in a 16-bit sext immediate field, codegen
1401     // this as "d, 0"
1402     short Imm;
1403     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1404       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1405       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1406                              CN->getValueType(0));
1407       return true;
1408     }
1409
1410     // Handle 32-bit sext immediates with LIS + addr mode.
1411     if ((CN->getValueType(0) == MVT::i32 ||
1412          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1413         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1414       int Addr = (int)CN->getZExtValue();
1415
1416       // Otherwise, break this down into an LIS + disp.
1417       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1418
1419       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1420       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1421       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1422       return true;
1423     }
1424   }
1425
1426   Disp = DAG.getTargetConstant(0, getPointerTy());
1427   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1428     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1429     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1430   } else
1431     Base = N;
1432   return true;      // [r+0]
1433 }
1434
1435 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1436 /// represented as an indexed [r+r] operation.
1437 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1438                                                 SDValue &Index,
1439                                                 SelectionDAG &DAG) const {
1440   // Check to see if we can easily represent this as an [r+r] address.  This
1441   // will fail if it thinks that the address is more profitably represented as
1442   // reg+imm, e.g. where imm = 0.
1443   if (SelectAddressRegReg(N, Base, Index, DAG))
1444     return true;
1445
1446   // If the operand is an addition, always emit this as [r+r], since this is
1447   // better (for code size, and execution, as the memop does the add for free)
1448   // than emitting an explicit add.
1449   if (N.getOpcode() == ISD::ADD) {
1450     Base = N.getOperand(0);
1451     Index = N.getOperand(1);
1452     return true;
1453   }
1454
1455   // Otherwise, do it the hard way, using R0 as the base register.
1456   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1457                          N.getValueType());
1458   Index = N;
1459   return true;
1460 }
1461
1462 /// getPreIndexedAddressParts - returns true by value, base pointer and
1463 /// offset pointer and addressing mode by reference if the node's address
1464 /// can be legally represented as pre-indexed load / store address.
1465 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1466                                                   SDValue &Offset,
1467                                                   ISD::MemIndexedMode &AM,
1468                                                   SelectionDAG &DAG) const {
1469   if (DisablePPCPreinc) return false;
1470
1471   bool isLoad = true;
1472   SDValue Ptr;
1473   EVT VT;
1474   unsigned Alignment;
1475   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1476     Ptr = LD->getBasePtr();
1477     VT = LD->getMemoryVT();
1478     Alignment = LD->getAlignment();
1479   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1480     Ptr = ST->getBasePtr();
1481     VT  = ST->getMemoryVT();
1482     Alignment = ST->getAlignment();
1483     isLoad = false;
1484   } else
1485     return false;
1486
1487   // PowerPC doesn't have preinc load/store instructions for vectors.
1488   if (VT.isVector())
1489     return false;
1490
1491   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1492
1493     // Common code will reject creating a pre-inc form if the base pointer
1494     // is a frame index, or if N is a store and the base pointer is either
1495     // the same as or a predecessor of the value being stored.  Check for
1496     // those situations here, and try with swapped Base/Offset instead.
1497     bool Swap = false;
1498
1499     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1500       Swap = true;
1501     else if (!isLoad) {
1502       SDValue Val = cast<StoreSDNode>(N)->getValue();
1503       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1504         Swap = true;
1505     }
1506
1507     if (Swap)
1508       std::swap(Base, Offset);
1509
1510     AM = ISD::PRE_INC;
1511     return true;
1512   }
1513
1514   // LDU/STU can only handle immediates that are a multiple of 4.
1515   if (VT != MVT::i64) {
1516     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1517       return false;
1518   } else {
1519     // LDU/STU need an address with at least 4-byte alignment.
1520     if (Alignment < 4)
1521       return false;
1522
1523     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1524       return false;
1525   }
1526
1527   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1528     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1529     // sext i32 to i64 when addr mode is r+i.
1530     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1531         LD->getExtensionType() == ISD::SEXTLOAD &&
1532         isa<ConstantSDNode>(Offset))
1533       return false;
1534   }
1535
1536   AM = ISD::PRE_INC;
1537   return true;
1538 }
1539
1540 //===----------------------------------------------------------------------===//
1541 //  LowerOperation implementation
1542 //===----------------------------------------------------------------------===//
1543
1544 /// GetLabelAccessInfo - Return true if we should reference labels using a
1545 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1546 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1547                                unsigned &LoOpFlags,
1548                                const GlobalValue *GV = nullptr) {
1549   HiOpFlags = PPCII::MO_HA;
1550   LoOpFlags = PPCII::MO_LO;
1551
1552   // Don't use the pic base if not in PIC relocation model.
1553   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1554
1555   if (isPIC) {
1556     HiOpFlags |= PPCII::MO_PIC_FLAG;
1557     LoOpFlags |= PPCII::MO_PIC_FLAG;
1558   }
1559
1560   // If this is a reference to a global value that requires a non-lazy-ptr, make
1561   // sure that instruction lowering adds it.
1562   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1563     HiOpFlags |= PPCII::MO_NLP_FLAG;
1564     LoOpFlags |= PPCII::MO_NLP_FLAG;
1565
1566     if (GV->hasHiddenVisibility()) {
1567       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1568       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1569     }
1570   }
1571
1572   return isPIC;
1573 }
1574
1575 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1576                              SelectionDAG &DAG) {
1577   EVT PtrVT = HiPart.getValueType();
1578   SDValue Zero = DAG.getConstant(0, PtrVT);
1579   SDLoc DL(HiPart);
1580
1581   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1582   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1583
1584   // With PIC, the first instruction is actually "GR+hi(&G)".
1585   if (isPIC)
1586     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1587                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1588
1589   // Generate non-pic code that has direct accesses to the constant pool.
1590   // The address of the global is just (hi(&g)+lo(&g)).
1591   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1592 }
1593
1594 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1595                                              SelectionDAG &DAG) const {
1596   EVT PtrVT = Op.getValueType();
1597   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1598   const Constant *C = CP->getConstVal();
1599
1600   // 64-bit SVR4 ABI code is always position-independent.
1601   // The actual address of the GlobalValue is stored in the TOC.
1602   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1603     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1604     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1605                        DAG.getRegister(PPC::X2, MVT::i64));
1606   }
1607
1608   unsigned MOHiFlag, MOLoFlag;
1609   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1610
1611   if (isPIC && Subtarget.isSVR4ABI()) {
1612     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1613                                            PPCII::MO_PIC_FLAG);
1614     SDLoc DL(CP);
1615     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1616                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1617   }
1618
1619   SDValue CPIHi =
1620     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1621   SDValue CPILo =
1622     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1623   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1624 }
1625
1626 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1627   EVT PtrVT = Op.getValueType();
1628   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1629
1630   // 64-bit SVR4 ABI code is always position-independent.
1631   // The actual address of the GlobalValue is stored in the TOC.
1632   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1633     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1634     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1635                        DAG.getRegister(PPC::X2, MVT::i64));
1636   }
1637
1638   unsigned MOHiFlag, MOLoFlag;
1639   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1640
1641   if (isPIC && Subtarget.isSVR4ABI()) {
1642     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1643                                         PPCII::MO_PIC_FLAG);
1644     SDLoc DL(GA);
1645     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1646                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1647   }
1648
1649   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1650   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1651   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1652 }
1653
1654 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1655                                              SelectionDAG &DAG) const {
1656   EVT PtrVT = Op.getValueType();
1657   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1658   const BlockAddress *BA = BASDN->getBlockAddress();
1659
1660   // 64-bit SVR4 ABI code is always position-independent.
1661   // The actual BlockAddress is stored in the TOC.
1662   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1663     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1664     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1665                        DAG.getRegister(PPC::X2, MVT::i64));
1666   }
1667
1668   unsigned MOHiFlag, MOLoFlag;
1669   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1670   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1671   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1672   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1673 }
1674
1675 // Generate a call to __tls_get_addr for the given GOT entry Op.
1676 std::pair<SDValue,SDValue>
1677 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1678                                 SelectionDAG &DAG) const {
1679
1680   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1681   TargetLowering::ArgListTy Args;
1682   TargetLowering::ArgListEntry Entry;
1683   Entry.Node = Op;
1684   Entry.Ty = IntPtrTy;
1685   Args.push_back(Entry);
1686
1687   TargetLowering::CallLoweringInfo CLI(DAG);
1688   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1689     .setCallee(CallingConv::C, IntPtrTy,
1690                DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1691                std::move(Args), 0);
1692
1693   return LowerCallTo(CLI);
1694 }
1695
1696 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1697                                               SelectionDAG &DAG) const {
1698
1699   // FIXME: TLS addresses currently use medium model code sequences,
1700   // which is the most useful form.  Eventually support for small and
1701   // large models could be added if users need it, at the cost of
1702   // additional complexity.
1703   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1704   SDLoc dl(GA);
1705   const GlobalValue *GV = GA->getGlobal();
1706   EVT PtrVT = getPointerTy();
1707   bool is64bit = Subtarget.isPPC64();
1708   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1709   PICLevel::Level picLevel = M->getPICLevel();
1710
1711   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1712
1713   if (Model == TLSModel::LocalExec) {
1714     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1715                                                PPCII::MO_TPREL_HA);
1716     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1717                                                PPCII::MO_TPREL_LO);
1718     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1719                                      is64bit ? MVT::i64 : MVT::i32);
1720     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1721     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1722   }
1723
1724   if (Model == TLSModel::InitialExec) {
1725     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1726     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1727                                                 PPCII::MO_TLS);
1728     SDValue GOTPtr;
1729     if (is64bit) {
1730       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1731       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1732                            PtrVT, GOTReg, TGA);
1733     } else
1734       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1735     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1736                                    PtrVT, TGA, GOTPtr);
1737     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1738   }
1739
1740   if (Model == TLSModel::GeneralDynamic) {
1741     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1742                                              PPCII::MO_TLSGD);
1743     SDValue GOTPtr;
1744     if (is64bit) {
1745       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1746       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1747                                    GOTReg, TGA);
1748     } else {
1749       if (picLevel == PICLevel::Small)
1750         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1751       else
1752         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1753     }
1754     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1755                                    GOTPtr, TGA);
1756     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1757     return CallResult.first;
1758   }
1759
1760   if (Model == TLSModel::LocalDynamic) {
1761     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1762                                              PPCII::MO_TLSLD);
1763     SDValue GOTPtr;
1764     if (is64bit) {
1765       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1766       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1767                            GOTReg, TGA);
1768     } else {
1769       if (picLevel == PICLevel::Small)
1770         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1771       else
1772         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1773     }
1774     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1775                                    GOTPtr, TGA);
1776     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1777     SDValue TLSAddr = CallResult.first;
1778     SDValue Chain = CallResult.second;
1779     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1780                                       Chain, TLSAddr, TGA);
1781     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1782   }
1783
1784   llvm_unreachable("Unknown TLS model!");
1785 }
1786
1787 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1788                                               SelectionDAG &DAG) const {
1789   EVT PtrVT = Op.getValueType();
1790   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1791   SDLoc DL(GSDN);
1792   const GlobalValue *GV = GSDN->getGlobal();
1793
1794   // 64-bit SVR4 ABI code is always position-independent.
1795   // The actual address of the GlobalValue is stored in the TOC.
1796   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1797     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1798     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1799                        DAG.getRegister(PPC::X2, MVT::i64));
1800   }
1801
1802   unsigned MOHiFlag, MOLoFlag;
1803   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1804
1805   if (isPIC && Subtarget.isSVR4ABI()) {
1806     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1807                                             GSDN->getOffset(),
1808                                             PPCII::MO_PIC_FLAG);
1809     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1810                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1811   }
1812
1813   SDValue GAHi =
1814     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1815   SDValue GALo =
1816     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1817
1818   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1819
1820   // If the global reference is actually to a non-lazy-pointer, we have to do an
1821   // extra load to get the address of the global.
1822   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1823     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1824                       false, false, false, 0);
1825   return Ptr;
1826 }
1827
1828 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1829   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1830   SDLoc dl(Op);
1831
1832   if (Op.getValueType() == MVT::v2i64) {
1833     // When the operands themselves are v2i64 values, we need to do something
1834     // special because VSX has no underlying comparison operations for these.
1835     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1836       // Equality can be handled by casting to the legal type for Altivec
1837       // comparisons, everything else needs to be expanded.
1838       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1839         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1840                  DAG.getSetCC(dl, MVT::v4i32,
1841                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1842                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1843                    CC));
1844       }
1845
1846       return SDValue();
1847     }
1848
1849     // We handle most of these in the usual way.
1850     return Op;
1851   }
1852
1853   // If we're comparing for equality to zero, expose the fact that this is
1854   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1855   // fold the new nodes.
1856   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1857     if (C->isNullValue() && CC == ISD::SETEQ) {
1858       EVT VT = Op.getOperand(0).getValueType();
1859       SDValue Zext = Op.getOperand(0);
1860       if (VT.bitsLT(MVT::i32)) {
1861         VT = MVT::i32;
1862         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1863       }
1864       unsigned Log2b = Log2_32(VT.getSizeInBits());
1865       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1866       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1867                                 DAG.getConstant(Log2b, MVT::i32));
1868       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1869     }
1870     // Leave comparisons against 0 and -1 alone for now, since they're usually
1871     // optimized.  FIXME: revisit this when we can custom lower all setcc
1872     // optimizations.
1873     if (C->isAllOnesValue() || C->isNullValue())
1874       return SDValue();
1875   }
1876
1877   // If we have an integer seteq/setne, turn it into a compare against zero
1878   // by xor'ing the rhs with the lhs, which is faster than setting a
1879   // condition register, reading it back out, and masking the correct bit.  The
1880   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1881   // the result to other bit-twiddling opportunities.
1882   EVT LHSVT = Op.getOperand(0).getValueType();
1883   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1884     EVT VT = Op.getValueType();
1885     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1886                                 Op.getOperand(1));
1887     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1888   }
1889   return SDValue();
1890 }
1891
1892 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1893                                       const PPCSubtarget &Subtarget) const {
1894   SDNode *Node = Op.getNode();
1895   EVT VT = Node->getValueType(0);
1896   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1897   SDValue InChain = Node->getOperand(0);
1898   SDValue VAListPtr = Node->getOperand(1);
1899   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1900   SDLoc dl(Node);
1901
1902   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1903
1904   // gpr_index
1905   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1906                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1907                                     false, false, false, 0);
1908   InChain = GprIndex.getValue(1);
1909
1910   if (VT == MVT::i64) {
1911     // Check if GprIndex is even
1912     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1913                                  DAG.getConstant(1, MVT::i32));
1914     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1915                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1916     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1917                                           DAG.getConstant(1, MVT::i32));
1918     // Align GprIndex to be even if it isn't
1919     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1920                            GprIndex);
1921   }
1922
1923   // fpr index is 1 byte after gpr
1924   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1925                                DAG.getConstant(1, MVT::i32));
1926
1927   // fpr
1928   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1929                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1930                                     false, false, false, 0);
1931   InChain = FprIndex.getValue(1);
1932
1933   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1934                                        DAG.getConstant(8, MVT::i32));
1935
1936   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1937                                         DAG.getConstant(4, MVT::i32));
1938
1939   // areas
1940   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1941                                      MachinePointerInfo(), false, false,
1942                                      false, 0);
1943   InChain = OverflowArea.getValue(1);
1944
1945   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1946                                     MachinePointerInfo(), false, false,
1947                                     false, 0);
1948   InChain = RegSaveArea.getValue(1);
1949
1950   // select overflow_area if index > 8
1951   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1952                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1953
1954   // adjustment constant gpr_index * 4/8
1955   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1956                                     VT.isInteger() ? GprIndex : FprIndex,
1957                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1958                                                     MVT::i32));
1959
1960   // OurReg = RegSaveArea + RegConstant
1961   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1962                                RegConstant);
1963
1964   // Floating types are 32 bytes into RegSaveArea
1965   if (VT.isFloatingPoint())
1966     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1967                          DAG.getConstant(32, MVT::i32));
1968
1969   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1970   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1971                                    VT.isInteger() ? GprIndex : FprIndex,
1972                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1973                                                    MVT::i32));
1974
1975   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1976                               VT.isInteger() ? VAListPtr : FprPtr,
1977                               MachinePointerInfo(SV),
1978                               MVT::i8, false, false, 0);
1979
1980   // determine if we should load from reg_save_area or overflow_area
1981   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1982
1983   // increase overflow_area by 4/8 if gpr/fpr > 8
1984   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1985                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1986                                           MVT::i32));
1987
1988   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1989                              OverflowAreaPlusN);
1990
1991   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1992                               OverflowAreaPtr,
1993                               MachinePointerInfo(),
1994                               MVT::i32, false, false, 0);
1995
1996   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1997                      false, false, false, 0);
1998 }
1999
2000 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2001                                        const PPCSubtarget &Subtarget) const {
2002   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2003
2004   // We have to copy the entire va_list struct:
2005   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2006   return DAG.getMemcpy(Op.getOperand(0), Op,
2007                        Op.getOperand(1), Op.getOperand(2),
2008                        DAG.getConstant(12, MVT::i32), 8, false, true,
2009                        MachinePointerInfo(), MachinePointerInfo());
2010 }
2011
2012 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2013                                                   SelectionDAG &DAG) const {
2014   return Op.getOperand(0);
2015 }
2016
2017 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2018                                                 SelectionDAG &DAG) const {
2019   SDValue Chain = Op.getOperand(0);
2020   SDValue Trmp = Op.getOperand(1); // trampoline
2021   SDValue FPtr = Op.getOperand(2); // nested function
2022   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2023   SDLoc dl(Op);
2024
2025   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2026   bool isPPC64 = (PtrVT == MVT::i64);
2027   Type *IntPtrTy =
2028     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2029                                                              *DAG.getContext());
2030
2031   TargetLowering::ArgListTy Args;
2032   TargetLowering::ArgListEntry Entry;
2033
2034   Entry.Ty = IntPtrTy;
2035   Entry.Node = Trmp; Args.push_back(Entry);
2036
2037   // TrampSize == (isPPC64 ? 48 : 40);
2038   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2039                                isPPC64 ? MVT::i64 : MVT::i32);
2040   Args.push_back(Entry);
2041
2042   Entry.Node = FPtr; Args.push_back(Entry);
2043   Entry.Node = Nest; Args.push_back(Entry);
2044
2045   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2046   TargetLowering::CallLoweringInfo CLI(DAG);
2047   CLI.setDebugLoc(dl).setChain(Chain)
2048     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2049                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2050                std::move(Args), 0);
2051
2052   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2053   return CallResult.second;
2054 }
2055
2056 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2057                                         const PPCSubtarget &Subtarget) const {
2058   MachineFunction &MF = DAG.getMachineFunction();
2059   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2060
2061   SDLoc dl(Op);
2062
2063   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2064     // vastart just stores the address of the VarArgsFrameIndex slot into the
2065     // memory location argument.
2066     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2067     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2068     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2069     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2070                         MachinePointerInfo(SV),
2071                         false, false, 0);
2072   }
2073
2074   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2075   // We suppose the given va_list is already allocated.
2076   //
2077   // typedef struct {
2078   //  char gpr;     /* index into the array of 8 GPRs
2079   //                 * stored in the register save area
2080   //                 * gpr=0 corresponds to r3,
2081   //                 * gpr=1 to r4, etc.
2082   //                 */
2083   //  char fpr;     /* index into the array of 8 FPRs
2084   //                 * stored in the register save area
2085   //                 * fpr=0 corresponds to f1,
2086   //                 * fpr=1 to f2, etc.
2087   //                 */
2088   //  char *overflow_arg_area;
2089   //                /* location on stack that holds
2090   //                 * the next overflow argument
2091   //                 */
2092   //  char *reg_save_area;
2093   //               /* where r3:r10 and f1:f8 (if saved)
2094   //                * are stored
2095   //                */
2096   // } va_list[1];
2097
2098
2099   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2100   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2101
2102
2103   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2104
2105   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2106                                             PtrVT);
2107   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2108                                  PtrVT);
2109
2110   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2111   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2112
2113   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2114   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2115
2116   uint64_t FPROffset = 1;
2117   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2118
2119   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2120
2121   // Store first byte : number of int regs
2122   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2123                                          Op.getOperand(1),
2124                                          MachinePointerInfo(SV),
2125                                          MVT::i8, false, false, 0);
2126   uint64_t nextOffset = FPROffset;
2127   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2128                                   ConstFPROffset);
2129
2130   // Store second byte : number of float regs
2131   SDValue secondStore =
2132     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2133                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2134                       false, false, 0);
2135   nextOffset += StackOffset;
2136   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2137
2138   // Store second word : arguments given on stack
2139   SDValue thirdStore =
2140     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2141                  MachinePointerInfo(SV, nextOffset),
2142                  false, false, 0);
2143   nextOffset += FrameOffset;
2144   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2145
2146   // Store third word : arguments given in registers
2147   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2148                       MachinePointerInfo(SV, nextOffset),
2149                       false, false, 0);
2150
2151 }
2152
2153 #include "PPCGenCallingConv.inc"
2154
2155 // Function whose sole purpose is to kill compiler warnings 
2156 // stemming from unused functions included from PPCGenCallingConv.inc.
2157 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2158   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2159 }
2160
2161 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2162                                       CCValAssign::LocInfo &LocInfo,
2163                                       ISD::ArgFlagsTy &ArgFlags,
2164                                       CCState &State) {
2165   return true;
2166 }
2167
2168 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2169                                              MVT &LocVT,
2170                                              CCValAssign::LocInfo &LocInfo,
2171                                              ISD::ArgFlagsTy &ArgFlags,
2172                                              CCState &State) {
2173   static const MCPhysReg ArgRegs[] = {
2174     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2175     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2176   };
2177   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2178
2179   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2180
2181   // Skip one register if the first unallocated register has an even register
2182   // number and there are still argument registers available which have not been
2183   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2184   // need to skip a register if RegNum is odd.
2185   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2186     State.AllocateReg(ArgRegs[RegNum]);
2187   }
2188
2189   // Always return false here, as this function only makes sure that the first
2190   // unallocated register has an odd register number and does not actually
2191   // allocate a register for the current argument.
2192   return false;
2193 }
2194
2195 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2196                                                MVT &LocVT,
2197                                                CCValAssign::LocInfo &LocInfo,
2198                                                ISD::ArgFlagsTy &ArgFlags,
2199                                                CCState &State) {
2200   static const MCPhysReg ArgRegs[] = {
2201     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2202     PPC::F8
2203   };
2204
2205   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2206
2207   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2208
2209   // If there is only one Floating-point register left we need to put both f64
2210   // values of a split ppc_fp128 value on the stack.
2211   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2212     State.AllocateReg(ArgRegs[RegNum]);
2213   }
2214
2215   // Always return false here, as this function only makes sure that the two f64
2216   // values a ppc_fp128 value is split into are both passed in registers or both
2217   // passed on the stack and does not actually allocate a register for the
2218   // current argument.
2219   return false;
2220 }
2221
2222 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2223 /// on Darwin.
2224 static const MCPhysReg *GetFPR() {
2225   static const MCPhysReg FPR[] = {
2226     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2227     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2228   };
2229
2230   return FPR;
2231 }
2232
2233 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2234 /// the stack.
2235 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2236                                        unsigned PtrByteSize) {
2237   unsigned ArgSize = ArgVT.getStoreSize();
2238   if (Flags.isByVal())
2239     ArgSize = Flags.getByValSize();
2240
2241   // Round up to multiples of the pointer size, except for array members,
2242   // which are always packed.
2243   if (!Flags.isInConsecutiveRegs())
2244     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2245
2246   return ArgSize;
2247 }
2248
2249 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2250 /// on the stack.
2251 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2252                                             ISD::ArgFlagsTy Flags,
2253                                             unsigned PtrByteSize) {
2254   unsigned Align = PtrByteSize;
2255
2256   // Altivec parameters are padded to a 16 byte boundary.
2257   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2258       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2259       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2260     Align = 16;
2261
2262   // ByVal parameters are aligned as requested.
2263   if (Flags.isByVal()) {
2264     unsigned BVAlign = Flags.getByValAlign();
2265     if (BVAlign > PtrByteSize) {
2266       if (BVAlign % PtrByteSize != 0)
2267           llvm_unreachable(
2268             "ByVal alignment is not a multiple of the pointer size");
2269
2270       Align = BVAlign;
2271     }
2272   }
2273
2274   // Array members are always packed to their original alignment.
2275   if (Flags.isInConsecutiveRegs()) {
2276     // If the array member was split into multiple registers, the first
2277     // needs to be aligned to the size of the full type.  (Except for
2278     // ppcf128, which is only aligned as its f64 components.)
2279     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2280       Align = OrigVT.getStoreSize();
2281     else
2282       Align = ArgVT.getStoreSize();
2283   }
2284
2285   return Align;
2286 }
2287
2288 /// CalculateStackSlotUsed - Return whether this argument will use its
2289 /// stack slot (instead of being passed in registers).  ArgOffset,
2290 /// AvailableFPRs, and AvailableVRs must hold the current argument
2291 /// position, and will be updated to account for this argument.
2292 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2293                                    ISD::ArgFlagsTy Flags,
2294                                    unsigned PtrByteSize,
2295                                    unsigned LinkageSize,
2296                                    unsigned ParamAreaSize,
2297                                    unsigned &ArgOffset,
2298                                    unsigned &AvailableFPRs,
2299                                    unsigned &AvailableVRs) {
2300   bool UseMemory = false;
2301
2302   // Respect alignment of argument on the stack.
2303   unsigned Align =
2304     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2305   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2306   // If there's no space left in the argument save area, we must
2307   // use memory (this check also catches zero-sized arguments).
2308   if (ArgOffset >= LinkageSize + ParamAreaSize)
2309     UseMemory = true;
2310
2311   // Allocate argument on the stack.
2312   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2313   if (Flags.isInConsecutiveRegsLast())
2314     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2315   // If we overran the argument save area, we must use memory
2316   // (this check catches arguments passed partially in memory)
2317   if (ArgOffset > LinkageSize + ParamAreaSize)
2318     UseMemory = true;
2319
2320   // However, if the argument is actually passed in an FPR or a VR,
2321   // we don't use memory after all.
2322   if (!Flags.isByVal()) {
2323     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2324       if (AvailableFPRs > 0) {
2325         --AvailableFPRs;
2326         return false;
2327       }
2328     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2329         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2330         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2331       if (AvailableVRs > 0) {
2332         --AvailableVRs;
2333         return false;
2334       }
2335   }
2336
2337   return UseMemory;
2338 }
2339
2340 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2341 /// ensure minimum alignment required for target.
2342 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2343                                      unsigned NumBytes) {
2344   unsigned TargetAlign =
2345       Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2346   unsigned AlignMask = TargetAlign - 1;
2347   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2348   return NumBytes;
2349 }
2350
2351 SDValue
2352 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2353                                         CallingConv::ID CallConv, bool isVarArg,
2354                                         const SmallVectorImpl<ISD::InputArg>
2355                                           &Ins,
2356                                         SDLoc dl, SelectionDAG &DAG,
2357                                         SmallVectorImpl<SDValue> &InVals)
2358                                           const {
2359   if (Subtarget.isSVR4ABI()) {
2360     if (Subtarget.isPPC64())
2361       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2362                                          dl, DAG, InVals);
2363     else
2364       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2365                                          dl, DAG, InVals);
2366   } else {
2367     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2368                                        dl, DAG, InVals);
2369   }
2370 }
2371
2372 SDValue
2373 PPCTargetLowering::LowerFormalArguments_32SVR4(
2374                                       SDValue Chain,
2375                                       CallingConv::ID CallConv, bool isVarArg,
2376                                       const SmallVectorImpl<ISD::InputArg>
2377                                         &Ins,
2378                                       SDLoc dl, SelectionDAG &DAG,
2379                                       SmallVectorImpl<SDValue> &InVals) const {
2380
2381   // 32-bit SVR4 ABI Stack Frame Layout:
2382   //              +-----------------------------------+
2383   //        +-->  |            Back chain             |
2384   //        |     +-----------------------------------+
2385   //        |     | Floating-point register save area |
2386   //        |     +-----------------------------------+
2387   //        |     |    General register save area     |
2388   //        |     +-----------------------------------+
2389   //        |     |          CR save word             |
2390   //        |     +-----------------------------------+
2391   //        |     |         VRSAVE save word          |
2392   //        |     +-----------------------------------+
2393   //        |     |         Alignment padding         |
2394   //        |     +-----------------------------------+
2395   //        |     |     Vector register save area     |
2396   //        |     +-----------------------------------+
2397   //        |     |       Local variable space        |
2398   //        |     +-----------------------------------+
2399   //        |     |        Parameter list area        |
2400   //        |     +-----------------------------------+
2401   //        |     |           LR save word            |
2402   //        |     +-----------------------------------+
2403   // SP-->  +---  |            Back chain             |
2404   //              +-----------------------------------+
2405   //
2406   // Specifications:
2407   //   System V Application Binary Interface PowerPC Processor Supplement
2408   //   AltiVec Technology Programming Interface Manual
2409
2410   MachineFunction &MF = DAG.getMachineFunction();
2411   MachineFrameInfo *MFI = MF.getFrameInfo();
2412   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2413
2414   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2415   // Potential tail calls could cause overwriting of argument stack slots.
2416   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2417                        (CallConv == CallingConv::Fast));
2418   unsigned PtrByteSize = 4;
2419
2420   // Assign locations to all of the incoming arguments.
2421   SmallVector<CCValAssign, 16> ArgLocs;
2422   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2423                  *DAG.getContext());
2424
2425   // Reserve space for the linkage area on the stack.
2426   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2427   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2428
2429   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2430
2431   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2432     CCValAssign &VA = ArgLocs[i];
2433
2434     // Arguments stored in registers.
2435     if (VA.isRegLoc()) {
2436       const TargetRegisterClass *RC;
2437       EVT ValVT = VA.getValVT();
2438
2439       switch (ValVT.getSimpleVT().SimpleTy) {
2440         default:
2441           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2442         case MVT::i1:
2443         case MVT::i32:
2444           RC = &PPC::GPRCRegClass;
2445           break;
2446         case MVT::f32:
2447           RC = &PPC::F4RCRegClass;
2448           break;
2449         case MVT::f64:
2450           if (Subtarget.hasVSX())
2451             RC = &PPC::VSFRCRegClass;
2452           else
2453             RC = &PPC::F8RCRegClass;
2454           break;
2455         case MVT::v16i8:
2456         case MVT::v8i16:
2457         case MVT::v4i32:
2458         case MVT::v4f32:
2459           RC = &PPC::VRRCRegClass;
2460           break;
2461         case MVT::v2f64:
2462         case MVT::v2i64:
2463           RC = &PPC::VSHRCRegClass;
2464           break;
2465       }
2466
2467       // Transform the arguments stored in physical registers into virtual ones.
2468       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2469       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2470                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2471
2472       if (ValVT == MVT::i1)
2473         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2474
2475       InVals.push_back(ArgValue);
2476     } else {
2477       // Argument stored in memory.
2478       assert(VA.isMemLoc());
2479
2480       unsigned ArgSize = VA.getLocVT().getStoreSize();
2481       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2482                                       isImmutable);
2483
2484       // Create load nodes to retrieve arguments from the stack.
2485       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2486       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2487                                    MachinePointerInfo(),
2488                                    false, false, false, 0));
2489     }
2490   }
2491
2492   // Assign locations to all of the incoming aggregate by value arguments.
2493   // Aggregates passed by value are stored in the local variable space of the
2494   // caller's stack frame, right above the parameter list area.
2495   SmallVector<CCValAssign, 16> ByValArgLocs;
2496   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2497                       ByValArgLocs, *DAG.getContext());
2498
2499   // Reserve stack space for the allocations in CCInfo.
2500   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2501
2502   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2503
2504   // Area that is at least reserved in the caller of this function.
2505   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2506   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2507
2508   // Set the size that is at least reserved in caller of this function.  Tail
2509   // call optimized function's reserved stack space needs to be aligned so that
2510   // taking the difference between two stack areas will result in an aligned
2511   // stack.
2512   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2513   FuncInfo->setMinReservedArea(MinReservedArea);
2514
2515   SmallVector<SDValue, 8> MemOps;
2516
2517   // If the function takes variable number of arguments, make a frame index for
2518   // the start of the first vararg value... for expansion of llvm.va_start.
2519   if (isVarArg) {
2520     static const MCPhysReg GPArgRegs[] = {
2521       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2522       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2523     };
2524     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2525
2526     static const MCPhysReg FPArgRegs[] = {
2527       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2528       PPC::F8
2529     };
2530     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2531     if (DisablePPCFloatInVariadic)
2532       NumFPArgRegs = 0;
2533
2534     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2535                                                           NumGPArgRegs));
2536     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2537                                                           NumFPArgRegs));
2538
2539     // Make room for NumGPArgRegs and NumFPArgRegs.
2540     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2541                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2542
2543     FuncInfo->setVarArgsStackOffset(
2544       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2545                              CCInfo.getNextStackOffset(), true));
2546
2547     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2548     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2549
2550     // The fixed integer arguments of a variadic function are stored to the
2551     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2552     // the result of va_next.
2553     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2554       // Get an existing live-in vreg, or add a new one.
2555       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2556       if (!VReg)
2557         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2558
2559       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2560       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2561                                    MachinePointerInfo(), false, false, 0);
2562       MemOps.push_back(Store);
2563       // Increment the address by four for the next argument to store
2564       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2565       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2566     }
2567
2568     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2569     // is set.
2570     // The double arguments are stored to the VarArgsFrameIndex
2571     // on the stack.
2572     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2573       // Get an existing live-in vreg, or add a new one.
2574       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2575       if (!VReg)
2576         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2577
2578       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2579       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2580                                    MachinePointerInfo(), false, false, 0);
2581       MemOps.push_back(Store);
2582       // Increment the address by eight for the next argument to store
2583       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2584                                          PtrVT);
2585       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2586     }
2587   }
2588
2589   if (!MemOps.empty())
2590     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2591
2592   return Chain;
2593 }
2594
2595 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2596 // value to MVT::i64 and then truncate to the correct register size.
2597 SDValue
2598 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2599                                      SelectionDAG &DAG, SDValue ArgVal,
2600                                      SDLoc dl) const {
2601   if (Flags.isSExt())
2602     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2603                          DAG.getValueType(ObjectVT));
2604   else if (Flags.isZExt())
2605     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2606                          DAG.getValueType(ObjectVT));
2607
2608   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2609 }
2610
2611 SDValue
2612 PPCTargetLowering::LowerFormalArguments_64SVR4(
2613                                       SDValue Chain,
2614                                       CallingConv::ID CallConv, bool isVarArg,
2615                                       const SmallVectorImpl<ISD::InputArg>
2616                                         &Ins,
2617                                       SDLoc dl, SelectionDAG &DAG,
2618                                       SmallVectorImpl<SDValue> &InVals) const {
2619   // TODO: add description of PPC stack frame format, or at least some docs.
2620   //
2621   bool isELFv2ABI = Subtarget.isELFv2ABI();
2622   bool isLittleEndian = Subtarget.isLittleEndian();
2623   MachineFunction &MF = DAG.getMachineFunction();
2624   MachineFrameInfo *MFI = MF.getFrameInfo();
2625   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2626
2627   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2628   // Potential tail calls could cause overwriting of argument stack slots.
2629   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2630                        (CallConv == CallingConv::Fast));
2631   unsigned PtrByteSize = 8;
2632
2633   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2634                                                           isELFv2ABI);
2635
2636   static const MCPhysReg GPR[] = {
2637     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2638     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2639   };
2640
2641   static const MCPhysReg *FPR = GetFPR();
2642
2643   static const MCPhysReg VR[] = {
2644     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2645     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2646   };
2647   static const MCPhysReg VSRH[] = {
2648     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2649     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2650   };
2651
2652   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2653   const unsigned Num_FPR_Regs = 13;
2654   const unsigned Num_VR_Regs  = array_lengthof(VR);
2655
2656   // Do a first pass over the arguments to determine whether the ABI
2657   // guarantees that our caller has allocated the parameter save area
2658   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2659   // in the ELFv2 ABI, it is true if this is a vararg function or if
2660   // any parameter is located in a stack slot.
2661
2662   bool HasParameterArea = !isELFv2ABI || isVarArg;
2663   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2664   unsigned NumBytes = LinkageSize;
2665   unsigned AvailableFPRs = Num_FPR_Regs;
2666   unsigned AvailableVRs = Num_VR_Regs;
2667   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2668     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2669                                PtrByteSize, LinkageSize, ParamAreaSize,
2670                                NumBytes, AvailableFPRs, AvailableVRs))
2671       HasParameterArea = true;
2672
2673   // Add DAG nodes to load the arguments or copy them out of registers.  On
2674   // entry to a function on PPC, the arguments start after the linkage area,
2675   // although the first ones are often in registers.
2676
2677   unsigned ArgOffset = LinkageSize;
2678   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2679   SmallVector<SDValue, 8> MemOps;
2680   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2681   unsigned CurArgIdx = 0;
2682   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2683     SDValue ArgVal;
2684     bool needsLoad = false;
2685     EVT ObjectVT = Ins[ArgNo].VT;
2686     EVT OrigVT = Ins[ArgNo].ArgVT;
2687     unsigned ObjSize = ObjectVT.getStoreSize();
2688     unsigned ArgSize = ObjSize;
2689     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2690     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2691     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2692
2693     /* Respect alignment of argument on the stack.  */
2694     unsigned Align =
2695       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2696     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2697     unsigned CurArgOffset = ArgOffset;
2698
2699     /* Compute GPR index associated with argument offset.  */
2700     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2701     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2702
2703     // FIXME the codegen can be much improved in some cases.
2704     // We do not have to keep everything in memory.
2705     if (Flags.isByVal()) {
2706       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2707       ObjSize = Flags.getByValSize();
2708       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2709       // Empty aggregate parameters do not take up registers.  Examples:
2710       //   struct { } a;
2711       //   union  { } b;
2712       //   int c[0];
2713       // etc.  However, we have to provide a place-holder in InVals, so
2714       // pretend we have an 8-byte item at the current address for that
2715       // purpose.
2716       if (!ObjSize) {
2717         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2718         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2719         InVals.push_back(FIN);
2720         continue;
2721       }
2722
2723       // Create a stack object covering all stack doublewords occupied
2724       // by the argument.  If the argument is (fully or partially) on
2725       // the stack, or if the argument is fully in registers but the
2726       // caller has allocated the parameter save anyway, we can refer
2727       // directly to the caller's stack frame.  Otherwise, create a
2728       // local copy in our own frame.
2729       int FI;
2730       if (HasParameterArea ||
2731           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2732         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2733       else
2734         FI = MFI->CreateStackObject(ArgSize, Align, false);
2735       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2736
2737       // Handle aggregates smaller than 8 bytes.
2738       if (ObjSize < PtrByteSize) {
2739         // The value of the object is its address, which differs from the
2740         // address of the enclosing doubleword on big-endian systems.
2741         SDValue Arg = FIN;
2742         if (!isLittleEndian) {
2743           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2744           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2745         }
2746         InVals.push_back(Arg);
2747
2748         if (GPR_idx != Num_GPR_Regs) {
2749           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2750           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2751           SDValue Store;
2752
2753           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2754             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2755                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2756             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2757                                       MachinePointerInfo(FuncArg),
2758                                       ObjType, false, false, 0);
2759           } else {
2760             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2761             // store the whole register as-is to the parameter save area
2762             // slot.
2763             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2764                                  MachinePointerInfo(FuncArg),
2765                                  false, false, 0);
2766           }
2767
2768           MemOps.push_back(Store);
2769         }
2770         // Whether we copied from a register or not, advance the offset
2771         // into the parameter save area by a full doubleword.
2772         ArgOffset += PtrByteSize;
2773         continue;
2774       }
2775
2776       // The value of the object is its address, which is the address of
2777       // its first stack doubleword.
2778       InVals.push_back(FIN);
2779
2780       // Store whatever pieces of the object are in registers to memory.
2781       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2782         if (GPR_idx == Num_GPR_Regs)
2783           break;
2784
2785         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2786         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2787         SDValue Addr = FIN;
2788         if (j) {
2789           SDValue Off = DAG.getConstant(j, PtrVT);
2790           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2791         }
2792         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2793                                      MachinePointerInfo(FuncArg, j),
2794                                      false, false, 0);
2795         MemOps.push_back(Store);
2796         ++GPR_idx;
2797       }
2798       ArgOffset += ArgSize;
2799       continue;
2800     }
2801
2802     switch (ObjectVT.getSimpleVT().SimpleTy) {
2803     default: llvm_unreachable("Unhandled argument type!");
2804     case MVT::i1:
2805     case MVT::i32:
2806     case MVT::i64:
2807       // These can be scalar arguments or elements of an integer array type
2808       // passed directly.  Clang may use those instead of "byval" aggregate
2809       // types to avoid forcing arguments to memory unnecessarily.
2810       if (GPR_idx != Num_GPR_Regs) {
2811         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2812         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2813
2814         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2815           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2816           // value to MVT::i64 and then truncate to the correct register size.
2817           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2818       } else {
2819         needsLoad = true;
2820         ArgSize = PtrByteSize;
2821       }
2822       ArgOffset += 8;
2823       break;
2824
2825     case MVT::f32:
2826     case MVT::f64:
2827       // These can be scalar arguments or elements of a float array type
2828       // passed directly.  The latter are used to implement ELFv2 homogenous
2829       // float aggregates.
2830       if (FPR_idx != Num_FPR_Regs) {
2831         unsigned VReg;
2832
2833         if (ObjectVT == MVT::f32)
2834           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2835         else
2836           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2837                                             &PPC::VSFRCRegClass :
2838                                             &PPC::F8RCRegClass);
2839
2840         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2841         ++FPR_idx;
2842       } else if (GPR_idx != Num_GPR_Regs) {
2843         // This can only ever happen in the presence of f32 array types,
2844         // since otherwise we never run out of FPRs before running out
2845         // of GPRs.
2846         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2847         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2848
2849         if (ObjectVT == MVT::f32) {
2850           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2851             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2852                                  DAG.getConstant(32, MVT::i32));
2853           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2854         }
2855
2856         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2857       } else {
2858         needsLoad = true;
2859       }
2860
2861       // When passing an array of floats, the array occupies consecutive
2862       // space in the argument area; only round up to the next doubleword
2863       // at the end of the array.  Otherwise, each float takes 8 bytes.
2864       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2865       ArgOffset += ArgSize;
2866       if (Flags.isInConsecutiveRegsLast())
2867         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2868       break;
2869     case MVT::v4f32:
2870     case MVT::v4i32:
2871     case MVT::v8i16:
2872     case MVT::v16i8:
2873     case MVT::v2f64:
2874     case MVT::v2i64:
2875       // These can be scalar arguments or elements of a vector array type
2876       // passed directly.  The latter are used to implement ELFv2 homogenous
2877       // vector aggregates.
2878       if (VR_idx != Num_VR_Regs) {
2879         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2880                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2881                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2882         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2883         ++VR_idx;
2884       } else {
2885         needsLoad = true;
2886       }
2887       ArgOffset += 16;
2888       break;
2889     }
2890
2891     // We need to load the argument to a virtual register if we determined
2892     // above that we ran out of physical registers of the appropriate type.
2893     if (needsLoad) {
2894       if (ObjSize < ArgSize && !isLittleEndian)
2895         CurArgOffset += ArgSize - ObjSize;
2896       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2897       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2898       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2899                            false, false, false, 0);
2900     }
2901
2902     InVals.push_back(ArgVal);
2903   }
2904
2905   // Area that is at least reserved in the caller of this function.
2906   unsigned MinReservedArea;
2907   if (HasParameterArea)
2908     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2909   else
2910     MinReservedArea = LinkageSize;
2911
2912   // Set the size that is at least reserved in caller of this function.  Tail
2913   // call optimized functions' reserved stack space needs to be aligned so that
2914   // taking the difference between two stack areas will result in an aligned
2915   // stack.
2916   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2917   FuncInfo->setMinReservedArea(MinReservedArea);
2918
2919   // If the function takes variable number of arguments, make a frame index for
2920   // the start of the first vararg value... for expansion of llvm.va_start.
2921   if (isVarArg) {
2922     int Depth = ArgOffset;
2923
2924     FuncInfo->setVarArgsFrameIndex(
2925       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2926     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2927
2928     // If this function is vararg, store any remaining integer argument regs
2929     // to their spots on the stack so that they may be loaded by deferencing the
2930     // result of va_next.
2931     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2932          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2933       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2934       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2935       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2936                                    MachinePointerInfo(), false, false, 0);
2937       MemOps.push_back(Store);
2938       // Increment the address by four for the next argument to store
2939       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2940       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2941     }
2942   }
2943
2944   if (!MemOps.empty())
2945     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2946
2947   return Chain;
2948 }
2949
2950 SDValue
2951 PPCTargetLowering::LowerFormalArguments_Darwin(
2952                                       SDValue Chain,
2953                                       CallingConv::ID CallConv, bool isVarArg,
2954                                       const SmallVectorImpl<ISD::InputArg>
2955                                         &Ins,
2956                                       SDLoc dl, SelectionDAG &DAG,
2957                                       SmallVectorImpl<SDValue> &InVals) const {
2958   // TODO: add description of PPC stack frame format, or at least some docs.
2959   //
2960   MachineFunction &MF = DAG.getMachineFunction();
2961   MachineFrameInfo *MFI = MF.getFrameInfo();
2962   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2963
2964   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2965   bool isPPC64 = PtrVT == MVT::i64;
2966   // Potential tail calls could cause overwriting of argument stack slots.
2967   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2968                        (CallConv == CallingConv::Fast));
2969   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2970
2971   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2972                                                           false);
2973   unsigned ArgOffset = LinkageSize;
2974   // Area that is at least reserved in caller of this function.
2975   unsigned MinReservedArea = ArgOffset;
2976
2977   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2978     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2979     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2980   };
2981   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2982     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2983     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2984   };
2985
2986   static const MCPhysReg *FPR = GetFPR();
2987
2988   static const MCPhysReg VR[] = {
2989     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2990     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2991   };
2992
2993   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2994   const unsigned Num_FPR_Regs = 13;
2995   const unsigned Num_VR_Regs  = array_lengthof( VR);
2996
2997   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2998
2999   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3000
3001   // In 32-bit non-varargs functions, the stack space for vectors is after the
3002   // stack space for non-vectors.  We do not use this space unless we have
3003   // too many vectors to fit in registers, something that only occurs in
3004   // constructed examples:), but we have to walk the arglist to figure
3005   // that out...for the pathological case, compute VecArgOffset as the
3006   // start of the vector parameter area.  Computing VecArgOffset is the
3007   // entire point of the following loop.
3008   unsigned VecArgOffset = ArgOffset;
3009   if (!isVarArg && !isPPC64) {
3010     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3011          ++ArgNo) {
3012       EVT ObjectVT = Ins[ArgNo].VT;
3013       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3014
3015       if (Flags.isByVal()) {
3016         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3017         unsigned ObjSize = Flags.getByValSize();
3018         unsigned ArgSize =
3019                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3020         VecArgOffset += ArgSize;
3021         continue;
3022       }
3023
3024       switch(ObjectVT.getSimpleVT().SimpleTy) {
3025       default: llvm_unreachable("Unhandled argument type!");
3026       case MVT::i1:
3027       case MVT::i32:
3028       case MVT::f32:
3029         VecArgOffset += 4;
3030         break;
3031       case MVT::i64:  // PPC64
3032       case MVT::f64:
3033         // FIXME: We are guaranteed to be !isPPC64 at this point.
3034         // Does MVT::i64 apply?
3035         VecArgOffset += 8;
3036         break;
3037       case MVT::v4f32:
3038       case MVT::v4i32:
3039       case MVT::v8i16:
3040       case MVT::v16i8:
3041         // Nothing to do, we're only looking at Nonvector args here.
3042         break;
3043       }
3044     }
3045   }
3046   // We've found where the vector parameter area in memory is.  Skip the
3047   // first 12 parameters; these don't use that memory.
3048   VecArgOffset = ((VecArgOffset+15)/16)*16;
3049   VecArgOffset += 12*16;
3050
3051   // Add DAG nodes to load the arguments or copy them out of registers.  On
3052   // entry to a function on PPC, the arguments start after the linkage area,
3053   // although the first ones are often in registers.
3054
3055   SmallVector<SDValue, 8> MemOps;
3056   unsigned nAltivecParamsAtEnd = 0;
3057   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3058   unsigned CurArgIdx = 0;
3059   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3060     SDValue ArgVal;
3061     bool needsLoad = false;
3062     EVT ObjectVT = Ins[ArgNo].VT;
3063     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3064     unsigned ArgSize = ObjSize;
3065     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3066     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3067     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3068
3069     unsigned CurArgOffset = ArgOffset;
3070
3071     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3072     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3073         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3074       if (isVarArg || isPPC64) {
3075         MinReservedArea = ((MinReservedArea+15)/16)*16;
3076         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3077                                                   Flags,
3078                                                   PtrByteSize);
3079       } else  nAltivecParamsAtEnd++;
3080     } else
3081       // Calculate min reserved area.
3082       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3083                                                 Flags,
3084                                                 PtrByteSize);
3085
3086     // FIXME the codegen can be much improved in some cases.
3087     // We do not have to keep everything in memory.
3088     if (Flags.isByVal()) {
3089       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3090       ObjSize = Flags.getByValSize();
3091       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3092       // Objects of size 1 and 2 are right justified, everything else is
3093       // left justified.  This means the memory address is adjusted forwards.
3094       if (ObjSize==1 || ObjSize==2) {
3095         CurArgOffset = CurArgOffset + (4 - ObjSize);
3096       }
3097       // The value of the object is its address.
3098       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3099       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3100       InVals.push_back(FIN);
3101       if (ObjSize==1 || ObjSize==2) {
3102         if (GPR_idx != Num_GPR_Regs) {
3103           unsigned VReg;
3104           if (isPPC64)
3105             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3106           else
3107             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3108           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3109           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3110           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3111                                             MachinePointerInfo(FuncArg),
3112                                             ObjType, false, false, 0);
3113           MemOps.push_back(Store);
3114           ++GPR_idx;
3115         }
3116
3117         ArgOffset += PtrByteSize;
3118
3119         continue;
3120       }
3121       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3122         // Store whatever pieces of the object are in registers
3123         // to memory.  ArgOffset will be the address of the beginning
3124         // of the object.
3125         if (GPR_idx != Num_GPR_Regs) {
3126           unsigned VReg;
3127           if (isPPC64)
3128             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3129           else
3130             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3131           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3132           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3133           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3134           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3135                                        MachinePointerInfo(FuncArg, j),
3136                                        false, false, 0);
3137           MemOps.push_back(Store);
3138           ++GPR_idx;
3139           ArgOffset += PtrByteSize;
3140         } else {
3141           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3142           break;
3143         }
3144       }
3145       continue;
3146     }
3147
3148     switch (ObjectVT.getSimpleVT().SimpleTy) {
3149     default: llvm_unreachable("Unhandled argument type!");
3150     case MVT::i1:
3151     case MVT::i32:
3152       if (!isPPC64) {
3153         if (GPR_idx != Num_GPR_Regs) {
3154           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3155           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3156
3157           if (ObjectVT == MVT::i1)
3158             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3159
3160           ++GPR_idx;
3161         } else {
3162           needsLoad = true;
3163           ArgSize = PtrByteSize;
3164         }
3165         // All int arguments reserve stack space in the Darwin ABI.
3166         ArgOffset += PtrByteSize;
3167         break;
3168       }
3169       // FALLTHROUGH
3170     case MVT::i64:  // PPC64
3171       if (GPR_idx != Num_GPR_Regs) {
3172         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3173         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3174
3175         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3176           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3177           // value to MVT::i64 and then truncate to the correct register size.
3178           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3179
3180         ++GPR_idx;
3181       } else {
3182         needsLoad = true;
3183         ArgSize = PtrByteSize;
3184       }
3185       // All int arguments reserve stack space in the Darwin ABI.
3186       ArgOffset += 8;
3187       break;
3188
3189     case MVT::f32:
3190     case MVT::f64:
3191       // Every 4 bytes of argument space consumes one of the GPRs available for
3192       // argument passing.
3193       if (GPR_idx != Num_GPR_Regs) {
3194         ++GPR_idx;
3195         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3196           ++GPR_idx;
3197       }
3198       if (FPR_idx != Num_FPR_Regs) {
3199         unsigned VReg;
3200
3201         if (ObjectVT == MVT::f32)
3202           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3203         else
3204           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3205
3206         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3207         ++FPR_idx;
3208       } else {
3209         needsLoad = true;
3210       }
3211
3212       // All FP arguments reserve stack space in the Darwin ABI.
3213       ArgOffset += isPPC64 ? 8 : ObjSize;
3214       break;
3215     case MVT::v4f32:
3216     case MVT::v4i32:
3217     case MVT::v8i16:
3218     case MVT::v16i8:
3219       // Note that vector arguments in registers don't reserve stack space,
3220       // except in varargs functions.
3221       if (VR_idx != Num_VR_Regs) {
3222         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3223         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3224         if (isVarArg) {
3225           while ((ArgOffset % 16) != 0) {
3226             ArgOffset += PtrByteSize;
3227             if (GPR_idx != Num_GPR_Regs)
3228               GPR_idx++;
3229           }
3230           ArgOffset += 16;
3231           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3232         }
3233         ++VR_idx;
3234       } else {
3235         if (!isVarArg && !isPPC64) {
3236           // Vectors go after all the nonvectors.
3237           CurArgOffset = VecArgOffset;
3238           VecArgOffset += 16;
3239         } else {
3240           // Vectors are aligned.
3241           ArgOffset = ((ArgOffset+15)/16)*16;
3242           CurArgOffset = ArgOffset;
3243           ArgOffset += 16;
3244         }
3245         needsLoad = true;
3246       }
3247       break;
3248     }
3249
3250     // We need to load the argument to a virtual register if we determined above
3251     // that we ran out of physical registers of the appropriate type.
3252     if (needsLoad) {
3253       int FI = MFI->CreateFixedObject(ObjSize,
3254                                       CurArgOffset + (ArgSize - ObjSize),
3255                                       isImmutable);
3256       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3257       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3258                            false, false, false, 0);
3259     }
3260
3261     InVals.push_back(ArgVal);
3262   }
3263
3264   // Allow for Altivec parameters at the end, if needed.
3265   if (nAltivecParamsAtEnd) {
3266     MinReservedArea = ((MinReservedArea+15)/16)*16;
3267     MinReservedArea += 16*nAltivecParamsAtEnd;
3268   }
3269
3270   // Area that is at least reserved in the caller of this function.
3271   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3272
3273   // Set the size that is at least reserved in caller of this function.  Tail
3274   // call optimized functions' reserved stack space needs to be aligned so that
3275   // taking the difference between two stack areas will result in an aligned
3276   // stack.
3277   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3278   FuncInfo->setMinReservedArea(MinReservedArea);
3279
3280   // If the function takes variable number of arguments, make a frame index for
3281   // the start of the first vararg value... for expansion of llvm.va_start.
3282   if (isVarArg) {
3283     int Depth = ArgOffset;
3284
3285     FuncInfo->setVarArgsFrameIndex(
3286       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3287                              Depth, true));
3288     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3289
3290     // If this function is vararg, store any remaining integer argument regs
3291     // to their spots on the stack so that they may be loaded by deferencing the
3292     // result of va_next.
3293     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3294       unsigned VReg;
3295
3296       if (isPPC64)
3297         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3298       else
3299         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3300
3301       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3302       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3303                                    MachinePointerInfo(), false, false, 0);
3304       MemOps.push_back(Store);
3305       // Increment the address by four for the next argument to store
3306       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3307       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3308     }
3309   }
3310
3311   if (!MemOps.empty())
3312     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3313
3314   return Chain;
3315 }
3316
3317 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3318 /// adjusted to accommodate the arguments for the tailcall.
3319 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3320                                    unsigned ParamSize) {
3321
3322   if (!isTailCall) return 0;
3323
3324   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3325   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3326   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3327   // Remember only if the new adjustement is bigger.
3328   if (SPDiff < FI->getTailCallSPDelta())
3329     FI->setTailCallSPDelta(SPDiff);
3330
3331   return SPDiff;
3332 }
3333
3334 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3335 /// for tail call optimization. Targets which want to do tail call
3336 /// optimization should implement this function.
3337 bool
3338 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3339                                                      CallingConv::ID CalleeCC,
3340                                                      bool isVarArg,
3341                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3342                                                      SelectionDAG& DAG) const {
3343   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3344     return false;
3345
3346   // Variable argument functions are not supported.
3347   if (isVarArg)
3348     return false;
3349
3350   MachineFunction &MF = DAG.getMachineFunction();
3351   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3352   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3353     // Functions containing by val parameters are not supported.
3354     for (unsigned i = 0; i != Ins.size(); i++) {
3355        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3356        if (Flags.isByVal()) return false;
3357     }
3358
3359     // Non-PIC/GOT tail calls are supported.
3360     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3361       return true;
3362
3363     // At the moment we can only do local tail calls (in same module, hidden
3364     // or protected) if we are generating PIC.
3365     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3366       return G->getGlobal()->hasHiddenVisibility()
3367           || G->getGlobal()->hasProtectedVisibility();
3368   }
3369
3370   return false;
3371 }
3372
3373 /// isCallCompatibleAddress - Return the immediate to use if the specified
3374 /// 32-bit value is representable in the immediate field of a BxA instruction.
3375 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3376   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3377   if (!C) return nullptr;
3378
3379   int Addr = C->getZExtValue();
3380   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3381       SignExtend32<26>(Addr) != Addr)
3382     return nullptr;  // Top 6 bits have to be sext of immediate.
3383
3384   return DAG.getConstant((int)C->getZExtValue() >> 2,
3385                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3386 }
3387
3388 namespace {
3389
3390 struct TailCallArgumentInfo {
3391   SDValue Arg;
3392   SDValue FrameIdxOp;
3393   int       FrameIdx;
3394
3395   TailCallArgumentInfo() : FrameIdx(0) {}
3396 };
3397
3398 }
3399
3400 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3401 static void
3402 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3403                                            SDValue Chain,
3404                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3405                    SmallVectorImpl<SDValue> &MemOpChains,
3406                    SDLoc dl) {
3407   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3408     SDValue Arg = TailCallArgs[i].Arg;
3409     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3410     int FI = TailCallArgs[i].FrameIdx;
3411     // Store relative to framepointer.
3412     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3413                                        MachinePointerInfo::getFixedStack(FI),
3414                                        false, false, 0));
3415   }
3416 }
3417
3418 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3419 /// the appropriate stack slot for the tail call optimized function call.
3420 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3421                                                MachineFunction &MF,
3422                                                SDValue Chain,
3423                                                SDValue OldRetAddr,
3424                                                SDValue OldFP,
3425                                                int SPDiff,
3426                                                bool isPPC64,
3427                                                bool isDarwinABI,
3428                                                SDLoc dl) {
3429   if (SPDiff) {
3430     // Calculate the new stack slot for the return address.
3431     int SlotSize = isPPC64 ? 8 : 4;
3432     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3433                                                                    isDarwinABI);
3434     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3435                                                           NewRetAddrLoc, true);
3436     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3437     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3438     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3439                          MachinePointerInfo::getFixedStack(NewRetAddr),
3440                          false, false, 0);
3441
3442     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3443     // slot as the FP is never overwritten.
3444     if (isDarwinABI) {
3445       int NewFPLoc =
3446         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3447       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3448                                                           true);
3449       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3450       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3451                            MachinePointerInfo::getFixedStack(NewFPIdx),
3452                            false, false, 0);
3453     }
3454   }
3455   return Chain;
3456 }
3457
3458 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3459 /// the position of the argument.
3460 static void
3461 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3462                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3463                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3464   int Offset = ArgOffset + SPDiff;
3465   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3466   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3467   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3468   SDValue FIN = DAG.getFrameIndex(FI, VT);
3469   TailCallArgumentInfo Info;
3470   Info.Arg = Arg;
3471   Info.FrameIdxOp = FIN;
3472   Info.FrameIdx = FI;
3473   TailCallArguments.push_back(Info);
3474 }
3475
3476 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3477 /// stack slot. Returns the chain as result and the loaded frame pointers in
3478 /// LROpOut/FPOpout. Used when tail calling.
3479 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3480                                                         int SPDiff,
3481                                                         SDValue Chain,
3482                                                         SDValue &LROpOut,
3483                                                         SDValue &FPOpOut,
3484                                                         bool isDarwinABI,
3485                                                         SDLoc dl) const {
3486   if (SPDiff) {
3487     // Load the LR and FP stack slot for later adjusting.
3488     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3489     LROpOut = getReturnAddrFrameIndex(DAG);
3490     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3491                           false, false, false, 0);
3492     Chain = SDValue(LROpOut.getNode(), 1);
3493
3494     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3495     // slot as the FP is never overwritten.
3496     if (isDarwinABI) {
3497       FPOpOut = getFramePointerFrameIndex(DAG);
3498       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3499                             false, false, false, 0);
3500       Chain = SDValue(FPOpOut.getNode(), 1);
3501     }
3502   }
3503   return Chain;
3504 }
3505
3506 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3507 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3508 /// specified by the specific parameter attribute. The copy will be passed as
3509 /// a byval function parameter.
3510 /// Sometimes what we are copying is the end of a larger object, the part that
3511 /// does not fit in registers.
3512 static SDValue
3513 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3514                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3515                           SDLoc dl) {
3516   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3517   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3518                        false, false, MachinePointerInfo(),
3519                        MachinePointerInfo());
3520 }
3521
3522 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3523 /// tail calls.
3524 static void
3525 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3526                  SDValue Arg, SDValue PtrOff, int SPDiff,
3527                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3528                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3529                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3530                  SDLoc dl) {
3531   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3532   if (!isTailCall) {
3533     if (isVector) {
3534       SDValue StackPtr;
3535       if (isPPC64)
3536         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3537       else
3538         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3539       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3540                            DAG.getConstant(ArgOffset, PtrVT));
3541     }
3542     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3543                                        MachinePointerInfo(), false, false, 0));
3544   // Calculate and remember argument location.
3545   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3546                                   TailCallArguments);
3547 }
3548
3549 static
3550 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3551                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3552                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3553                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3554   MachineFunction &MF = DAG.getMachineFunction();
3555
3556   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3557   // might overwrite each other in case of tail call optimization.
3558   SmallVector<SDValue, 8> MemOpChains2;
3559   // Do not flag preceding copytoreg stuff together with the following stuff.
3560   InFlag = SDValue();
3561   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3562                                     MemOpChains2, dl);
3563   if (!MemOpChains2.empty())
3564     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3565
3566   // Store the return address to the appropriate stack slot.
3567   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3568                                         isPPC64, isDarwinABI, dl);
3569
3570   // Emit callseq_end just before tailcall node.
3571   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3572                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3573   InFlag = Chain.getValue(1);
3574 }
3575
3576 static
3577 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3578                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3579                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3580                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3581                      const PPCSubtarget &Subtarget) {
3582
3583   bool isPPC64 = Subtarget.isPPC64();
3584   bool isSVR4ABI = Subtarget.isSVR4ABI();
3585   bool isELFv2ABI = Subtarget.isELFv2ABI();
3586
3587   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3588   NodeTys.push_back(MVT::Other);   // Returns a chain
3589   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3590
3591   unsigned CallOpc = PPCISD::CALL;
3592
3593   bool needIndirectCall = true;
3594   if (!isSVR4ABI || !isPPC64)
3595     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3596       // If this is an absolute destination address, use the munged value.
3597       Callee = SDValue(Dest, 0);
3598       needIndirectCall = false;
3599     }
3600
3601   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3602     unsigned OpFlags = 0;
3603     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3604          (Subtarget.getTargetTriple().isMacOSX() &&
3605           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3606          (G->getGlobal()->isDeclaration() ||
3607           G->getGlobal()->isWeakForLinker())) ||
3608         (Subtarget.isTargetELF() && !isPPC64 &&
3609          !G->getGlobal()->hasLocalLinkage() &&
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     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3618     // every direct call is) turn it into a TargetGlobalAddress /
3619     // TargetExternalSymbol node so that legalize doesn't hack it.
3620     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3621                                         Callee.getValueType(), 0, OpFlags);
3622     needIndirectCall = false;
3623   }
3624
3625   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3626     unsigned char OpFlags = 0;
3627
3628     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3629          (Subtarget.getTargetTriple().isMacOSX() &&
3630           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3631         (Subtarget.isTargetELF() && !isPPC64 &&
3632          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3633       // PC-relative references to external symbols should go through $stub,
3634       // unless we're building with the leopard linker or later, which
3635       // automatically synthesizes these stubs.
3636       OpFlags = PPCII::MO_PLT_OR_STUB;
3637     }
3638
3639     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3640                                          OpFlags);
3641     needIndirectCall = false;
3642   }
3643
3644   if (needIndirectCall) {
3645     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3646     // to do the call, we can't use PPCISD::CALL.
3647     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3648
3649     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3650       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3651       // entry point, but to the function descriptor (the function entry point
3652       // address is part of the function descriptor though).
3653       // The function descriptor is a three doubleword structure with the
3654       // following fields: function entry point, TOC base address and
3655       // environment pointer.
3656       // Thus for a call through a function pointer, the following actions need
3657       // to be performed:
3658       //   1. Save the TOC of the caller in the TOC save area of its stack
3659       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3660       //   2. Load the address of the function entry point from the function
3661       //      descriptor.
3662       //   3. Load the TOC of the callee from the function descriptor into r2.
3663       //   4. Load the environment pointer from the function descriptor into
3664       //      r11.
3665       //   5. Branch to the function entry point address.
3666       //   6. On return of the callee, the TOC of the caller needs to be
3667       //      restored (this is done in FinishCall()).
3668       //
3669       // All those operations are flagged together to ensure that no other
3670       // operations can be scheduled in between. E.g. without flagging the
3671       // operations together, a TOC access in the caller could be scheduled
3672       // between the load of the callee TOC and the branch to the callee, which
3673       // results in the TOC access going through the TOC of the callee instead
3674       // of going through the TOC of the caller, which leads to incorrect code.
3675
3676       // Load the address of the function entry point from the function
3677       // descriptor.
3678       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3679       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3680                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3681       Chain = LoadFuncPtr.getValue(1);
3682       InFlag = LoadFuncPtr.getValue(2);
3683
3684       // Load environment pointer into r11.
3685       // Offset of the environment pointer within the function descriptor.
3686       SDValue PtrOff = DAG.getIntPtrConstant(16);
3687
3688       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3689       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3690                                        InFlag);
3691       Chain = LoadEnvPtr.getValue(1);
3692       InFlag = LoadEnvPtr.getValue(2);
3693
3694       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3695                                         InFlag);
3696       Chain = EnvVal.getValue(0);
3697       InFlag = EnvVal.getValue(1);
3698
3699       // Load TOC of the callee into r2. We are using a target-specific load
3700       // with r2 hard coded, because the result of a target-independent load
3701       // would never go directly into r2, since r2 is a reserved register (which
3702       // prevents the register allocator from allocating it), resulting in an
3703       // additional register being allocated and an unnecessary move instruction
3704       // being generated.
3705       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3706       SDValue TOCOff = DAG.getIntPtrConstant(8);
3707       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3708       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3709                                        AddTOC, InFlag);
3710       Chain = LoadTOCPtr.getValue(0);
3711       InFlag = LoadTOCPtr.getValue(1);
3712
3713       MTCTROps[0] = Chain;
3714       MTCTROps[1] = LoadFuncPtr;
3715       MTCTROps[2] = InFlag;
3716     }
3717
3718     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3719                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3720     InFlag = Chain.getValue(1);
3721
3722     NodeTys.clear();
3723     NodeTys.push_back(MVT::Other);
3724     NodeTys.push_back(MVT::Glue);
3725     Ops.push_back(Chain);
3726     CallOpc = PPCISD::BCTRL;
3727     Callee.setNode(nullptr);
3728     // Add use of X11 (holding environment pointer)
3729     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3730       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3731     // Add CTR register as callee so a bctr can be emitted later.
3732     if (isTailCall)
3733       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3734   }
3735
3736   // If this is a direct call, pass the chain and the callee.
3737   if (Callee.getNode()) {
3738     Ops.push_back(Chain);
3739     Ops.push_back(Callee);
3740
3741     // If this is a call to __tls_get_addr, find the symbol whose address
3742     // is to be taken and add it to the list.  This will be used to 
3743     // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3744     // We find the symbol by walking the chain to the CopyFromReg, walking
3745     // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3746     // pulling the symbol from that node.
3747     if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3748       if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3749         assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3750         SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3751         SDValue TGTAddr = AddI->getOperand(1);
3752         assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3753                "Didn't find target global TLS address where we expected one");
3754         Ops.push_back(TGTAddr);
3755         CallOpc = PPCISD::CALL_TLS;
3756       }
3757   }
3758   // If this is a tail call add stack pointer delta.
3759   if (isTailCall)
3760     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3761
3762   // Add argument registers to the end of the list so that they are known live
3763   // into the call.
3764   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3765     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3766                                   RegsToPass[i].second.getValueType()));
3767
3768   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3769   if (Callee.getNode() && isELFv2ABI)
3770     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3771
3772   return CallOpc;
3773 }
3774
3775 static
3776 bool isLocalCall(const SDValue &Callee)
3777 {
3778   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3779     return !G->getGlobal()->isDeclaration() &&
3780            !G->getGlobal()->isWeakForLinker();
3781   return false;
3782 }
3783
3784 SDValue
3785 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3786                                    CallingConv::ID CallConv, bool isVarArg,
3787                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3788                                    SDLoc dl, SelectionDAG &DAG,
3789                                    SmallVectorImpl<SDValue> &InVals) const {
3790
3791   SmallVector<CCValAssign, 16> RVLocs;
3792   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3793                     *DAG.getContext());
3794   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3795
3796   // Copy all of the result registers out of their specified physreg.
3797   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3798     CCValAssign &VA = RVLocs[i];
3799     assert(VA.isRegLoc() && "Can only return in registers!");
3800
3801     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3802                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3803     Chain = Val.getValue(1);
3804     InFlag = Val.getValue(2);
3805
3806     switch (VA.getLocInfo()) {
3807     default: llvm_unreachable("Unknown loc info!");
3808     case CCValAssign::Full: break;
3809     case CCValAssign::AExt:
3810       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3811       break;
3812     case CCValAssign::ZExt:
3813       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3814                         DAG.getValueType(VA.getValVT()));
3815       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3816       break;
3817     case CCValAssign::SExt:
3818       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3819                         DAG.getValueType(VA.getValVT()));
3820       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3821       break;
3822     }
3823
3824     InVals.push_back(Val);
3825   }
3826
3827   return Chain;
3828 }
3829
3830 SDValue
3831 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3832                               bool isTailCall, bool isVarArg,
3833                               SelectionDAG &DAG,
3834                               SmallVector<std::pair<unsigned, SDValue>, 8>
3835                                 &RegsToPass,
3836                               SDValue InFlag, SDValue Chain,
3837                               SDValue &Callee,
3838                               int SPDiff, unsigned NumBytes,
3839                               const SmallVectorImpl<ISD::InputArg> &Ins,
3840                               SmallVectorImpl<SDValue> &InVals) const {
3841
3842   bool isELFv2ABI = Subtarget.isELFv2ABI();
3843   std::vector<EVT> NodeTys;
3844   SmallVector<SDValue, 8> Ops;
3845   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3846                                  isTailCall, RegsToPass, Ops, NodeTys,
3847                                  Subtarget);
3848
3849   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3850   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3851     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3852
3853   // When performing tail call optimization the callee pops its arguments off
3854   // the stack. Account for this here so these bytes can be pushed back on in
3855   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3856   int BytesCalleePops =
3857     (CallConv == CallingConv::Fast &&
3858      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3859
3860   // Add a register mask operand representing the call-preserved registers.
3861   const TargetRegisterInfo *TRI =
3862       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3863   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3864   assert(Mask && "Missing call preserved mask for calling convention");
3865   Ops.push_back(DAG.getRegisterMask(Mask));
3866
3867   if (InFlag.getNode())
3868     Ops.push_back(InFlag);
3869
3870   // Emit tail call.
3871   if (isTailCall) {
3872     assert(((Callee.getOpcode() == ISD::Register &&
3873              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3874             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3875             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3876             isa<ConstantSDNode>(Callee)) &&
3877     "Expecting an global address, external symbol, absolute value or register");
3878
3879     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3880   }
3881
3882   // Add a NOP immediately after the branch instruction when using the 64-bit
3883   // SVR4 ABI. At link time, if caller and callee are in a different module and
3884   // thus have a different TOC, the call will be replaced with a call to a stub
3885   // function which saves the current TOC, loads the TOC of the callee and
3886   // branches to the callee. The NOP will be replaced with a load instruction
3887   // which restores the TOC of the caller from the TOC save slot of the current
3888   // stack frame. If caller and callee belong to the same module (and have the
3889   // same TOC), the NOP will remain unchanged.
3890
3891   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3892     if (CallOpc == PPCISD::BCTRL) {
3893       // This is a call through a function pointer.
3894       // Restore the caller TOC from the save area into R2.
3895       // See PrepareCall() for more information about calls through function
3896       // pointers in the 64-bit SVR4 ABI.
3897       // We are using a target-specific load with r2 hard coded, because the
3898       // result of a target-independent load would never go directly into r2,
3899       // since r2 is a reserved register (which prevents the register allocator
3900       // from allocating it), resulting in an additional register being
3901       // allocated and an unnecessary move instruction being generated.
3902       CallOpc = PPCISD::BCTRL_LOAD_TOC;
3903
3904       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3905       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3906       unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3907       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3908       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3909
3910       // The address needs to go after the chain input but before the flag (or
3911       // any other variadic arguments).
3912       Ops.insert(std::next(Ops.begin()), AddTOC);
3913     } else if ((CallOpc == PPCISD::CALL) &&
3914                (!isLocalCall(Callee) ||
3915                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3916       // Otherwise insert NOP for non-local calls.
3917       CallOpc = PPCISD::CALL_NOP;
3918     } else if (CallOpc == PPCISD::CALL_TLS)
3919       // For 64-bit SVR4, TLS calls are always non-local.
3920       CallOpc = PPCISD::CALL_NOP_TLS;
3921   }
3922
3923   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3924   InFlag = Chain.getValue(1);
3925
3926   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3927                              DAG.getIntPtrConstant(BytesCalleePops, true),
3928                              InFlag, dl);
3929   if (!Ins.empty())
3930     InFlag = Chain.getValue(1);
3931
3932   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3933                          Ins, dl, DAG, InVals);
3934 }
3935
3936 SDValue
3937 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3938                              SmallVectorImpl<SDValue> &InVals) const {
3939   SelectionDAG &DAG                     = CLI.DAG;
3940   SDLoc &dl                             = CLI.DL;
3941   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3942   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3943   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3944   SDValue Chain                         = CLI.Chain;
3945   SDValue Callee                        = CLI.Callee;
3946   bool &isTailCall                      = CLI.IsTailCall;
3947   CallingConv::ID CallConv              = CLI.CallConv;
3948   bool isVarArg                         = CLI.IsVarArg;
3949
3950   if (isTailCall)
3951     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3952                                                    Ins, DAG);
3953
3954   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3955     report_fatal_error("failed to perform tail call elimination on a call "
3956                        "site marked musttail");
3957
3958   if (Subtarget.isSVR4ABI()) {
3959     if (Subtarget.isPPC64())
3960       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3961                               isTailCall, Outs, OutVals, Ins,
3962                               dl, DAG, InVals);
3963     else
3964       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3965                               isTailCall, Outs, OutVals, Ins,
3966                               dl, DAG, InVals);
3967   }
3968
3969   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3970                           isTailCall, Outs, OutVals, Ins,
3971                           dl, DAG, InVals);
3972 }
3973
3974 SDValue
3975 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3976                                     CallingConv::ID CallConv, bool isVarArg,
3977                                     bool isTailCall,
3978                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3979                                     const SmallVectorImpl<SDValue> &OutVals,
3980                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3981                                     SDLoc dl, SelectionDAG &DAG,
3982                                     SmallVectorImpl<SDValue> &InVals) const {
3983   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3984   // of the 32-bit SVR4 ABI stack frame layout.
3985
3986   assert((CallConv == CallingConv::C ||
3987           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3988
3989   unsigned PtrByteSize = 4;
3990
3991   MachineFunction &MF = DAG.getMachineFunction();
3992
3993   // Mark this function as potentially containing a function that contains a
3994   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3995   // and restoring the callers stack pointer in this functions epilog. This is
3996   // done because by tail calling the called function might overwrite the value
3997   // in this function's (MF) stack pointer stack slot 0(SP).
3998   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3999       CallConv == CallingConv::Fast)
4000     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4001
4002   // Count how many bytes are to be pushed on the stack, including the linkage
4003   // area, parameter list area and the part of the local variable space which
4004   // contains copies of aggregates which are passed by value.
4005
4006   // Assign locations to all of the outgoing arguments.
4007   SmallVector<CCValAssign, 16> ArgLocs;
4008   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4009                  *DAG.getContext());
4010
4011   // Reserve space for the linkage area on the stack.
4012   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4013                        PtrByteSize);
4014
4015   if (isVarArg) {
4016     // Handle fixed and variable vector arguments differently.
4017     // Fixed vector arguments go into registers as long as registers are
4018     // available. Variable vector arguments always go into memory.
4019     unsigned NumArgs = Outs.size();
4020
4021     for (unsigned i = 0; i != NumArgs; ++i) {
4022       MVT ArgVT = Outs[i].VT;
4023       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4024       bool Result;
4025
4026       if (Outs[i].IsFixed) {
4027         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4028                                CCInfo);
4029       } else {
4030         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4031                                       ArgFlags, CCInfo);
4032       }
4033
4034       if (Result) {
4035 #ifndef NDEBUG
4036         errs() << "Call operand #" << i << " has unhandled type "
4037              << EVT(ArgVT).getEVTString() << "\n";
4038 #endif
4039         llvm_unreachable(nullptr);
4040       }
4041     }
4042   } else {
4043     // All arguments are treated the same.
4044     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4045   }
4046
4047   // Assign locations to all of the outgoing aggregate by value arguments.
4048   SmallVector<CCValAssign, 16> ByValArgLocs;
4049   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4050                       ByValArgLocs, *DAG.getContext());
4051
4052   // Reserve stack space for the allocations in CCInfo.
4053   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4054
4055   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4056
4057   // Size of the linkage area, parameter list area and the part of the local
4058   // space variable where copies of aggregates which are passed by value are
4059   // stored.
4060   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4061
4062   // Calculate by how many bytes the stack has to be adjusted in case of tail
4063   // call optimization.
4064   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4065
4066   // Adjust the stack pointer for the new arguments...
4067   // These operations are automatically eliminated by the prolog/epilog pass
4068   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4069                                dl);
4070   SDValue CallSeqStart = Chain;
4071
4072   // Load the return address and frame pointer so it can be moved somewhere else
4073   // later.
4074   SDValue LROp, FPOp;
4075   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4076                                        dl);
4077
4078   // Set up a copy of the stack pointer for use loading and storing any
4079   // arguments that may not fit in the registers available for argument
4080   // passing.
4081   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4082
4083   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4084   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4085   SmallVector<SDValue, 8> MemOpChains;
4086
4087   bool seenFloatArg = false;
4088   // Walk the register/memloc assignments, inserting copies/loads.
4089   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4090        i != e;
4091        ++i) {
4092     CCValAssign &VA = ArgLocs[i];
4093     SDValue Arg = OutVals[i];
4094     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4095
4096     if (Flags.isByVal()) {
4097       // Argument is an aggregate which is passed by value, thus we need to
4098       // create a copy of it in the local variable space of the current stack
4099       // frame (which is the stack frame of the caller) and pass the address of
4100       // this copy to the callee.
4101       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4102       CCValAssign &ByValVA = ByValArgLocs[j++];
4103       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4104
4105       // Memory reserved in the local variable space of the callers stack frame.
4106       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4107
4108       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4109       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4110
4111       // Create a copy of the argument in the local area of the current
4112       // stack frame.
4113       SDValue MemcpyCall =
4114         CreateCopyOfByValArgument(Arg, PtrOff,
4115                                   CallSeqStart.getNode()->getOperand(0),
4116                                   Flags, DAG, dl);
4117
4118       // This must go outside the CALLSEQ_START..END.
4119       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4120                            CallSeqStart.getNode()->getOperand(1),
4121                            SDLoc(MemcpyCall));
4122       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4123                              NewCallSeqStart.getNode());
4124       Chain = CallSeqStart = NewCallSeqStart;
4125
4126       // Pass the address of the aggregate copy on the stack either in a
4127       // physical register or in the parameter list area of the current stack
4128       // frame to the callee.
4129       Arg = PtrOff;
4130     }
4131
4132     if (VA.isRegLoc()) {
4133       if (Arg.getValueType() == MVT::i1)
4134         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4135
4136       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4137       // Put argument in a physical register.
4138       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4139     } else {
4140       // Put argument in the parameter list area of the current stack frame.
4141       assert(VA.isMemLoc());
4142       unsigned LocMemOffset = VA.getLocMemOffset();
4143
4144       if (!isTailCall) {
4145         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4146         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4147
4148         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4149                                            MachinePointerInfo(),
4150                                            false, false, 0));
4151       } else {
4152         // Calculate and remember argument location.
4153         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4154                                  TailCallArguments);
4155       }
4156     }
4157   }
4158
4159   if (!MemOpChains.empty())
4160     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4161
4162   // Build a sequence of copy-to-reg nodes chained together with token chain
4163   // and flag operands which copy the outgoing args into the appropriate regs.
4164   SDValue InFlag;
4165   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4166     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4167                              RegsToPass[i].second, InFlag);
4168     InFlag = Chain.getValue(1);
4169   }
4170
4171   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4172   // registers.
4173   if (isVarArg) {
4174     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4175     SDValue Ops[] = { Chain, InFlag };
4176
4177     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4178                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4179
4180     InFlag = Chain.getValue(1);
4181   }
4182
4183   if (isTailCall)
4184     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4185                     false, TailCallArguments);
4186
4187   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4188                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4189                     Ins, InVals);
4190 }
4191
4192 // Copy an argument into memory, being careful to do this outside the
4193 // call sequence for the call to which the argument belongs.
4194 SDValue
4195 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4196                                               SDValue CallSeqStart,
4197                                               ISD::ArgFlagsTy Flags,
4198                                               SelectionDAG &DAG,
4199                                               SDLoc dl) const {
4200   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4201                         CallSeqStart.getNode()->getOperand(0),
4202                         Flags, DAG, dl);
4203   // The MEMCPY must go outside the CALLSEQ_START..END.
4204   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4205                              CallSeqStart.getNode()->getOperand(1),
4206                              SDLoc(MemcpyCall));
4207   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4208                          NewCallSeqStart.getNode());
4209   return NewCallSeqStart;
4210 }
4211
4212 SDValue
4213 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4214                                     CallingConv::ID CallConv, bool isVarArg,
4215                                     bool isTailCall,
4216                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4217                                     const SmallVectorImpl<SDValue> &OutVals,
4218                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4219                                     SDLoc dl, SelectionDAG &DAG,
4220                                     SmallVectorImpl<SDValue> &InVals) const {
4221
4222   bool isELFv2ABI = Subtarget.isELFv2ABI();
4223   bool isLittleEndian = Subtarget.isLittleEndian();
4224   unsigned NumOps = Outs.size();
4225
4226   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4227   unsigned PtrByteSize = 8;
4228
4229   MachineFunction &MF = DAG.getMachineFunction();
4230
4231   // Mark this function as potentially containing a function that contains a
4232   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4233   // and restoring the callers stack pointer in this functions epilog. This is
4234   // done because by tail calling the called function might overwrite the value
4235   // in this function's (MF) stack pointer stack slot 0(SP).
4236   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4237       CallConv == CallingConv::Fast)
4238     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4239
4240   // Count how many bytes are to be pushed on the stack, including the linkage
4241   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4242   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4243   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4244   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4245                                                           isELFv2ABI);
4246   unsigned NumBytes = LinkageSize;
4247
4248   // Add up all the space actually used.
4249   for (unsigned i = 0; i != NumOps; ++i) {
4250     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4251     EVT ArgVT = Outs[i].VT;
4252     EVT OrigVT = Outs[i].ArgVT;
4253
4254     /* Respect alignment of argument on the stack.  */
4255     unsigned Align =
4256       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4257     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4258
4259     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4260     if (Flags.isInConsecutiveRegsLast())
4261       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4262   }
4263
4264   unsigned NumBytesActuallyUsed = NumBytes;
4265
4266   // The prolog code of the callee may store up to 8 GPR argument registers to
4267   // the stack, allowing va_start to index over them in memory if its varargs.
4268   // Because we cannot tell if this is needed on the caller side, we have to
4269   // conservatively assume that it is needed.  As such, make sure we have at
4270   // least enough stack space for the caller to store the 8 GPRs.
4271   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4272   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4273
4274   // Tail call needs the stack to be aligned.
4275   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4276       CallConv == CallingConv::Fast)
4277     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4278
4279   // Calculate by how many bytes the stack has to be adjusted in case of tail
4280   // call optimization.
4281   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4282
4283   // To protect arguments on the stack from being clobbered in a tail call,
4284   // force all the loads to happen before doing any other lowering.
4285   if (isTailCall)
4286     Chain = DAG.getStackArgumentTokenFactor(Chain);
4287
4288   // Adjust the stack pointer for the new arguments...
4289   // These operations are automatically eliminated by the prolog/epilog pass
4290   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4291                                dl);
4292   SDValue CallSeqStart = Chain;
4293
4294   // Load the return address and frame pointer so it can be move somewhere else
4295   // later.
4296   SDValue LROp, FPOp;
4297   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4298                                        dl);
4299
4300   // Set up a copy of the stack pointer for use loading and storing any
4301   // arguments that may not fit in the registers available for argument
4302   // passing.
4303   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4304
4305   // Figure out which arguments are going to go in registers, and which in
4306   // memory.  Also, if this is a vararg function, floating point operations
4307   // must be stored to our stack, and loaded into integer regs as well, if
4308   // any integer regs are available for argument passing.
4309   unsigned ArgOffset = LinkageSize;
4310   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4311
4312   static const MCPhysReg GPR[] = {
4313     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4314     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4315   };
4316   static const MCPhysReg *FPR = GetFPR();
4317
4318   static const MCPhysReg VR[] = {
4319     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4320     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4321   };
4322   static const MCPhysReg VSRH[] = {
4323     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4324     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4325   };
4326
4327   const unsigned NumGPRs = array_lengthof(GPR);
4328   const unsigned NumFPRs = 13;
4329   const unsigned NumVRs  = array_lengthof(VR);
4330
4331   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4332   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4333
4334   SmallVector<SDValue, 8> MemOpChains;
4335   for (unsigned i = 0; i != NumOps; ++i) {
4336     SDValue Arg = OutVals[i];
4337     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4338     EVT ArgVT = Outs[i].VT;
4339     EVT OrigVT = Outs[i].ArgVT;
4340
4341     /* Respect alignment of argument on the stack.  */
4342     unsigned Align =
4343       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4344     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4345
4346     /* Compute GPR index associated with argument offset.  */
4347     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4348     GPR_idx = std::min(GPR_idx, NumGPRs);
4349
4350     // PtrOff will be used to store the current argument to the stack if a
4351     // register cannot be found for it.
4352     SDValue PtrOff;
4353
4354     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4355
4356     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4357
4358     // Promote integers to 64-bit values.
4359     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4360       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4361       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4362       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4363     }
4364
4365     // FIXME memcpy is used way more than necessary.  Correctness first.
4366     // Note: "by value" is code for passing a structure by value, not
4367     // basic types.
4368     if (Flags.isByVal()) {
4369       // Note: Size includes alignment padding, so
4370       //   struct x { short a; char b; }
4371       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4372       // These are the proper values we need for right-justifying the
4373       // aggregate in a parameter register.
4374       unsigned Size = Flags.getByValSize();
4375
4376       // An empty aggregate parameter takes up no storage and no
4377       // registers.
4378       if (Size == 0)
4379         continue;
4380
4381       // All aggregates smaller than 8 bytes must be passed right-justified.
4382       if (Size==1 || Size==2 || Size==4) {
4383         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4384         if (GPR_idx != NumGPRs) {
4385           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4386                                         MachinePointerInfo(), VT,
4387                                         false, false, false, 0);
4388           MemOpChains.push_back(Load.getValue(1));
4389           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4390
4391           ArgOffset += PtrByteSize;
4392           continue;
4393         }
4394       }
4395
4396       if (GPR_idx == NumGPRs && Size < 8) {
4397         SDValue AddPtr = PtrOff;
4398         if (!isLittleEndian) {
4399           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4400                                           PtrOff.getValueType());
4401           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4402         }
4403         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4404                                                           CallSeqStart,
4405                                                           Flags, DAG, dl);
4406         ArgOffset += PtrByteSize;
4407         continue;
4408       }
4409       // Copy entire object into memory.  There are cases where gcc-generated
4410       // code assumes it is there, even if it could be put entirely into
4411       // registers.  (This is not what the doc says.)
4412
4413       // FIXME: The above statement is likely due to a misunderstanding of the
4414       // documents.  All arguments must be copied into the parameter area BY
4415       // THE CALLEE in the event that the callee takes the address of any
4416       // formal argument.  That has not yet been implemented.  However, it is
4417       // reasonable to use the stack area as a staging area for the register
4418       // load.
4419
4420       // Skip this for small aggregates, as we will use the same slot for a
4421       // right-justified copy, below.
4422       if (Size >= 8)
4423         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4424                                                           CallSeqStart,
4425                                                           Flags, DAG, dl);
4426
4427       // When a register is available, pass a small aggregate right-justified.
4428       if (Size < 8 && GPR_idx != NumGPRs) {
4429         // The easiest way to get this right-justified in a register
4430         // is to copy the structure into the rightmost portion of a
4431         // local variable slot, then load the whole slot into the
4432         // register.
4433         // FIXME: The memcpy seems to produce pretty awful code for
4434         // small aggregates, particularly for packed ones.
4435         // FIXME: It would be preferable to use the slot in the
4436         // parameter save area instead of a new local variable.
4437         SDValue AddPtr = PtrOff;
4438         if (!isLittleEndian) {
4439           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4440           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4441         }
4442         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4443                                                           CallSeqStart,
4444                                                           Flags, DAG, dl);
4445
4446         // Load the slot into the register.
4447         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4448                                    MachinePointerInfo(),
4449                                    false, false, false, 0);
4450         MemOpChains.push_back(Load.getValue(1));
4451         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4452
4453         // Done with this argument.
4454         ArgOffset += PtrByteSize;
4455         continue;
4456       }
4457
4458       // For aggregates larger than PtrByteSize, copy the pieces of the
4459       // object that fit into registers from the parameter save area.
4460       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4461         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4462         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4463         if (GPR_idx != NumGPRs) {
4464           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4465                                      MachinePointerInfo(),
4466                                      false, false, false, 0);
4467           MemOpChains.push_back(Load.getValue(1));
4468           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4469           ArgOffset += PtrByteSize;
4470         } else {
4471           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4472           break;
4473         }
4474       }
4475       continue;
4476     }
4477
4478     switch (Arg.getSimpleValueType().SimpleTy) {
4479     default: llvm_unreachable("Unexpected ValueType for argument!");
4480     case MVT::i1:
4481     case MVT::i32:
4482     case MVT::i64:
4483       // These can be scalar arguments or elements of an integer array type
4484       // passed directly.  Clang may use those instead of "byval" aggregate
4485       // types to avoid forcing arguments to memory unnecessarily.
4486       if (GPR_idx != NumGPRs) {
4487         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4488       } else {
4489         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4490                          true, isTailCall, false, MemOpChains,
4491                          TailCallArguments, dl);
4492       }
4493       ArgOffset += PtrByteSize;
4494       break;
4495     case MVT::f32:
4496     case MVT::f64: {
4497       // These can be scalar arguments or elements of a float array type
4498       // passed directly.  The latter are used to implement ELFv2 homogenous
4499       // float aggregates.
4500
4501       // Named arguments go into FPRs first, and once they overflow, the
4502       // remaining arguments go into GPRs and then the parameter save area.
4503       // Unnamed arguments for vararg functions always go to GPRs and
4504       // then the parameter save area.  For now, put all arguments to vararg
4505       // routines always in both locations (FPR *and* GPR or stack slot).
4506       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4507
4508       // First load the argument into the next available FPR.
4509       if (FPR_idx != NumFPRs)
4510         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4511
4512       // Next, load the argument into GPR or stack slot if needed.
4513       if (!NeedGPROrStack)
4514         ;
4515       else if (GPR_idx != NumGPRs) {
4516         // In the non-vararg case, this can only ever happen in the
4517         // presence of f32 array types, since otherwise we never run
4518         // out of FPRs before running out of GPRs.
4519         SDValue ArgVal;
4520
4521         // Double values are always passed in a single GPR.
4522         if (Arg.getValueType() != MVT::f32) {
4523           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4524
4525         // Non-array float values are extended and passed in a GPR.
4526         } else if (!Flags.isInConsecutiveRegs()) {
4527           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4528           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4529
4530         // If we have an array of floats, we collect every odd element
4531         // together with its predecessor into one GPR.
4532         } else if (ArgOffset % PtrByteSize != 0) {
4533           SDValue Lo, Hi;
4534           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4535           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4536           if (!isLittleEndian)
4537             std::swap(Lo, Hi);
4538           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4539
4540         // The final element, if even, goes into the first half of a GPR.
4541         } else if (Flags.isInConsecutiveRegsLast()) {
4542           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4543           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4544           if (!isLittleEndian)
4545             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4546                                  DAG.getConstant(32, MVT::i32));
4547
4548         // Non-final even elements are skipped; they will be handled
4549         // together the with subsequent argument on the next go-around.
4550         } else
4551           ArgVal = SDValue();
4552
4553         if (ArgVal.getNode())
4554           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4555       } else {
4556         // Single-precision floating-point values are mapped to the
4557         // second (rightmost) word of the stack doubleword.
4558         if (Arg.getValueType() == MVT::f32 &&
4559             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4560           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4561           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4562         }
4563
4564         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4565                          true, isTailCall, false, MemOpChains,
4566                          TailCallArguments, dl);
4567       }
4568       // When passing an array of floats, the array occupies consecutive
4569       // space in the argument area; only round up to the next doubleword
4570       // at the end of the array.  Otherwise, each float takes 8 bytes.
4571       ArgOffset += (Arg.getValueType() == MVT::f32 &&
4572                     Flags.isInConsecutiveRegs()) ? 4 : 8;
4573       if (Flags.isInConsecutiveRegsLast())
4574         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4575       break;
4576     }
4577     case MVT::v4f32:
4578     case MVT::v4i32:
4579     case MVT::v8i16:
4580     case MVT::v16i8:
4581     case MVT::v2f64:
4582     case MVT::v2i64:
4583       // These can be scalar arguments or elements of a vector array type
4584       // passed directly.  The latter are used to implement ELFv2 homogenous
4585       // vector aggregates.
4586
4587       // For a varargs call, named arguments go into VRs or on the stack as
4588       // usual; unnamed arguments always go to the stack or the corresponding
4589       // GPRs when within range.  For now, we always put the value in both
4590       // locations (or even all three).
4591       if (isVarArg) {
4592         // We could elide this store in the case where the object fits
4593         // entirely in R registers.  Maybe later.
4594         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4595                                      MachinePointerInfo(), false, false, 0);
4596         MemOpChains.push_back(Store);
4597         if (VR_idx != NumVRs) {
4598           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4599                                      MachinePointerInfo(),
4600                                      false, false, false, 0);
4601           MemOpChains.push_back(Load.getValue(1));
4602
4603           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4604                            Arg.getSimpleValueType() == MVT::v2i64) ?
4605                           VSRH[VR_idx] : VR[VR_idx];
4606           ++VR_idx;
4607
4608           RegsToPass.push_back(std::make_pair(VReg, Load));
4609         }
4610         ArgOffset += 16;
4611         for (unsigned i=0; i<16; i+=PtrByteSize) {
4612           if (GPR_idx == NumGPRs)
4613             break;
4614           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4615                                   DAG.getConstant(i, PtrVT));
4616           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4617                                      false, false, false, 0);
4618           MemOpChains.push_back(Load.getValue(1));
4619           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4620         }
4621         break;
4622       }
4623
4624       // Non-varargs Altivec params go into VRs or on the stack.
4625       if (VR_idx != NumVRs) {
4626         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4627                          Arg.getSimpleValueType() == MVT::v2i64) ?
4628                         VSRH[VR_idx] : VR[VR_idx];
4629         ++VR_idx;
4630
4631         RegsToPass.push_back(std::make_pair(VReg, Arg));
4632       } else {
4633         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4634                          true, isTailCall, true, MemOpChains,
4635                          TailCallArguments, dl);
4636       }
4637       ArgOffset += 16;
4638       break;
4639     }
4640   }
4641
4642   assert(NumBytesActuallyUsed == ArgOffset);
4643   (void)NumBytesActuallyUsed;
4644
4645   if (!MemOpChains.empty())
4646     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4647
4648   // Check if this is an indirect call (MTCTR/BCTRL).
4649   // See PrepareCall() for more information about calls through function
4650   // pointers in the 64-bit SVR4 ABI.
4651   if (!isTailCall &&
4652       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4653       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4654     // Load r2 into a virtual register and store it to the TOC save area.
4655     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4656     // TOC save area offset.
4657     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4658     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4659     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4660     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4661                          false, false, 0);
4662     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4663     // This does not mean the MTCTR instruction must use R12; it's easier
4664     // to model this as an extra parameter, so do that.
4665     if (isELFv2ABI)
4666       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4667   }
4668
4669   // Build a sequence of copy-to-reg nodes chained together with token chain
4670   // and flag operands which copy the outgoing args into the appropriate regs.
4671   SDValue InFlag;
4672   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4673     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4674                              RegsToPass[i].second, InFlag);
4675     InFlag = Chain.getValue(1);
4676   }
4677
4678   if (isTailCall)
4679     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4680                     FPOp, true, TailCallArguments);
4681
4682   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4683                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4684                     Ins, InVals);
4685 }
4686
4687 SDValue
4688 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4689                                     CallingConv::ID CallConv, bool isVarArg,
4690                                     bool isTailCall,
4691                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4692                                     const SmallVectorImpl<SDValue> &OutVals,
4693                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4694                                     SDLoc dl, SelectionDAG &DAG,
4695                                     SmallVectorImpl<SDValue> &InVals) const {
4696
4697   unsigned NumOps = Outs.size();
4698
4699   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4700   bool isPPC64 = PtrVT == MVT::i64;
4701   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4702
4703   MachineFunction &MF = DAG.getMachineFunction();
4704
4705   // Mark this function as potentially containing a function that contains a
4706   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4707   // and restoring the callers stack pointer in this functions epilog. This is
4708   // done because by tail calling the called function might overwrite the value
4709   // in this function's (MF) stack pointer stack slot 0(SP).
4710   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4711       CallConv == CallingConv::Fast)
4712     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4713
4714   // Count how many bytes are to be pushed on the stack, including the linkage
4715   // area, and parameter passing area.  We start with 24/48 bytes, which is
4716   // prereserved space for [SP][CR][LR][3 x unused].
4717   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4718                                                           false);
4719   unsigned NumBytes = LinkageSize;
4720
4721   // Add up all the space actually used.
4722   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4723   // they all go in registers, but we must reserve stack space for them for
4724   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4725   // assigned stack space in order, with padding so Altivec parameters are
4726   // 16-byte aligned.
4727   unsigned nAltivecParamsAtEnd = 0;
4728   for (unsigned i = 0; i != NumOps; ++i) {
4729     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4730     EVT ArgVT = Outs[i].VT;
4731     // Varargs Altivec parameters are padded to a 16 byte boundary.
4732     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4733         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4734         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4735       if (!isVarArg && !isPPC64) {
4736         // Non-varargs Altivec parameters go after all the non-Altivec
4737         // parameters; handle those later so we know how much padding we need.
4738         nAltivecParamsAtEnd++;
4739         continue;
4740       }
4741       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4742       NumBytes = ((NumBytes+15)/16)*16;
4743     }
4744     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4745   }
4746
4747   // Allow for Altivec parameters at the end, if needed.
4748   if (nAltivecParamsAtEnd) {
4749     NumBytes = ((NumBytes+15)/16)*16;
4750     NumBytes += 16*nAltivecParamsAtEnd;
4751   }
4752
4753   // The prolog code of the callee may store up to 8 GPR argument registers to
4754   // the stack, allowing va_start to index over them in memory if its varargs.
4755   // Because we cannot tell if this is needed on the caller side, we have to
4756   // conservatively assume that it is needed.  As such, make sure we have at
4757   // least enough stack space for the caller to store the 8 GPRs.
4758   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4759
4760   // Tail call needs the stack to be aligned.
4761   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4762       CallConv == CallingConv::Fast)
4763     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4764
4765   // Calculate by how many bytes the stack has to be adjusted in case of tail
4766   // call optimization.
4767   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4768
4769   // To protect arguments on the stack from being clobbered in a tail call,
4770   // force all the loads to happen before doing any other lowering.
4771   if (isTailCall)
4772     Chain = DAG.getStackArgumentTokenFactor(Chain);
4773
4774   // Adjust the stack pointer for the new arguments...
4775   // These operations are automatically eliminated by the prolog/epilog pass
4776   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4777                                dl);
4778   SDValue CallSeqStart = Chain;
4779
4780   // Load the return address and frame pointer so it can be move somewhere else
4781   // later.
4782   SDValue LROp, FPOp;
4783   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4784                                        dl);
4785
4786   // Set up a copy of the stack pointer for use loading and storing any
4787   // arguments that may not fit in the registers available for argument
4788   // passing.
4789   SDValue StackPtr;
4790   if (isPPC64)
4791     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4792   else
4793     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4794
4795   // Figure out which arguments are going to go in registers, and which in
4796   // memory.  Also, if this is a vararg function, floating point operations
4797   // must be stored to our stack, and loaded into integer regs as well, if
4798   // any integer regs are available for argument passing.
4799   unsigned ArgOffset = LinkageSize;
4800   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4801
4802   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4803     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4804     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4805   };
4806   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4807     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4808     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4809   };
4810   static const MCPhysReg *FPR = GetFPR();
4811
4812   static const MCPhysReg VR[] = {
4813     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4814     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4815   };
4816   const unsigned NumGPRs = array_lengthof(GPR_32);
4817   const unsigned NumFPRs = 13;
4818   const unsigned NumVRs  = array_lengthof(VR);
4819
4820   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4821
4822   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4823   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4824
4825   SmallVector<SDValue, 8> MemOpChains;
4826   for (unsigned i = 0; i != NumOps; ++i) {
4827     SDValue Arg = OutVals[i];
4828     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4829
4830     // PtrOff will be used to store the current argument to the stack if a
4831     // register cannot be found for it.
4832     SDValue PtrOff;
4833
4834     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4835
4836     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4837
4838     // On PPC64, promote integers to 64-bit values.
4839     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4840       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4841       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4842       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4843     }
4844
4845     // FIXME memcpy is used way more than necessary.  Correctness first.
4846     // Note: "by value" is code for passing a structure by value, not
4847     // basic types.
4848     if (Flags.isByVal()) {
4849       unsigned Size = Flags.getByValSize();
4850       // Very small objects are passed right-justified.  Everything else is
4851       // passed left-justified.
4852       if (Size==1 || Size==2) {
4853         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4854         if (GPR_idx != NumGPRs) {
4855           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4856                                         MachinePointerInfo(), VT,
4857                                         false, false, false, 0);
4858           MemOpChains.push_back(Load.getValue(1));
4859           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4860
4861           ArgOffset += PtrByteSize;
4862         } else {
4863           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4864                                           PtrOff.getValueType());
4865           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4866           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4867                                                             CallSeqStart,
4868                                                             Flags, DAG, dl);
4869           ArgOffset += PtrByteSize;
4870         }
4871         continue;
4872       }
4873       // Copy entire object into memory.  There are cases where gcc-generated
4874       // code assumes it is there, even if it could be put entirely into
4875       // registers.  (This is not what the doc says.)
4876       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4877                                                         CallSeqStart,
4878                                                         Flags, DAG, dl);
4879
4880       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4881       // copy the pieces of the object that fit into registers from the
4882       // parameter save area.
4883       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4884         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4885         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4886         if (GPR_idx != NumGPRs) {
4887           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4888                                      MachinePointerInfo(),
4889                                      false, false, false, 0);
4890           MemOpChains.push_back(Load.getValue(1));
4891           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4892           ArgOffset += PtrByteSize;
4893         } else {
4894           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4895           break;
4896         }
4897       }
4898       continue;
4899     }
4900
4901     switch (Arg.getSimpleValueType().SimpleTy) {
4902     default: llvm_unreachable("Unexpected ValueType for argument!");
4903     case MVT::i1:
4904     case MVT::i32:
4905     case MVT::i64:
4906       if (GPR_idx != NumGPRs) {
4907         if (Arg.getValueType() == MVT::i1)
4908           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4909
4910         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4911       } else {
4912         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4913                          isPPC64, isTailCall, false, MemOpChains,
4914                          TailCallArguments, dl);
4915       }
4916       ArgOffset += PtrByteSize;
4917       break;
4918     case MVT::f32:
4919     case MVT::f64:
4920       if (FPR_idx != NumFPRs) {
4921         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4922
4923         if (isVarArg) {
4924           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4925                                        MachinePointerInfo(), false, false, 0);
4926           MemOpChains.push_back(Store);
4927
4928           // Float varargs are always shadowed in available integer registers
4929           if (GPR_idx != NumGPRs) {
4930             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4931                                        MachinePointerInfo(), false, false,
4932                                        false, 0);
4933             MemOpChains.push_back(Load.getValue(1));
4934             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4935           }
4936           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4937             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4938             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4939             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4940                                        MachinePointerInfo(),
4941                                        false, false, false, 0);
4942             MemOpChains.push_back(Load.getValue(1));
4943             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4944           }
4945         } else {
4946           // If we have any FPRs remaining, we may also have GPRs remaining.
4947           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4948           // GPRs.
4949           if (GPR_idx != NumGPRs)
4950             ++GPR_idx;
4951           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4952               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4953             ++GPR_idx;
4954         }
4955       } else
4956         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4957                          isPPC64, isTailCall, false, MemOpChains,
4958                          TailCallArguments, dl);
4959       if (isPPC64)
4960         ArgOffset += 8;
4961       else
4962         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4963       break;
4964     case MVT::v4f32:
4965     case MVT::v4i32:
4966     case MVT::v8i16:
4967     case MVT::v16i8:
4968       if (isVarArg) {
4969         // These go aligned on the stack, or in the corresponding R registers
4970         // when within range.  The Darwin PPC ABI doc claims they also go in
4971         // V registers; in fact gcc does this only for arguments that are
4972         // prototyped, not for those that match the ...  We do it for all
4973         // arguments, seems to work.
4974         while (ArgOffset % 16 !=0) {
4975           ArgOffset += PtrByteSize;
4976           if (GPR_idx != NumGPRs)
4977             GPR_idx++;
4978         }
4979         // We could elide this store in the case where the object fits
4980         // entirely in R registers.  Maybe later.
4981         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4982                             DAG.getConstant(ArgOffset, PtrVT));
4983         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4984                                      MachinePointerInfo(), false, false, 0);
4985         MemOpChains.push_back(Store);
4986         if (VR_idx != NumVRs) {
4987           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4988                                      MachinePointerInfo(),
4989                                      false, false, false, 0);
4990           MemOpChains.push_back(Load.getValue(1));
4991           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4992         }
4993         ArgOffset += 16;
4994         for (unsigned i=0; i<16; i+=PtrByteSize) {
4995           if (GPR_idx == NumGPRs)
4996             break;
4997           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4998                                   DAG.getConstant(i, PtrVT));
4999           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5000                                      false, false, false, 0);
5001           MemOpChains.push_back(Load.getValue(1));
5002           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5003         }
5004         break;
5005       }
5006
5007       // Non-varargs Altivec params generally go in registers, but have
5008       // stack space allocated at the end.
5009       if (VR_idx != NumVRs) {
5010         // Doesn't have GPR space allocated.
5011         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5012       } else if (nAltivecParamsAtEnd==0) {
5013         // We are emitting Altivec params in order.
5014         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5015                          isPPC64, isTailCall, true, MemOpChains,
5016                          TailCallArguments, dl);
5017         ArgOffset += 16;
5018       }
5019       break;
5020     }
5021   }
5022   // If all Altivec parameters fit in registers, as they usually do,
5023   // they get stack space following the non-Altivec parameters.  We
5024   // don't track this here because nobody below needs it.
5025   // If there are more Altivec parameters than fit in registers emit
5026   // the stores here.
5027   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5028     unsigned j = 0;
5029     // Offset is aligned; skip 1st 12 params which go in V registers.
5030     ArgOffset = ((ArgOffset+15)/16)*16;
5031     ArgOffset += 12*16;
5032     for (unsigned i = 0; i != NumOps; ++i) {
5033       SDValue Arg = OutVals[i];
5034       EVT ArgType = Outs[i].VT;
5035       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5036           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5037         if (++j > NumVRs) {
5038           SDValue PtrOff;
5039           // We are emitting Altivec params in order.
5040           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5041                            isPPC64, isTailCall, true, MemOpChains,
5042                            TailCallArguments, dl);
5043           ArgOffset += 16;
5044         }
5045       }
5046     }
5047   }
5048
5049   if (!MemOpChains.empty())
5050     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5051
5052   // On Darwin, R12 must contain the address of an indirect callee.  This does
5053   // not mean the MTCTR instruction must use R12; it's easier to model this as
5054   // an extra parameter, so do that.
5055   if (!isTailCall &&
5056       !dyn_cast<GlobalAddressSDNode>(Callee) &&
5057       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5058       !isBLACompatibleAddress(Callee, DAG))
5059     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5060                                                    PPC::R12), Callee));
5061
5062   // Build a sequence of copy-to-reg nodes chained together with token chain
5063   // and flag operands which copy the outgoing args into the appropriate regs.
5064   SDValue InFlag;
5065   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5066     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5067                              RegsToPass[i].second, InFlag);
5068     InFlag = Chain.getValue(1);
5069   }
5070
5071   if (isTailCall)
5072     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5073                     FPOp, true, TailCallArguments);
5074
5075   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5076                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5077                     Ins, InVals);
5078 }
5079
5080 bool
5081 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5082                                   MachineFunction &MF, bool isVarArg,
5083                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5084                                   LLVMContext &Context) const {
5085   SmallVector<CCValAssign, 16> RVLocs;
5086   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5087   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5088 }
5089
5090 SDValue
5091 PPCTargetLowering::LowerReturn(SDValue Chain,
5092                                CallingConv::ID CallConv, bool isVarArg,
5093                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5094                                const SmallVectorImpl<SDValue> &OutVals,
5095                                SDLoc dl, SelectionDAG &DAG) const {
5096
5097   SmallVector<CCValAssign, 16> RVLocs;
5098   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5099                  *DAG.getContext());
5100   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5101
5102   SDValue Flag;
5103   SmallVector<SDValue, 4> RetOps(1, Chain);
5104
5105   // Copy the result values into the output registers.
5106   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5107     CCValAssign &VA = RVLocs[i];
5108     assert(VA.isRegLoc() && "Can only return in registers!");
5109
5110     SDValue Arg = OutVals[i];
5111
5112     switch (VA.getLocInfo()) {
5113     default: llvm_unreachable("Unknown loc info!");
5114     case CCValAssign::Full: break;
5115     case CCValAssign::AExt:
5116       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5117       break;
5118     case CCValAssign::ZExt:
5119       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5120       break;
5121     case CCValAssign::SExt:
5122       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5123       break;
5124     }
5125
5126     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5127     Flag = Chain.getValue(1);
5128     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5129   }
5130
5131   RetOps[0] = Chain;  // Update chain.
5132
5133   // Add the flag if we have it.
5134   if (Flag.getNode())
5135     RetOps.push_back(Flag);
5136
5137   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5138 }
5139
5140 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5141                                    const PPCSubtarget &Subtarget) const {
5142   // When we pop the dynamic allocation we need to restore the SP link.
5143   SDLoc dl(Op);
5144
5145   // Get the corect type for pointers.
5146   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5147
5148   // Construct the stack pointer operand.
5149   bool isPPC64 = Subtarget.isPPC64();
5150   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5151   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5152
5153   // Get the operands for the STACKRESTORE.
5154   SDValue Chain = Op.getOperand(0);
5155   SDValue SaveSP = Op.getOperand(1);
5156
5157   // Load the old link SP.
5158   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5159                                    MachinePointerInfo(),
5160                                    false, false, false, 0);
5161
5162   // Restore the stack pointer.
5163   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5164
5165   // Store the old link SP.
5166   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5167                       false, false, 0);
5168 }
5169
5170
5171
5172 SDValue
5173 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5174   MachineFunction &MF = DAG.getMachineFunction();
5175   bool isPPC64 = Subtarget.isPPC64();
5176   bool isDarwinABI = Subtarget.isDarwinABI();
5177   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5178
5179   // Get current frame pointer save index.  The users of this index will be
5180   // primarily DYNALLOC instructions.
5181   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5182   int RASI = FI->getReturnAddrSaveIndex();
5183
5184   // If the frame pointer save index hasn't been defined yet.
5185   if (!RASI) {
5186     // Find out what the fix offset of the frame pointer save area.
5187     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5188     // Allocate the frame index for frame pointer save area.
5189     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5190     // Save the result.
5191     FI->setReturnAddrSaveIndex(RASI);
5192   }
5193   return DAG.getFrameIndex(RASI, PtrVT);
5194 }
5195
5196 SDValue
5197 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5198   MachineFunction &MF = DAG.getMachineFunction();
5199   bool isPPC64 = Subtarget.isPPC64();
5200   bool isDarwinABI = Subtarget.isDarwinABI();
5201   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5202
5203   // Get current frame pointer save index.  The users of this index will be
5204   // primarily DYNALLOC instructions.
5205   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5206   int FPSI = FI->getFramePointerSaveIndex();
5207
5208   // If the frame pointer save index hasn't been defined yet.
5209   if (!FPSI) {
5210     // Find out what the fix offset of the frame pointer save area.
5211     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5212                                                            isDarwinABI);
5213
5214     // Allocate the frame index for frame pointer save area.
5215     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5216     // Save the result.
5217     FI->setFramePointerSaveIndex(FPSI);
5218   }
5219   return DAG.getFrameIndex(FPSI, PtrVT);
5220 }
5221
5222 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5223                                          SelectionDAG &DAG,
5224                                          const PPCSubtarget &Subtarget) const {
5225   // Get the inputs.
5226   SDValue Chain = Op.getOperand(0);
5227   SDValue Size  = Op.getOperand(1);
5228   SDLoc dl(Op);
5229
5230   // Get the corect type for pointers.
5231   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5232   // Negate the size.
5233   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5234                                   DAG.getConstant(0, PtrVT), Size);
5235   // Construct a node for the frame pointer save index.
5236   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5237   // Build a DYNALLOC node.
5238   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5239   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5240   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5241 }
5242
5243 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5244                                                SelectionDAG &DAG) const {
5245   SDLoc DL(Op);
5246   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5247                      DAG.getVTList(MVT::i32, MVT::Other),
5248                      Op.getOperand(0), Op.getOperand(1));
5249 }
5250
5251 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5252                                                 SelectionDAG &DAG) const {
5253   SDLoc DL(Op);
5254   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5255                      Op.getOperand(0), Op.getOperand(1));
5256 }
5257
5258 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5259   assert(Op.getValueType() == MVT::i1 &&
5260          "Custom lowering only for i1 loads");
5261
5262   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5263
5264   SDLoc dl(Op);
5265   LoadSDNode *LD = cast<LoadSDNode>(Op);
5266
5267   SDValue Chain = LD->getChain();
5268   SDValue BasePtr = LD->getBasePtr();
5269   MachineMemOperand *MMO = LD->getMemOperand();
5270
5271   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5272                                  BasePtr, MVT::i8, MMO);
5273   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5274
5275   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5276   return DAG.getMergeValues(Ops, dl);
5277 }
5278
5279 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5280   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5281          "Custom lowering only for i1 stores");
5282
5283   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5284
5285   SDLoc dl(Op);
5286   StoreSDNode *ST = cast<StoreSDNode>(Op);
5287
5288   SDValue Chain = ST->getChain();
5289   SDValue BasePtr = ST->getBasePtr();
5290   SDValue Value = ST->getValue();
5291   MachineMemOperand *MMO = ST->getMemOperand();
5292
5293   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5294   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5295 }
5296
5297 // FIXME: Remove this once the ANDI glue bug is fixed:
5298 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5299   assert(Op.getValueType() == MVT::i1 &&
5300          "Custom lowering only for i1 results");
5301
5302   SDLoc DL(Op);
5303   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5304                      Op.getOperand(0));
5305 }
5306
5307 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5308 /// possible.
5309 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5310   // Not FP? Not a fsel.
5311   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5312       !Op.getOperand(2).getValueType().isFloatingPoint())
5313     return Op;
5314
5315   // We might be able to do better than this under some circumstances, but in
5316   // general, fsel-based lowering of select is a finite-math-only optimization.
5317   // For more information, see section F.3 of the 2.06 ISA specification.
5318   if (!DAG.getTarget().Options.NoInfsFPMath ||
5319       !DAG.getTarget().Options.NoNaNsFPMath)
5320     return Op;
5321
5322   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5323
5324   EVT ResVT = Op.getValueType();
5325   EVT CmpVT = Op.getOperand(0).getValueType();
5326   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5327   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5328   SDLoc dl(Op);
5329
5330   // If the RHS of the comparison is a 0.0, we don't need to do the
5331   // subtraction at all.
5332   SDValue Sel1;
5333   if (isFloatingPointZero(RHS))
5334     switch (CC) {
5335     default: break;       // SETUO etc aren't handled by fsel.
5336     case ISD::SETNE:
5337       std::swap(TV, FV);
5338     case ISD::SETEQ:
5339       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5340         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5341       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5342       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5343         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5344       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5345                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5346     case ISD::SETULT:
5347     case ISD::SETLT:
5348       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5349     case ISD::SETOGE:
5350     case ISD::SETGE:
5351       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5352         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5353       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5354     case ISD::SETUGT:
5355     case ISD::SETGT:
5356       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5357     case ISD::SETOLE:
5358     case ISD::SETLE:
5359       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5360         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5361       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5362                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5363     }
5364
5365   SDValue Cmp;
5366   switch (CC) {
5367   default: break;       // SETUO etc aren't handled by fsel.
5368   case ISD::SETNE:
5369     std::swap(TV, FV);
5370   case ISD::SETEQ:
5371     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5372     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5373       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5374     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5375     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5376       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5377     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5378                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5379   case ISD::SETULT:
5380   case ISD::SETLT:
5381     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5382     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5383       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5384     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5385   case ISD::SETOGE:
5386   case ISD::SETGE:
5387     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5388     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5389       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5390     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5391   case ISD::SETUGT:
5392   case ISD::SETGT:
5393     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5394     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5395       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5396     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5397   case ISD::SETOLE:
5398   case ISD::SETLE:
5399     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5400     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5401       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5402     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5403   }
5404   return Op;
5405 }
5406
5407 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5408                                                SelectionDAG &DAG,
5409                                                SDLoc dl) const {
5410   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5411   SDValue Src = Op.getOperand(0);
5412   if (Src.getValueType() == MVT::f32)
5413     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5414
5415   SDValue Tmp;
5416   switch (Op.getSimpleValueType().SimpleTy) {
5417   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5418   case MVT::i32:
5419     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5420                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5421                                                    PPCISD::FCTIDZ),
5422                       dl, MVT::f64, Src);
5423     break;
5424   case MVT::i64:
5425     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5426            "i64 FP_TO_UINT is supported only with FPCVT");
5427     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5428                                                         PPCISD::FCTIDUZ,
5429                       dl, MVT::f64, Src);
5430     break;
5431   }
5432
5433   // Convert the FP value to an int value through memory.
5434   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5435     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5436   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5437   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5438   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5439
5440   // Emit a store to the stack slot.
5441   SDValue Chain;
5442   if (i32Stack) {
5443     MachineFunction &MF = DAG.getMachineFunction();
5444     MachineMemOperand *MMO =
5445       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5446     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5447     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5448               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5449   } else
5450     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5451                          MPI, false, false, 0);
5452
5453   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5454   // add in a bias.
5455   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5456     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5457                         DAG.getConstant(4, FIPtr.getValueType()));
5458     MPI = MPI.getWithOffset(4);
5459   }
5460
5461   RLI.Chain = Chain;
5462   RLI.Ptr = FIPtr;
5463   RLI.MPI = MPI;
5464 }
5465
5466 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5467                                           SDLoc dl) const {
5468   ReuseLoadInfo RLI;
5469   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5470
5471   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5472                      false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5473                      RLI.Ranges);
5474 }
5475
5476 // We're trying to insert a regular store, S, and then a load, L. If the
5477 // incoming value, O, is a load, we might just be able to have our load use the
5478 // address used by O. However, we don't know if anything else will store to
5479 // that address before we can load from it. To prevent this situation, we need
5480 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5481 // the same chain operand as O, we create a token factor from the chain results
5482 // of O and L, and we replace all uses of O's chain result with that token
5483 // factor (see spliceIntoChain below for this last part).
5484 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5485                                             ReuseLoadInfo &RLI,
5486                                             SelectionDAG &DAG,
5487                                             ISD::LoadExtType ET) const {
5488   SDLoc dl(Op);
5489   if (ET == ISD::NON_EXTLOAD &&
5490       (Op.getOpcode() == ISD::FP_TO_UINT ||
5491        Op.getOpcode() == ISD::FP_TO_SINT) &&
5492       isOperationLegalOrCustom(Op.getOpcode(),
5493                                Op.getOperand(0).getValueType())) {
5494
5495     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5496     return true;
5497   }
5498
5499   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5500   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5501       LD->isNonTemporal())
5502     return false;
5503   if (LD->getMemoryVT() != MemVT)
5504     return false;
5505
5506   RLI.Ptr = LD->getBasePtr();
5507   if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5508     assert(LD->getAddressingMode() == ISD::PRE_INC &&
5509            "Non-pre-inc AM on PPC?");
5510     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5511                           LD->getOffset());
5512   }
5513
5514   RLI.Chain = LD->getChain();
5515   RLI.MPI = LD->getPointerInfo();
5516   RLI.IsInvariant = LD->isInvariant();
5517   RLI.Alignment = LD->getAlignment();
5518   RLI.AAInfo = LD->getAAInfo();
5519   RLI.Ranges = LD->getRanges();
5520
5521   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5522   return true;
5523 }
5524
5525 // Given the head of the old chain, ResChain, insert a token factor containing
5526 // it and NewResChain, and make users of ResChain now be users of that token
5527 // factor.
5528 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5529                                         SDValue NewResChain,
5530                                         SelectionDAG &DAG) const {
5531   if (!ResChain)
5532     return;
5533
5534   SDLoc dl(NewResChain);
5535
5536   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5537                            NewResChain, DAG.getUNDEF(MVT::Other));
5538   assert(TF.getNode() != NewResChain.getNode() &&
5539          "A new TF really is required here");
5540
5541   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5542   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5543 }
5544
5545 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5546                                           SelectionDAG &DAG) const {
5547   SDLoc dl(Op);
5548   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5549   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5550     return SDValue();
5551
5552   if (Op.getOperand(0).getValueType() == MVT::i1)
5553     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5554                        DAG.getConstantFP(1.0, Op.getValueType()),
5555                        DAG.getConstantFP(0.0, Op.getValueType()));
5556
5557   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5558          "UINT_TO_FP is supported only with FPCVT");
5559
5560   // If we have FCFIDS, then use it when converting to single-precision.
5561   // Otherwise, convert to double-precision and then round.
5562   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5563                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5564                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5565                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5566                     PPCISD::FCFIDU : PPCISD::FCFID);
5567   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5568                    MVT::f32 : MVT::f64;
5569
5570   if (Op.getOperand(0).getValueType() == MVT::i64) {
5571     SDValue SINT = Op.getOperand(0);
5572     // When converting to single-precision, we actually need to convert
5573     // to double-precision first and then round to single-precision.
5574     // To avoid double-rounding effects during that operation, we have
5575     // to prepare the input operand.  Bits that might be truncated when
5576     // converting to double-precision are replaced by a bit that won't
5577     // be lost at this stage, but is below the single-precision rounding
5578     // position.
5579     //
5580     // However, if -enable-unsafe-fp-math is in effect, accept double
5581     // rounding to avoid the extra overhead.
5582     if (Op.getValueType() == MVT::f32 &&
5583         !Subtarget.hasFPCVT() &&
5584         !DAG.getTarget().Options.UnsafeFPMath) {
5585
5586       // Twiddle input to make sure the low 11 bits are zero.  (If this
5587       // is the case, we are guaranteed the value will fit into the 53 bit
5588       // mantissa of an IEEE double-precision value without rounding.)
5589       // If any of those low 11 bits were not zero originally, make sure
5590       // bit 12 (value 2048) is set instead, so that the final rounding
5591       // to single-precision gets the correct result.
5592       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5593                                   SINT, DAG.getConstant(2047, MVT::i64));
5594       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5595                           Round, DAG.getConstant(2047, MVT::i64));
5596       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5597       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5598                           Round, DAG.getConstant(-2048, MVT::i64));
5599
5600       // However, we cannot use that value unconditionally: if the magnitude
5601       // of the input value is small, the bit-twiddling we did above might
5602       // end up visibly changing the output.  Fortunately, in that case, we
5603       // don't need to twiddle bits since the original input will convert
5604       // exactly to double-precision floating-point already.  Therefore,
5605       // construct a conditional to use the original value if the top 11
5606       // bits are all sign-bit copies, and use the rounded value computed
5607       // above otherwise.
5608       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5609                                  SINT, DAG.getConstant(53, MVT::i32));
5610       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5611                          Cond, DAG.getConstant(1, MVT::i64));
5612       Cond = DAG.getSetCC(dl, MVT::i32,
5613                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5614
5615       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5616     }
5617
5618     ReuseLoadInfo RLI;
5619     SDValue Bits;
5620
5621     MachineFunction &MF = DAG.getMachineFunction();
5622     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5623       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5624                          false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5625                          RLI.Ranges);
5626       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5627     } else if (Subtarget.hasLFIWAX() &&
5628                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
5629       MachineMemOperand *MMO =
5630         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5631                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5632       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5633       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
5634                                      DAG.getVTList(MVT::f64, MVT::Other),
5635                                      Ops, MVT::i32, MMO);
5636       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5637     } else if (Subtarget.hasFPCVT() &&
5638                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
5639       MachineMemOperand *MMO =
5640         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5641                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5642       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5643       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
5644                                      DAG.getVTList(MVT::f64, MVT::Other),
5645                                      Ops, MVT::i32, MMO);
5646       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5647     } else if (((Subtarget.hasLFIWAX() &&
5648                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
5649                 (Subtarget.hasFPCVT() &&
5650                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
5651                SINT.getOperand(0).getValueType() == MVT::i32) {
5652       MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5653       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5654
5655       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5656       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5657
5658       SDValue Store =
5659         DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
5660                      MachinePointerInfo::getFixedStack(FrameIdx),
5661                      false, false, 0);
5662
5663       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5664              "Expected an i32 store");
5665
5666       RLI.Ptr = FIdx;
5667       RLI.Chain = Store;
5668       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5669       RLI.Alignment = 4;
5670
5671       MachineMemOperand *MMO =
5672         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5673                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5674       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5675       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
5676                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
5677                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
5678                                      Ops, MVT::i32, MMO);
5679     } else
5680       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5681
5682     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5683
5684     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5685       FP = DAG.getNode(ISD::FP_ROUND, dl,
5686                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5687     return FP;
5688   }
5689
5690   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5691          "Unhandled INT_TO_FP type in custom expander!");
5692   // Since we only generate this in 64-bit mode, we can take advantage of
5693   // 64-bit registers.  In particular, sign extend the input value into the
5694   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5695   // then lfd it and fcfid it.
5696   MachineFunction &MF = DAG.getMachineFunction();
5697   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5698   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5699
5700   SDValue Ld;
5701   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5702     ReuseLoadInfo RLI;
5703     bool ReusingLoad;
5704     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5705                                             DAG))) {
5706       int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5707       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5708
5709       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5710                                    MachinePointerInfo::getFixedStack(FrameIdx),
5711                                    false, false, 0);
5712
5713       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5714              "Expected an i32 store");
5715
5716       RLI.Ptr = FIdx;
5717       RLI.Chain = Store;
5718       RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5719       RLI.Alignment = 4;
5720     }
5721
5722     MachineMemOperand *MMO =
5723       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5724                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5725     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5726     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5727                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5728                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5729                                  Ops, MVT::i32, MMO);
5730     if (ReusingLoad)
5731       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5732   } else {
5733     assert(Subtarget.isPPC64() &&
5734            "i32->FP without LFIWAX supported only on PPC64");
5735
5736     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5737     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5738
5739     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5740                                 Op.getOperand(0));
5741
5742     // STD the extended value into the stack slot.
5743     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5744                                  MachinePointerInfo::getFixedStack(FrameIdx),
5745                                  false, false, 0);
5746
5747     // Load the value as a double.
5748     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5749                      MachinePointerInfo::getFixedStack(FrameIdx),
5750                      false, false, false, 0);
5751   }
5752
5753   // FCFID it and return it.
5754   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5755   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5756     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5757   return FP;
5758 }
5759
5760 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5761                                             SelectionDAG &DAG) const {
5762   SDLoc dl(Op);
5763   /*
5764    The rounding mode is in bits 30:31 of FPSR, and has the following
5765    settings:
5766      00 Round to nearest
5767      01 Round to 0
5768      10 Round to +inf
5769      11 Round to -inf
5770
5771   FLT_ROUNDS, on the other hand, expects the following:
5772     -1 Undefined
5773      0 Round to 0
5774      1 Round to nearest
5775      2 Round to +inf
5776      3 Round to -inf
5777
5778   To perform the conversion, we do:
5779     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5780   */
5781
5782   MachineFunction &MF = DAG.getMachineFunction();
5783   EVT VT = Op.getValueType();
5784   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5785
5786   // Save FP Control Word to register
5787   EVT NodeTys[] = {
5788     MVT::f64,    // return register
5789     MVT::Glue    // unused in this context
5790   };
5791   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5792
5793   // Save FP register to stack slot
5794   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5795   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5796   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5797                                StackSlot, MachinePointerInfo(), false, false,0);
5798
5799   // Load FP Control Word from low 32 bits of stack slot.
5800   SDValue Four = DAG.getConstant(4, PtrVT);
5801   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5802   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5803                             false, false, false, 0);
5804
5805   // Transform as necessary
5806   SDValue CWD1 =
5807     DAG.getNode(ISD::AND, dl, MVT::i32,
5808                 CWD, DAG.getConstant(3, MVT::i32));
5809   SDValue CWD2 =
5810     DAG.getNode(ISD::SRL, dl, MVT::i32,
5811                 DAG.getNode(ISD::AND, dl, MVT::i32,
5812                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5813                                         CWD, DAG.getConstant(3, MVT::i32)),
5814                             DAG.getConstant(3, MVT::i32)),
5815                 DAG.getConstant(1, MVT::i32));
5816
5817   SDValue RetVal =
5818     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5819
5820   return DAG.getNode((VT.getSizeInBits() < 16 ?
5821                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5822 }
5823
5824 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5825   EVT VT = Op.getValueType();
5826   unsigned BitWidth = VT.getSizeInBits();
5827   SDLoc dl(Op);
5828   assert(Op.getNumOperands() == 3 &&
5829          VT == Op.getOperand(1).getValueType() &&
5830          "Unexpected SHL!");
5831
5832   // Expand into a bunch of logical ops.  Note that these ops
5833   // depend on the PPC behavior for oversized shift amounts.
5834   SDValue Lo = Op.getOperand(0);
5835   SDValue Hi = Op.getOperand(1);
5836   SDValue Amt = Op.getOperand(2);
5837   EVT AmtVT = Amt.getValueType();
5838
5839   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5840                              DAG.getConstant(BitWidth, AmtVT), Amt);
5841   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5842   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5843   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5844   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5845                              DAG.getConstant(-BitWidth, AmtVT));
5846   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5847   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5848   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5849   SDValue OutOps[] = { OutLo, OutHi };
5850   return DAG.getMergeValues(OutOps, dl);
5851 }
5852
5853 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5854   EVT VT = Op.getValueType();
5855   SDLoc dl(Op);
5856   unsigned BitWidth = VT.getSizeInBits();
5857   assert(Op.getNumOperands() == 3 &&
5858          VT == Op.getOperand(1).getValueType() &&
5859          "Unexpected SRL!");
5860
5861   // Expand into a bunch of logical ops.  Note that these ops
5862   // depend on the PPC behavior for oversized shift amounts.
5863   SDValue Lo = Op.getOperand(0);
5864   SDValue Hi = Op.getOperand(1);
5865   SDValue Amt = Op.getOperand(2);
5866   EVT AmtVT = Amt.getValueType();
5867
5868   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5869                              DAG.getConstant(BitWidth, AmtVT), Amt);
5870   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5871   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5872   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5873   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5874                              DAG.getConstant(-BitWidth, AmtVT));
5875   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5876   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5877   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5878   SDValue OutOps[] = { OutLo, OutHi };
5879   return DAG.getMergeValues(OutOps, dl);
5880 }
5881
5882 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5883   SDLoc dl(Op);
5884   EVT VT = Op.getValueType();
5885   unsigned BitWidth = VT.getSizeInBits();
5886   assert(Op.getNumOperands() == 3 &&
5887          VT == Op.getOperand(1).getValueType() &&
5888          "Unexpected SRA!");
5889
5890   // Expand into a bunch of logical ops, followed by a select_cc.
5891   SDValue Lo = Op.getOperand(0);
5892   SDValue Hi = Op.getOperand(1);
5893   SDValue Amt = Op.getOperand(2);
5894   EVT AmtVT = Amt.getValueType();
5895
5896   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5897                              DAG.getConstant(BitWidth, AmtVT), Amt);
5898   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5899   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5900   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5901   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5902                              DAG.getConstant(-BitWidth, AmtVT));
5903   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5904   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5905   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5906                                   Tmp4, Tmp6, ISD::SETLE);
5907   SDValue OutOps[] = { OutLo, OutHi };
5908   return DAG.getMergeValues(OutOps, dl);
5909 }
5910
5911 //===----------------------------------------------------------------------===//
5912 // Vector related lowering.
5913 //
5914
5915 /// BuildSplatI - Build a canonical splati of Val with an element size of
5916 /// SplatSize.  Cast the result to VT.
5917 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5918                              SelectionDAG &DAG, SDLoc dl) {
5919   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5920
5921   static const EVT VTys[] = { // canonical VT to use for each size.
5922     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5923   };
5924
5925   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5926
5927   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5928   if (Val == -1)
5929     SplatSize = 1;
5930
5931   EVT CanonicalVT = VTys[SplatSize-1];
5932
5933   // Build a canonical splat for this value.
5934   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5935   SmallVector<SDValue, 8> Ops;
5936   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5937   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5938   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5939 }
5940
5941 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5942 /// specified intrinsic ID.
5943 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5944                                 SelectionDAG &DAG, SDLoc dl,
5945                                 EVT DestVT = MVT::Other) {
5946   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5947   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5948                      DAG.getConstant(IID, MVT::i32), Op);
5949 }
5950
5951 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5952 /// specified intrinsic ID.
5953 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5954                                 SelectionDAG &DAG, SDLoc dl,
5955                                 EVT DestVT = MVT::Other) {
5956   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5957   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5958                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5959 }
5960
5961 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5962 /// specified intrinsic ID.
5963 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5964                                 SDValue Op2, SelectionDAG &DAG,
5965                                 SDLoc dl, EVT DestVT = MVT::Other) {
5966   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5967   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5968                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5969 }
5970
5971
5972 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5973 /// amount.  The result has the specified value type.
5974 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5975                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5976   // Force LHS/RHS to be the right type.
5977   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5978   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5979
5980   int Ops[16];
5981   for (unsigned i = 0; i != 16; ++i)
5982     Ops[i] = i + Amt;
5983   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5984   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5985 }
5986
5987 // If this is a case we can't handle, return null and let the default
5988 // expansion code take care of it.  If we CAN select this case, and if it
5989 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5990 // this case more efficiently than a constant pool load, lower it to the
5991 // sequence of ops that should be used.
5992 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5993                                              SelectionDAG &DAG) const {
5994   SDLoc dl(Op);
5995   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5996   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5997
5998   // Check if this is a splat of a constant value.
5999   APInt APSplatBits, APSplatUndef;
6000   unsigned SplatBitSize;
6001   bool HasAnyUndefs;
6002   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6003                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
6004     return SDValue();
6005
6006   unsigned SplatBits = APSplatBits.getZExtValue();
6007   unsigned SplatUndef = APSplatUndef.getZExtValue();
6008   unsigned SplatSize = SplatBitSize / 8;
6009
6010   // First, handle single instruction cases.
6011
6012   // All zeros?
6013   if (SplatBits == 0) {
6014     // Canonicalize all zero vectors to be v4i32.
6015     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6016       SDValue Z = DAG.getConstant(0, MVT::i32);
6017       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6018       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6019     }
6020     return Op;
6021   }
6022
6023   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6024   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6025                     (32-SplatBitSize));
6026   if (SextVal >= -16 && SextVal <= 15)
6027     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6028
6029
6030   // Two instruction sequences.
6031
6032   // If this value is in the range [-32,30] and is even, use:
6033   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6034   // If this value is in the range [17,31] and is odd, use:
6035   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6036   // If this value is in the range [-31,-17] and is odd, use:
6037   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6038   // Note the last two are three-instruction sequences.
6039   if (SextVal >= -32 && SextVal <= 31) {
6040     // To avoid having these optimizations undone by constant folding,
6041     // we convert to a pseudo that will be expanded later into one of
6042     // the above forms.
6043     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6044     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6045               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6046     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6047     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6048     if (VT == Op.getValueType())
6049       return RetVal;
6050     else
6051       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6052   }
6053
6054   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
6055   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
6056   // for fneg/fabs.
6057   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6058     // Make -1 and vspltisw -1:
6059     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6060
6061     // Make the VSLW intrinsic, computing 0x8000_0000.
6062     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6063                                    OnesV, DAG, dl);
6064
6065     // xor by OnesV to invert it.
6066     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6067     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6068   }
6069
6070   // The remaining cases assume either big endian element order or
6071   // a splat-size that equates to the element size of the vector
6072   // to be built.  An example that doesn't work for little endian is
6073   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6074   // and a vector element size of 16 bits.  The code below will
6075   // produce the vector in big endian element order, which for little
6076   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6077
6078   // For now, just avoid these optimizations in that case.
6079   // FIXME: Develop correct optimizations for LE with mismatched
6080   // splat and element sizes.
6081
6082   if (Subtarget.isLittleEndian() &&
6083       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6084     return SDValue();
6085
6086   // Check to see if this is a wide variety of vsplti*, binop self cases.
6087   static const signed char SplatCsts[] = {
6088     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6089     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6090   };
6091
6092   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6093     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6094     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
6095     int i = SplatCsts[idx];
6096
6097     // Figure out what shift amount will be used by altivec if shifted by i in
6098     // this splat size.
6099     unsigned TypeShiftAmt = i & (SplatBitSize-1);
6100
6101     // vsplti + shl self.
6102     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6103       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6104       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6105         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6106         Intrinsic::ppc_altivec_vslw
6107       };
6108       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6109       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6110     }
6111
6112     // vsplti + srl self.
6113     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6114       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6115       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6116         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6117         Intrinsic::ppc_altivec_vsrw
6118       };
6119       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6120       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6121     }
6122
6123     // vsplti + sra self.
6124     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6125       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6126       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6127         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6128         Intrinsic::ppc_altivec_vsraw
6129       };
6130       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6131       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6132     }
6133
6134     // vsplti + rol self.
6135     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6136                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6137       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6138       static const unsigned IIDs[] = { // Intrinsic to use for each size.
6139         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6140         Intrinsic::ppc_altivec_vrlw
6141       };
6142       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6143       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6144     }
6145
6146     // t = vsplti c, result = vsldoi t, t, 1
6147     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6148       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6149       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6150     }
6151     // t = vsplti c, result = vsldoi t, t, 2
6152     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6153       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6154       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6155     }
6156     // t = vsplti c, result = vsldoi t, t, 3
6157     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6158       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6159       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6160     }
6161   }
6162
6163   return SDValue();
6164 }
6165
6166 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6167 /// the specified operations to build the shuffle.
6168 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6169                                       SDValue RHS, SelectionDAG &DAG,
6170                                       SDLoc dl) {
6171   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6172   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6173   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6174
6175   enum {
6176     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6177     OP_VMRGHW,
6178     OP_VMRGLW,
6179     OP_VSPLTISW0,
6180     OP_VSPLTISW1,
6181     OP_VSPLTISW2,
6182     OP_VSPLTISW3,
6183     OP_VSLDOI4,
6184     OP_VSLDOI8,
6185     OP_VSLDOI12
6186   };
6187
6188   if (OpNum == OP_COPY) {
6189     if (LHSID == (1*9+2)*9+3) return LHS;
6190     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6191     return RHS;
6192   }
6193
6194   SDValue OpLHS, OpRHS;
6195   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6196   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6197
6198   int ShufIdxs[16];
6199   switch (OpNum) {
6200   default: llvm_unreachable("Unknown i32 permute!");
6201   case OP_VMRGHW:
6202     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6203     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6204     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6205     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6206     break;
6207   case OP_VMRGLW:
6208     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6209     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6210     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6211     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6212     break;
6213   case OP_VSPLTISW0:
6214     for (unsigned i = 0; i != 16; ++i)
6215       ShufIdxs[i] = (i&3)+0;
6216     break;
6217   case OP_VSPLTISW1:
6218     for (unsigned i = 0; i != 16; ++i)
6219       ShufIdxs[i] = (i&3)+4;
6220     break;
6221   case OP_VSPLTISW2:
6222     for (unsigned i = 0; i != 16; ++i)
6223       ShufIdxs[i] = (i&3)+8;
6224     break;
6225   case OP_VSPLTISW3:
6226     for (unsigned i = 0; i != 16; ++i)
6227       ShufIdxs[i] = (i&3)+12;
6228     break;
6229   case OP_VSLDOI4:
6230     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6231   case OP_VSLDOI8:
6232     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6233   case OP_VSLDOI12:
6234     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6235   }
6236   EVT VT = OpLHS.getValueType();
6237   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6238   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6239   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6240   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6241 }
6242
6243 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6244 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6245 /// return the code it can be lowered into.  Worst case, it can always be
6246 /// lowered into a vperm.
6247 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6248                                                SelectionDAG &DAG) const {
6249   SDLoc dl(Op);
6250   SDValue V1 = Op.getOperand(0);
6251   SDValue V2 = Op.getOperand(1);
6252   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6253   EVT VT = Op.getValueType();
6254   bool isLittleEndian = Subtarget.isLittleEndian();
6255
6256   // Cases that are handled by instructions that take permute immediates
6257   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6258   // selected by the instruction selector.
6259   if (V2.getOpcode() == ISD::UNDEF) {
6260     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6261         PPC::isSplatShuffleMask(SVOp, 2) ||
6262         PPC::isSplatShuffleMask(SVOp, 4) ||
6263         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6264         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6265         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6266         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6267         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6268         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6269         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6270         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6271         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6272       return Op;
6273     }
6274   }
6275
6276   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6277   // and produce a fixed permutation.  If any of these match, do not lower to
6278   // VPERM.
6279   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6280   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6281       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6282       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6283       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6284       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6285       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6286       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6287       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6288       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6289     return Op;
6290
6291   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6292   // perfect shuffle table to emit an optimal matching sequence.
6293   ArrayRef<int> PermMask = SVOp->getMask();
6294
6295   unsigned PFIndexes[4];
6296   bool isFourElementShuffle = true;
6297   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6298     unsigned EltNo = 8;   // Start out undef.
6299     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6300       if (PermMask[i*4+j] < 0)
6301         continue;   // Undef, ignore it.
6302
6303       unsigned ByteSource = PermMask[i*4+j];
6304       if ((ByteSource & 3) != j) {
6305         isFourElementShuffle = false;
6306         break;
6307       }
6308
6309       if (EltNo == 8) {
6310         EltNo = ByteSource/4;
6311       } else if (EltNo != ByteSource/4) {
6312         isFourElementShuffle = false;
6313         break;
6314       }
6315     }
6316     PFIndexes[i] = EltNo;
6317   }
6318
6319   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6320   // perfect shuffle vector to determine if it is cost effective to do this as
6321   // discrete instructions, or whether we should use a vperm.
6322   // For now, we skip this for little endian until such time as we have a
6323   // little-endian perfect shuffle table.
6324   if (isFourElementShuffle && !isLittleEndian) {
6325     // Compute the index in the perfect shuffle table.
6326     unsigned PFTableIndex =
6327       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6328
6329     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6330     unsigned Cost  = (PFEntry >> 30);
6331
6332     // Determining when to avoid vperm is tricky.  Many things affect the cost
6333     // of vperm, particularly how many times the perm mask needs to be computed.
6334     // For example, if the perm mask can be hoisted out of a loop or is already
6335     // used (perhaps because there are multiple permutes with the same shuffle
6336     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6337     // the loop requires an extra register.
6338     //
6339     // As a compromise, we only emit discrete instructions if the shuffle can be
6340     // generated in 3 or fewer operations.  When we have loop information
6341     // available, if this block is within a loop, we should avoid using vperm
6342     // for 3-operation perms and use a constant pool load instead.
6343     if (Cost < 3)
6344       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6345   }
6346
6347   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6348   // vector that will get spilled to the constant pool.
6349   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6350
6351   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6352   // that it is in input element units, not in bytes.  Convert now.
6353
6354   // For little endian, the order of the input vectors is reversed, and
6355   // the permutation mask is complemented with respect to 31.  This is
6356   // necessary to produce proper semantics with the big-endian-biased vperm
6357   // instruction.
6358   EVT EltVT = V1.getValueType().getVectorElementType();
6359   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6360
6361   SmallVector<SDValue, 16> ResultMask;
6362   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6363     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6364
6365     for (unsigned j = 0; j != BytesPerElement; ++j)
6366       if (isLittleEndian)
6367         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6368                                              MVT::i32));
6369       else
6370         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6371                                              MVT::i32));
6372   }
6373
6374   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6375                                   ResultMask);
6376   if (isLittleEndian)
6377     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6378                        V2, V1, VPermMask);
6379   else
6380     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6381                        V1, V2, VPermMask);
6382 }
6383
6384 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6385 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6386 /// information about the intrinsic.
6387 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6388                                   bool &isDot) {
6389   unsigned IntrinsicID =
6390     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6391   CompareOpc = -1;
6392   isDot = false;
6393   switch (IntrinsicID) {
6394   default: return false;
6395     // Comparison predicates.
6396   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6397   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6398   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6399   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6400   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6401   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6402   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6403   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6404   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6405   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6406   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6407   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6408   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6409
6410     // Normal Comparisons.
6411   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6412   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6413   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6414   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6415   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6416   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6417   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6418   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6419   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6420   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6421   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6422   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6423   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6424   }
6425   return true;
6426 }
6427
6428 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6429 /// lower, do it, otherwise return null.
6430 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6431                                                    SelectionDAG &DAG) const {
6432   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6433   // opcode number of the comparison.
6434   SDLoc dl(Op);
6435   int CompareOpc;
6436   bool isDot;
6437   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6438     return SDValue();    // Don't custom lower most intrinsics.
6439
6440   // If this is a non-dot comparison, make the VCMP node and we are done.
6441   if (!isDot) {
6442     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6443                               Op.getOperand(1), Op.getOperand(2),
6444                               DAG.getConstant(CompareOpc, MVT::i32));
6445     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6446   }
6447
6448   // Create the PPCISD altivec 'dot' comparison node.
6449   SDValue Ops[] = {
6450     Op.getOperand(2),  // LHS
6451     Op.getOperand(3),  // RHS
6452     DAG.getConstant(CompareOpc, MVT::i32)
6453   };
6454   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6455   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6456
6457   // Now that we have the comparison, emit a copy from the CR to a GPR.
6458   // This is flagged to the above dot comparison.
6459   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6460                                 DAG.getRegister(PPC::CR6, MVT::i32),
6461                                 CompNode.getValue(1));
6462
6463   // Unpack the result based on how the target uses it.
6464   unsigned BitNo;   // Bit # of CR6.
6465   bool InvertBit;   // Invert result?
6466   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6467   default:  // Can't happen, don't crash on invalid number though.
6468   case 0:   // Return the value of the EQ bit of CR6.
6469     BitNo = 0; InvertBit = false;
6470     break;
6471   case 1:   // Return the inverted value of the EQ bit of CR6.
6472     BitNo = 0; InvertBit = true;
6473     break;
6474   case 2:   // Return the value of the LT bit of CR6.
6475     BitNo = 2; InvertBit = false;
6476     break;
6477   case 3:   // Return the inverted value of the LT bit of CR6.
6478     BitNo = 2; InvertBit = true;
6479     break;
6480   }
6481
6482   // Shift the bit into the low position.
6483   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6484                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6485   // Isolate the bit.
6486   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6487                       DAG.getConstant(1, MVT::i32));
6488
6489   // If we are supposed to, toggle the bit.
6490   if (InvertBit)
6491     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6492                         DAG.getConstant(1, MVT::i32));
6493   return Flags;
6494 }
6495
6496 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6497                                                   SelectionDAG &DAG) const {
6498   SDLoc dl(Op);
6499   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6500   // instructions), but for smaller types, we need to first extend up to v2i32
6501   // before doing going farther.
6502   if (Op.getValueType() == MVT::v2i64) {
6503     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6504     if (ExtVT != MVT::v2i32) {
6505       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6506       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6507                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6508                                         ExtVT.getVectorElementType(), 4)));
6509       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6510       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6511                        DAG.getValueType(MVT::v2i32));
6512     }
6513
6514     return Op;
6515   }
6516
6517   return SDValue();
6518 }
6519
6520 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6521                                                    SelectionDAG &DAG) const {
6522   SDLoc dl(Op);
6523   // Create a stack slot that is 16-byte aligned.
6524   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6525   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6526   EVT PtrVT = getPointerTy();
6527   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6528
6529   // Store the input value into Value#0 of the stack slot.
6530   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6531                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6532                                false, false, 0);
6533   // Load it out.
6534   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6535                      false, false, false, 0);
6536 }
6537
6538 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6539   SDLoc dl(Op);
6540   if (Op.getValueType() == MVT::v4i32) {
6541     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6542
6543     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6544     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6545
6546     SDValue RHSSwap =   // = vrlw RHS, 16
6547       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6548
6549     // Shrinkify inputs to v8i16.
6550     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6551     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6552     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6553
6554     // Low parts multiplied together, generating 32-bit results (we ignore the
6555     // top parts).
6556     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6557                                         LHS, RHS, DAG, dl, MVT::v4i32);
6558
6559     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6560                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6561     // Shift the high parts up 16 bits.
6562     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6563                               Neg16, DAG, dl);
6564     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6565   } else if (Op.getValueType() == MVT::v8i16) {
6566     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6567
6568     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6569
6570     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6571                             LHS, RHS, Zero, DAG, dl);
6572   } else if (Op.getValueType() == MVT::v16i8) {
6573     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6574     bool isLittleEndian = Subtarget.isLittleEndian();
6575
6576     // Multiply the even 8-bit parts, producing 16-bit sums.
6577     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6578                                            LHS, RHS, DAG, dl, MVT::v8i16);
6579     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6580
6581     // Multiply the odd 8-bit parts, producing 16-bit sums.
6582     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6583                                           LHS, RHS, DAG, dl, MVT::v8i16);
6584     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6585
6586     // Merge the results together.  Because vmuleub and vmuloub are
6587     // instructions with a big-endian bias, we must reverse the
6588     // element numbering and reverse the meaning of "odd" and "even"
6589     // when generating little endian code.
6590     int Ops[16];
6591     for (unsigned i = 0; i != 8; ++i) {
6592       if (isLittleEndian) {
6593         Ops[i*2  ] = 2*i;
6594         Ops[i*2+1] = 2*i+16;
6595       } else {
6596         Ops[i*2  ] = 2*i+1;
6597         Ops[i*2+1] = 2*i+1+16;
6598       }
6599     }
6600     if (isLittleEndian)
6601       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6602     else
6603       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6604   } else {
6605     llvm_unreachable("Unknown mul to lower!");
6606   }
6607 }
6608
6609 /// LowerOperation - Provide custom lowering hooks for some operations.
6610 ///
6611 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6612   switch (Op.getOpcode()) {
6613   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6614   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6615   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6616   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6617   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6618   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6619   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6620   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6621   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6622   case ISD::VASTART:
6623     return LowerVASTART(Op, DAG, Subtarget);
6624
6625   case ISD::VAARG:
6626     return LowerVAARG(Op, DAG, Subtarget);
6627
6628   case ISD::VACOPY:
6629     return LowerVACOPY(Op, DAG, Subtarget);
6630
6631   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6632   case ISD::DYNAMIC_STACKALLOC:
6633     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6634
6635   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6636   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6637
6638   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6639   case ISD::STORE:              return LowerSTORE(Op, DAG);
6640   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6641   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6642   case ISD::FP_TO_UINT:
6643   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6644                                                       SDLoc(Op));
6645   case ISD::UINT_TO_FP:
6646   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6647   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6648
6649   // Lower 64-bit shifts.
6650   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6651   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6652   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6653
6654   // Vector-related lowering.
6655   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6656   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6657   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6658   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6659   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6660   case ISD::MUL:                return LowerMUL(Op, DAG);
6661
6662   // For counter-based loop handling.
6663   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6664
6665   // Frame & Return address.
6666   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6667   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6668   }
6669 }
6670
6671 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6672                                            SmallVectorImpl<SDValue>&Results,
6673                                            SelectionDAG &DAG) const {
6674   const TargetMachine &TM = getTargetMachine();
6675   SDLoc dl(N);
6676   switch (N->getOpcode()) {
6677   default:
6678     llvm_unreachable("Do not know how to custom type legalize this operation!");
6679   case ISD::READCYCLECOUNTER: {
6680     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6681     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6682
6683     Results.push_back(RTB);
6684     Results.push_back(RTB.getValue(1));
6685     Results.push_back(RTB.getValue(2));
6686     break;
6687   }
6688   case ISD::INTRINSIC_W_CHAIN: {
6689     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6690         Intrinsic::ppc_is_decremented_ctr_nonzero)
6691       break;
6692
6693     assert(N->getValueType(0) == MVT::i1 &&
6694            "Unexpected result type for CTR decrement intrinsic");
6695     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6696     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6697     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6698                                  N->getOperand(1)); 
6699
6700     Results.push_back(NewInt);
6701     Results.push_back(NewInt.getValue(1));
6702     break;
6703   }
6704   case ISD::VAARG: {
6705     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6706         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6707       return;
6708
6709     EVT VT = N->getValueType(0);
6710
6711     if (VT == MVT::i64) {
6712       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6713
6714       Results.push_back(NewNode);
6715       Results.push_back(NewNode.getValue(1));
6716     }
6717     return;
6718   }
6719   case ISD::FP_ROUND_INREG: {
6720     assert(N->getValueType(0) == MVT::ppcf128);
6721     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6722     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6723                              MVT::f64, N->getOperand(0),
6724                              DAG.getIntPtrConstant(0));
6725     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6726                              MVT::f64, N->getOperand(0),
6727                              DAG.getIntPtrConstant(1));
6728
6729     // Add the two halves of the long double in round-to-zero mode.
6730     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6731
6732     // We know the low half is about to be thrown away, so just use something
6733     // convenient.
6734     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6735                                 FPreg, FPreg));
6736     return;
6737   }
6738   case ISD::FP_TO_SINT:
6739     // LowerFP_TO_INT() can only handle f32 and f64.
6740     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6741       return;
6742     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6743     return;
6744   }
6745 }
6746
6747
6748 //===----------------------------------------------------------------------===//
6749 //  Other Lowering Code
6750 //===----------------------------------------------------------------------===//
6751
6752 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6753   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6754   Function *Func = Intrinsic::getDeclaration(M, Id);
6755   return Builder.CreateCall(Func);
6756 }
6757
6758 // The mappings for emitLeading/TrailingFence is taken from
6759 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6760 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6761                                          AtomicOrdering Ord, bool IsStore,
6762                                          bool IsLoad) const {
6763   if (Ord == SequentiallyConsistent)
6764     return callIntrinsic(Builder, Intrinsic::ppc_sync);
6765   else if (isAtLeastRelease(Ord))
6766     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6767   else
6768     return nullptr;
6769 }
6770
6771 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6772                                           AtomicOrdering Ord, bool IsStore,
6773                                           bool IsLoad) const {
6774   if (IsLoad && isAtLeastAcquire(Ord))
6775     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6776   // FIXME: this is too conservative, a dependent branch + isync is enough.
6777   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6778   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6779   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6780   else
6781     return nullptr;
6782 }
6783
6784 MachineBasicBlock *
6785 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6786                                     bool is64bit, unsigned BinOpcode) const {
6787   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6788   const TargetInstrInfo *TII =
6789       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6790
6791   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6792   MachineFunction *F = BB->getParent();
6793   MachineFunction::iterator It = BB;
6794   ++It;
6795
6796   unsigned dest = MI->getOperand(0).getReg();
6797   unsigned ptrA = MI->getOperand(1).getReg();
6798   unsigned ptrB = MI->getOperand(2).getReg();
6799   unsigned incr = MI->getOperand(3).getReg();
6800   DebugLoc dl = MI->getDebugLoc();
6801
6802   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6803   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6804   F->insert(It, loopMBB);
6805   F->insert(It, exitMBB);
6806   exitMBB->splice(exitMBB->begin(), BB,
6807                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6808   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6809
6810   MachineRegisterInfo &RegInfo = F->getRegInfo();
6811   unsigned TmpReg = (!BinOpcode) ? incr :
6812     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6813                                            : &PPC::GPRCRegClass);
6814
6815   //  thisMBB:
6816   //   ...
6817   //   fallthrough --> loopMBB
6818   BB->addSuccessor(loopMBB);
6819
6820   //  loopMBB:
6821   //   l[wd]arx dest, ptr
6822   //   add r0, dest, incr
6823   //   st[wd]cx. r0, ptr
6824   //   bne- loopMBB
6825   //   fallthrough --> exitMBB
6826   BB = loopMBB;
6827   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6828     .addReg(ptrA).addReg(ptrB);
6829   if (BinOpcode)
6830     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6831   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6832     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6833   BuildMI(BB, dl, TII->get(PPC::BCC))
6834     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6835   BB->addSuccessor(loopMBB);
6836   BB->addSuccessor(exitMBB);
6837
6838   //  exitMBB:
6839   //   ...
6840   BB = exitMBB;
6841   return BB;
6842 }
6843
6844 MachineBasicBlock *
6845 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6846                                             MachineBasicBlock *BB,
6847                                             bool is8bit,    // operation
6848                                             unsigned BinOpcode) const {
6849   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6850   const TargetInstrInfo *TII =
6851       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6852   // In 64 bit mode we have to use 64 bits for addresses, even though the
6853   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6854   // registers without caring whether they're 32 or 64, but here we're
6855   // doing actual arithmetic on the addresses.
6856   bool is64bit = Subtarget.isPPC64();
6857   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6858
6859   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6860   MachineFunction *F = BB->getParent();
6861   MachineFunction::iterator It = BB;
6862   ++It;
6863
6864   unsigned dest = MI->getOperand(0).getReg();
6865   unsigned ptrA = MI->getOperand(1).getReg();
6866   unsigned ptrB = MI->getOperand(2).getReg();
6867   unsigned incr = MI->getOperand(3).getReg();
6868   DebugLoc dl = MI->getDebugLoc();
6869
6870   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6871   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6872   F->insert(It, loopMBB);
6873   F->insert(It, exitMBB);
6874   exitMBB->splice(exitMBB->begin(), BB,
6875                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6876   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6877
6878   MachineRegisterInfo &RegInfo = F->getRegInfo();
6879   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
6880                                           : &PPC::GPRCRegClass;
6881   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6882   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6883   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6884   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6885   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6886   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6887   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6888   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6889   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6890   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6891   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6892   unsigned Ptr1Reg;
6893   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6894
6895   //  thisMBB:
6896   //   ...
6897   //   fallthrough --> loopMBB
6898   BB->addSuccessor(loopMBB);
6899
6900   // The 4-byte load must be aligned, while a char or short may be
6901   // anywhere in the word.  Hence all this nasty bookkeeping code.
6902   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6903   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6904   //   xori shift, shift1, 24 [16]
6905   //   rlwinm ptr, ptr1, 0, 0, 29
6906   //   slw incr2, incr, shift
6907   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6908   //   slw mask, mask2, shift
6909   //  loopMBB:
6910   //   lwarx tmpDest, ptr
6911   //   add tmp, tmpDest, incr2
6912   //   andc tmp2, tmpDest, mask
6913   //   and tmp3, tmp, mask
6914   //   or tmp4, tmp3, tmp2
6915   //   stwcx. tmp4, ptr
6916   //   bne- loopMBB
6917   //   fallthrough --> exitMBB
6918   //   srw dest, tmpDest, shift
6919   if (ptrA != ZeroReg) {
6920     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6921     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6922       .addReg(ptrA).addReg(ptrB);
6923   } else {
6924     Ptr1Reg = ptrB;
6925   }
6926   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6927       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6928   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6929       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6930   if (is64bit)
6931     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6932       .addReg(Ptr1Reg).addImm(0).addImm(61);
6933   else
6934     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6935       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6936   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6937       .addReg(incr).addReg(ShiftReg);
6938   if (is8bit)
6939     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6940   else {
6941     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6942     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6943   }
6944   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6945       .addReg(Mask2Reg).addReg(ShiftReg);
6946
6947   BB = loopMBB;
6948   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6949     .addReg(ZeroReg).addReg(PtrReg);
6950   if (BinOpcode)
6951     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6952       .addReg(Incr2Reg).addReg(TmpDestReg);
6953   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6954     .addReg(TmpDestReg).addReg(MaskReg);
6955   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6956     .addReg(TmpReg).addReg(MaskReg);
6957   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6958     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6959   BuildMI(BB, dl, TII->get(PPC::STWCX))
6960     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6961   BuildMI(BB, dl, TII->get(PPC::BCC))
6962     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6963   BB->addSuccessor(loopMBB);
6964   BB->addSuccessor(exitMBB);
6965
6966   //  exitMBB:
6967   //   ...
6968   BB = exitMBB;
6969   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6970     .addReg(ShiftReg);
6971   return BB;
6972 }
6973
6974 llvm::MachineBasicBlock*
6975 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6976                                     MachineBasicBlock *MBB) const {
6977   DebugLoc DL = MI->getDebugLoc();
6978   const TargetInstrInfo *TII =
6979       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6980
6981   MachineFunction *MF = MBB->getParent();
6982   MachineRegisterInfo &MRI = MF->getRegInfo();
6983
6984   const BasicBlock *BB = MBB->getBasicBlock();
6985   MachineFunction::iterator I = MBB;
6986   ++I;
6987
6988   // Memory Reference
6989   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6990   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6991
6992   unsigned DstReg = MI->getOperand(0).getReg();
6993   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6994   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6995   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6996   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6997
6998   MVT PVT = getPointerTy();
6999   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7000          "Invalid Pointer Size!");
7001   // For v = setjmp(buf), we generate
7002   //
7003   // thisMBB:
7004   //  SjLjSetup mainMBB
7005   //  bl mainMBB
7006   //  v_restore = 1
7007   //  b sinkMBB
7008   //
7009   // mainMBB:
7010   //  buf[LabelOffset] = LR
7011   //  v_main = 0
7012   //
7013   // sinkMBB:
7014   //  v = phi(main, restore)
7015   //
7016
7017   MachineBasicBlock *thisMBB = MBB;
7018   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7019   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7020   MF->insert(I, mainMBB);
7021   MF->insert(I, sinkMBB);
7022
7023   MachineInstrBuilder MIB;
7024
7025   // Transfer the remainder of BB and its successor edges to sinkMBB.
7026   sinkMBB->splice(sinkMBB->begin(), MBB,
7027                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7028   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7029
7030   // Note that the structure of the jmp_buf used here is not compatible
7031   // with that used by libc, and is not designed to be. Specifically, it
7032   // stores only those 'reserved' registers that LLVM does not otherwise
7033   // understand how to spill. Also, by convention, by the time this
7034   // intrinsic is called, Clang has already stored the frame address in the
7035   // first slot of the buffer and stack address in the third. Following the
7036   // X86 target code, we'll store the jump address in the second slot. We also
7037   // need to save the TOC pointer (R2) to handle jumps between shared
7038   // libraries, and that will be stored in the fourth slot. The thread
7039   // identifier (R13) is not affected.
7040
7041   // thisMBB:
7042   const int64_t LabelOffset = 1 * PVT.getStoreSize();
7043   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
7044   const int64_t BPOffset    = 4 * PVT.getStoreSize();
7045
7046   // Prepare IP either in reg.
7047   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7048   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7049   unsigned BufReg = MI->getOperand(1).getReg();
7050
7051   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7052     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7053             .addReg(PPC::X2)
7054             .addImm(TOCOffset)
7055             .addReg(BufReg);
7056     MIB.setMemRefs(MMOBegin, MMOEnd);
7057   }
7058
7059   // Naked functions never have a base pointer, and so we use r1. For all
7060   // other functions, this decision must be delayed until during PEI.
7061   unsigned BaseReg;
7062   if (MF->getFunction()->getAttributes().hasAttribute(
7063           AttributeSet::FunctionIndex, Attribute::Naked))
7064     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7065   else
7066     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7067
7068   MIB = BuildMI(*thisMBB, MI, DL,
7069                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7070           .addReg(BaseReg)
7071           .addImm(BPOffset)
7072           .addReg(BufReg);
7073   MIB.setMemRefs(MMOBegin, MMOEnd);
7074
7075   // Setup
7076   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7077   const PPCRegisterInfo *TRI =
7078       getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
7079   MIB.addRegMask(TRI->getNoPreservedMask());
7080
7081   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7082
7083   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7084           .addMBB(mainMBB);
7085   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7086
7087   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7088   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7089
7090   // mainMBB:
7091   //  mainDstReg = 0
7092   MIB = BuildMI(mainMBB, DL,
7093     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7094
7095   // Store IP
7096   if (Subtarget.isPPC64()) {
7097     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7098             .addReg(LabelReg)
7099             .addImm(LabelOffset)
7100             .addReg(BufReg);
7101   } else {
7102     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7103             .addReg(LabelReg)
7104             .addImm(LabelOffset)
7105             .addReg(BufReg);
7106   }
7107
7108   MIB.setMemRefs(MMOBegin, MMOEnd);
7109
7110   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7111   mainMBB->addSuccessor(sinkMBB);
7112
7113   // sinkMBB:
7114   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7115           TII->get(PPC::PHI), DstReg)
7116     .addReg(mainDstReg).addMBB(mainMBB)
7117     .addReg(restoreDstReg).addMBB(thisMBB);
7118
7119   MI->eraseFromParent();
7120   return sinkMBB;
7121 }
7122
7123 MachineBasicBlock *
7124 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7125                                      MachineBasicBlock *MBB) const {
7126   DebugLoc DL = MI->getDebugLoc();
7127   const TargetInstrInfo *TII =
7128       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7129
7130   MachineFunction *MF = MBB->getParent();
7131   MachineRegisterInfo &MRI = MF->getRegInfo();
7132
7133   // Memory Reference
7134   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7135   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7136
7137   MVT PVT = getPointerTy();
7138   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7139          "Invalid Pointer Size!");
7140
7141   const TargetRegisterClass *RC =
7142     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7143   unsigned Tmp = MRI.createVirtualRegister(RC);
7144   // Since FP is only updated here but NOT referenced, it's treated as GPR.
7145   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7146   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7147   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
7148                   (Subtarget.isSVR4ABI() &&
7149                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
7150                      PPC::R29 : PPC::R30);
7151
7152   MachineInstrBuilder MIB;
7153
7154   const int64_t LabelOffset = 1 * PVT.getStoreSize();
7155   const int64_t SPOffset    = 2 * PVT.getStoreSize();
7156   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
7157   const int64_t BPOffset    = 4 * PVT.getStoreSize();
7158
7159   unsigned BufReg = MI->getOperand(0).getReg();
7160
7161   // Reload FP (the jumped-to function may not have had a
7162   // frame pointer, and if so, then its r31 will be restored
7163   // as necessary).
7164   if (PVT == MVT::i64) {
7165     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7166             .addImm(0)
7167             .addReg(BufReg);
7168   } else {
7169     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7170             .addImm(0)
7171             .addReg(BufReg);
7172   }
7173   MIB.setMemRefs(MMOBegin, MMOEnd);
7174
7175   // Reload IP
7176   if (PVT == MVT::i64) {
7177     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7178             .addImm(LabelOffset)
7179             .addReg(BufReg);
7180   } else {
7181     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7182             .addImm(LabelOffset)
7183             .addReg(BufReg);
7184   }
7185   MIB.setMemRefs(MMOBegin, MMOEnd);
7186
7187   // Reload SP
7188   if (PVT == MVT::i64) {
7189     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7190             .addImm(SPOffset)
7191             .addReg(BufReg);
7192   } else {
7193     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7194             .addImm(SPOffset)
7195             .addReg(BufReg);
7196   }
7197   MIB.setMemRefs(MMOBegin, MMOEnd);
7198
7199   // Reload BP
7200   if (PVT == MVT::i64) {
7201     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7202             .addImm(BPOffset)
7203             .addReg(BufReg);
7204   } else {
7205     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7206             .addImm(BPOffset)
7207             .addReg(BufReg);
7208   }
7209   MIB.setMemRefs(MMOBegin, MMOEnd);
7210
7211   // Reload TOC
7212   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7213     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7214             .addImm(TOCOffset)
7215             .addReg(BufReg);
7216
7217     MIB.setMemRefs(MMOBegin, MMOEnd);
7218   }
7219
7220   // Jump
7221   BuildMI(*MBB, MI, DL,
7222           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7223   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7224
7225   MI->eraseFromParent();
7226   return MBB;
7227 }
7228
7229 MachineBasicBlock *
7230 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7231                                                MachineBasicBlock *BB) const {
7232   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7233       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7234     return emitEHSjLjSetJmp(MI, BB);
7235   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7236              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7237     return emitEHSjLjLongJmp(MI, BB);
7238   }
7239
7240   const TargetInstrInfo *TII =
7241       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7242
7243   // To "insert" these instructions we actually have to insert their
7244   // control-flow patterns.
7245   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7246   MachineFunction::iterator It = BB;
7247   ++It;
7248
7249   MachineFunction *F = BB->getParent();
7250
7251   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7252                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
7253                                  MI->getOpcode() == PPC::SELECT_I4 ||
7254                                  MI->getOpcode() == PPC::SELECT_I8)) {
7255     SmallVector<MachineOperand, 2> Cond;
7256     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7257         MI->getOpcode() == PPC::SELECT_CC_I8)
7258       Cond.push_back(MI->getOperand(4));
7259     else
7260       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7261     Cond.push_back(MI->getOperand(1));
7262
7263     DebugLoc dl = MI->getDebugLoc();
7264     const TargetInstrInfo *TII =
7265         getTargetMachine().getSubtargetImpl()->getInstrInfo();
7266     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7267                       Cond, MI->getOperand(2).getReg(),
7268                       MI->getOperand(3).getReg());
7269   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7270              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7271              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7272              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7273              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7274              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7275              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7276              MI->getOpcode() == PPC::SELECT_I4 ||
7277              MI->getOpcode() == PPC::SELECT_I8 ||
7278              MI->getOpcode() == PPC::SELECT_F4 ||
7279              MI->getOpcode() == PPC::SELECT_F8 ||
7280              MI->getOpcode() == PPC::SELECT_VRRC ||
7281              MI->getOpcode() == PPC::SELECT_VSFRC ||
7282              MI->getOpcode() == PPC::SELECT_VSRC) {
7283     // The incoming instruction knows the destination vreg to set, the
7284     // condition code register to branch on, the true/false values to
7285     // select between, and a branch opcode to use.
7286
7287     //  thisMBB:
7288     //  ...
7289     //   TrueVal = ...
7290     //   cmpTY ccX, r1, r2
7291     //   bCC copy1MBB
7292     //   fallthrough --> copy0MBB
7293     MachineBasicBlock *thisMBB = BB;
7294     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7295     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7296     DebugLoc dl = MI->getDebugLoc();
7297     F->insert(It, copy0MBB);
7298     F->insert(It, sinkMBB);
7299
7300     // Transfer the remainder of BB and its successor edges to sinkMBB.
7301     sinkMBB->splice(sinkMBB->begin(), BB,
7302                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7303     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7304
7305     // Next, add the true and fallthrough blocks as its successors.
7306     BB->addSuccessor(copy0MBB);
7307     BB->addSuccessor(sinkMBB);
7308
7309     if (MI->getOpcode() == PPC::SELECT_I4 ||
7310         MI->getOpcode() == PPC::SELECT_I8 ||
7311         MI->getOpcode() == PPC::SELECT_F4 ||
7312         MI->getOpcode() == PPC::SELECT_F8 ||
7313         MI->getOpcode() == PPC::SELECT_VRRC ||
7314         MI->getOpcode() == PPC::SELECT_VSFRC ||
7315         MI->getOpcode() == PPC::SELECT_VSRC) {
7316       BuildMI(BB, dl, TII->get(PPC::BC))
7317         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7318     } else {
7319       unsigned SelectPred = MI->getOperand(4).getImm();
7320       BuildMI(BB, dl, TII->get(PPC::BCC))
7321         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7322     }
7323
7324     //  copy0MBB:
7325     //   %FalseValue = ...
7326     //   # fallthrough to sinkMBB
7327     BB = copy0MBB;
7328
7329     // Update machine-CFG edges
7330     BB->addSuccessor(sinkMBB);
7331
7332     //  sinkMBB:
7333     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7334     //  ...
7335     BB = sinkMBB;
7336     BuildMI(*BB, BB->begin(), dl,
7337             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7338       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7339       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7340   } else if (MI->getOpcode() == PPC::ReadTB) {
7341     // To read the 64-bit time-base register on a 32-bit target, we read the
7342     // two halves. Should the counter have wrapped while it was being read, we
7343     // need to try again.
7344     // ...
7345     // readLoop:
7346     // mfspr Rx,TBU # load from TBU
7347     // mfspr Ry,TB  # load from TB
7348     // mfspr Rz,TBU # load from TBU
7349     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
7350     // bne readLoop   # branch if they're not equal
7351     // ...
7352
7353     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7354     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7355     DebugLoc dl = MI->getDebugLoc();
7356     F->insert(It, readMBB);
7357     F->insert(It, sinkMBB);
7358
7359     // Transfer the remainder of BB and its successor edges to sinkMBB.
7360     sinkMBB->splice(sinkMBB->begin(), BB,
7361                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7362     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7363
7364     BB->addSuccessor(readMBB);
7365     BB = readMBB;
7366
7367     MachineRegisterInfo &RegInfo = F->getRegInfo();
7368     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7369     unsigned LoReg = MI->getOperand(0).getReg();
7370     unsigned HiReg = MI->getOperand(1).getReg();
7371
7372     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7373     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7374     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7375
7376     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7377
7378     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7379       .addReg(HiReg).addReg(ReadAgainReg);
7380     BuildMI(BB, dl, TII->get(PPC::BCC))
7381       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7382
7383     BB->addSuccessor(readMBB);
7384     BB->addSuccessor(sinkMBB);
7385   }
7386   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7387     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7388   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7389     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7390   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7391     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7392   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7393     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7394
7395   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7396     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7397   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7398     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7399   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7400     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7401   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7402     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7403
7404   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7405     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7406   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7407     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7408   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7409     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7410   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7411     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7412
7413   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7414     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7415   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7416     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7417   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7418     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7419   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7420     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7421
7422   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7423     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7424   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7425     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7426   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7427     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7428   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7429     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7430
7431   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7432     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7433   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7434     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7435   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7436     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7437   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7438     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7439
7440   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7441     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7442   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7443     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7444   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7445     BB = EmitAtomicBinary(MI, BB, false, 0);
7446   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7447     BB = EmitAtomicBinary(MI, BB, true, 0);
7448
7449   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7450            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7451     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7452
7453     unsigned dest   = MI->getOperand(0).getReg();
7454     unsigned ptrA   = MI->getOperand(1).getReg();
7455     unsigned ptrB   = MI->getOperand(2).getReg();
7456     unsigned oldval = MI->getOperand(3).getReg();
7457     unsigned newval = MI->getOperand(4).getReg();
7458     DebugLoc dl     = MI->getDebugLoc();
7459
7460     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7461     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7462     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7463     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7464     F->insert(It, loop1MBB);
7465     F->insert(It, loop2MBB);
7466     F->insert(It, midMBB);
7467     F->insert(It, exitMBB);
7468     exitMBB->splice(exitMBB->begin(), BB,
7469                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7470     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7471
7472     //  thisMBB:
7473     //   ...
7474     //   fallthrough --> loopMBB
7475     BB->addSuccessor(loop1MBB);
7476
7477     // loop1MBB:
7478     //   l[wd]arx dest, ptr
7479     //   cmp[wd] dest, oldval
7480     //   bne- midMBB
7481     // loop2MBB:
7482     //   st[wd]cx. newval, ptr
7483     //   bne- loopMBB
7484     //   b exitBB
7485     // midMBB:
7486     //   st[wd]cx. dest, ptr
7487     // exitBB:
7488     BB = loop1MBB;
7489     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7490       .addReg(ptrA).addReg(ptrB);
7491     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7492       .addReg(oldval).addReg(dest);
7493     BuildMI(BB, dl, TII->get(PPC::BCC))
7494       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7495     BB->addSuccessor(loop2MBB);
7496     BB->addSuccessor(midMBB);
7497
7498     BB = loop2MBB;
7499     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7500       .addReg(newval).addReg(ptrA).addReg(ptrB);
7501     BuildMI(BB, dl, TII->get(PPC::BCC))
7502       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7503     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7504     BB->addSuccessor(loop1MBB);
7505     BB->addSuccessor(exitMBB);
7506
7507     BB = midMBB;
7508     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7509       .addReg(dest).addReg(ptrA).addReg(ptrB);
7510     BB->addSuccessor(exitMBB);
7511
7512     //  exitMBB:
7513     //   ...
7514     BB = exitMBB;
7515   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7516              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7517     // We must use 64-bit registers for addresses when targeting 64-bit,
7518     // since we're actually doing arithmetic on them.  Other registers
7519     // can be 32-bit.
7520     bool is64bit = Subtarget.isPPC64();
7521     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7522
7523     unsigned dest   = MI->getOperand(0).getReg();
7524     unsigned ptrA   = MI->getOperand(1).getReg();
7525     unsigned ptrB   = MI->getOperand(2).getReg();
7526     unsigned oldval = MI->getOperand(3).getReg();
7527     unsigned newval = MI->getOperand(4).getReg();
7528     DebugLoc dl     = MI->getDebugLoc();
7529
7530     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7531     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7532     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7533     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7534     F->insert(It, loop1MBB);
7535     F->insert(It, loop2MBB);
7536     F->insert(It, midMBB);
7537     F->insert(It, exitMBB);
7538     exitMBB->splice(exitMBB->begin(), BB,
7539                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7540     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7541
7542     MachineRegisterInfo &RegInfo = F->getRegInfo();
7543     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7544                                             : &PPC::GPRCRegClass;
7545     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7546     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7547     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7548     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7549     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7550     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7551     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7552     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7553     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7554     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7555     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7556     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7557     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7558     unsigned Ptr1Reg;
7559     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7560     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7561     //  thisMBB:
7562     //   ...
7563     //   fallthrough --> loopMBB
7564     BB->addSuccessor(loop1MBB);
7565
7566     // The 4-byte load must be aligned, while a char or short may be
7567     // anywhere in the word.  Hence all this nasty bookkeeping code.
7568     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7569     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7570     //   xori shift, shift1, 24 [16]
7571     //   rlwinm ptr, ptr1, 0, 0, 29
7572     //   slw newval2, newval, shift
7573     //   slw oldval2, oldval,shift
7574     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7575     //   slw mask, mask2, shift
7576     //   and newval3, newval2, mask
7577     //   and oldval3, oldval2, mask
7578     // loop1MBB:
7579     //   lwarx tmpDest, ptr
7580     //   and tmp, tmpDest, mask
7581     //   cmpw tmp, oldval3
7582     //   bne- midMBB
7583     // loop2MBB:
7584     //   andc tmp2, tmpDest, mask
7585     //   or tmp4, tmp2, newval3
7586     //   stwcx. tmp4, ptr
7587     //   bne- loop1MBB
7588     //   b exitBB
7589     // midMBB:
7590     //   stwcx. tmpDest, ptr
7591     // exitBB:
7592     //   srw dest, tmpDest, shift
7593     if (ptrA != ZeroReg) {
7594       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7595       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7596         .addReg(ptrA).addReg(ptrB);
7597     } else {
7598       Ptr1Reg = ptrB;
7599     }
7600     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7601         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7602     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7603         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7604     if (is64bit)
7605       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7606         .addReg(Ptr1Reg).addImm(0).addImm(61);
7607     else
7608       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7609         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7610     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7611         .addReg(newval).addReg(ShiftReg);
7612     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7613         .addReg(oldval).addReg(ShiftReg);
7614     if (is8bit)
7615       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7616     else {
7617       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7618       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7619         .addReg(Mask3Reg).addImm(65535);
7620     }
7621     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7622         .addReg(Mask2Reg).addReg(ShiftReg);
7623     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7624         .addReg(NewVal2Reg).addReg(MaskReg);
7625     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7626         .addReg(OldVal2Reg).addReg(MaskReg);
7627
7628     BB = loop1MBB;
7629     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7630         .addReg(ZeroReg).addReg(PtrReg);
7631     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7632         .addReg(TmpDestReg).addReg(MaskReg);
7633     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7634         .addReg(TmpReg).addReg(OldVal3Reg);
7635     BuildMI(BB, dl, TII->get(PPC::BCC))
7636         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7637     BB->addSuccessor(loop2MBB);
7638     BB->addSuccessor(midMBB);
7639
7640     BB = loop2MBB;
7641     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7642         .addReg(TmpDestReg).addReg(MaskReg);
7643     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7644         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7645     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7646         .addReg(ZeroReg).addReg(PtrReg);
7647     BuildMI(BB, dl, TII->get(PPC::BCC))
7648       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7649     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7650     BB->addSuccessor(loop1MBB);
7651     BB->addSuccessor(exitMBB);
7652
7653     BB = midMBB;
7654     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7655       .addReg(ZeroReg).addReg(PtrReg);
7656     BB->addSuccessor(exitMBB);
7657
7658     //  exitMBB:
7659     //   ...
7660     BB = exitMBB;
7661     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7662       .addReg(ShiftReg);
7663   } else if (MI->getOpcode() == PPC::FADDrtz) {
7664     // This pseudo performs an FADD with rounding mode temporarily forced
7665     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7666     // is not modeled at the SelectionDAG level.
7667     unsigned Dest = MI->getOperand(0).getReg();
7668     unsigned Src1 = MI->getOperand(1).getReg();
7669     unsigned Src2 = MI->getOperand(2).getReg();
7670     DebugLoc dl   = MI->getDebugLoc();
7671
7672     MachineRegisterInfo &RegInfo = F->getRegInfo();
7673     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7674
7675     // Save FPSCR value.
7676     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7677
7678     // Set rounding mode to round-to-zero.
7679     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7680     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7681
7682     // Perform addition.
7683     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7684
7685     // Restore FPSCR value.
7686     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7687   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7688              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7689              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7690              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7691     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7692                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7693                       PPC::ANDIo8 : PPC::ANDIo;
7694     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7695                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7696
7697     MachineRegisterInfo &RegInfo = F->getRegInfo();
7698     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7699                                                   &PPC::GPRCRegClass :
7700                                                   &PPC::G8RCRegClass);
7701
7702     DebugLoc dl   = MI->getDebugLoc();
7703     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7704       .addReg(MI->getOperand(1).getReg()).addImm(1);
7705     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7706             MI->getOperand(0).getReg())
7707       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7708   } else {
7709     llvm_unreachable("Unexpected instr type to insert");
7710   }
7711
7712   MI->eraseFromParent();   // The pseudo instruction is gone now.
7713   return BB;
7714 }
7715
7716 //===----------------------------------------------------------------------===//
7717 // Target Optimization Hooks
7718 //===----------------------------------------------------------------------===//
7719
7720 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7721                                             DAGCombinerInfo &DCI,
7722                                             unsigned &RefinementSteps,
7723                                             bool &UseOneConstNR) const {
7724   EVT VT = Operand.getValueType();
7725   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7726       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7727       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7728       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7729     // Convergence is quadratic, so we essentially double the number of digits
7730     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7731     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7732     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7733     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7734     if (VT.getScalarType() == MVT::f64)
7735       ++RefinementSteps;
7736     UseOneConstNR = true;
7737     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7738   }
7739   return SDValue();
7740 }
7741
7742 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7743                                             DAGCombinerInfo &DCI,
7744                                             unsigned &RefinementSteps) const {
7745   EVT VT = Operand.getValueType();
7746   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7747       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7748       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7749       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7750     // Convergence is quadratic, so we essentially double the number of digits
7751     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7752     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7753     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7754     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7755     if (VT.getScalarType() == MVT::f64)
7756       ++RefinementSteps;
7757     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7758   }
7759   return SDValue();
7760 }
7761
7762 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7763   // Note: This functionality is used only when unsafe-fp-math is enabled, and
7764   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7765   // enabled for division), this functionality is redundant with the default
7766   // combiner logic (once the division -> reciprocal/multiply transformation
7767   // has taken place). As a result, this matters more for older cores than for
7768   // newer ones.
7769
7770   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7771   // reciprocal if there are two or more FDIVs (for embedded cores with only
7772   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7773   switch (Subtarget.getDarwinDirective()) {
7774   default:
7775     return NumUsers > 2;
7776   case PPC::DIR_440:
7777   case PPC::DIR_A2:
7778   case PPC::DIR_E500mc:
7779   case PPC::DIR_E5500:
7780     return NumUsers > 1;
7781   }
7782 }
7783
7784 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7785                             unsigned Bytes, int Dist,
7786                             SelectionDAG &DAG) {
7787   if (VT.getSizeInBits() / 8 != Bytes)
7788     return false;
7789
7790   SDValue BaseLoc = Base->getBasePtr();
7791   if (Loc.getOpcode() == ISD::FrameIndex) {
7792     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7793       return false;
7794     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7795     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7796     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7797     int FS  = MFI->getObjectSize(FI);
7798     int BFS = MFI->getObjectSize(BFI);
7799     if (FS != BFS || FS != (int)Bytes) return false;
7800     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7801   }
7802
7803   // Handle X+C
7804   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7805       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7806     return true;
7807
7808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7809   const GlobalValue *GV1 = nullptr;
7810   const GlobalValue *GV2 = nullptr;
7811   int64_t Offset1 = 0;
7812   int64_t Offset2 = 0;
7813   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7814   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7815   if (isGA1 && isGA2 && GV1 == GV2)
7816     return Offset1 == (Offset2 + Dist*Bytes);
7817   return false;
7818 }
7819
7820 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7821 // not enforce equality of the chain operands.
7822 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7823                             unsigned Bytes, int Dist,
7824                             SelectionDAG &DAG) {
7825   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7826     EVT VT = LS->getMemoryVT();
7827     SDValue Loc = LS->getBasePtr();
7828     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7829   }
7830
7831   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7832     EVT VT;
7833     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7834     default: return false;
7835     case Intrinsic::ppc_altivec_lvx:
7836     case Intrinsic::ppc_altivec_lvxl:
7837     case Intrinsic::ppc_vsx_lxvw4x:
7838       VT = MVT::v4i32;
7839       break;
7840     case Intrinsic::ppc_vsx_lxvd2x:
7841       VT = MVT::v2f64;
7842       break;
7843     case Intrinsic::ppc_altivec_lvebx:
7844       VT = MVT::i8;
7845       break;
7846     case Intrinsic::ppc_altivec_lvehx:
7847       VT = MVT::i16;
7848       break;
7849     case Intrinsic::ppc_altivec_lvewx:
7850       VT = MVT::i32;
7851       break;
7852     }
7853
7854     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7855   }
7856
7857   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7858     EVT VT;
7859     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7860     default: return false;
7861     case Intrinsic::ppc_altivec_stvx:
7862     case Intrinsic::ppc_altivec_stvxl:
7863     case Intrinsic::ppc_vsx_stxvw4x:
7864       VT = MVT::v4i32;
7865       break;
7866     case Intrinsic::ppc_vsx_stxvd2x:
7867       VT = MVT::v2f64;
7868       break;
7869     case Intrinsic::ppc_altivec_stvebx:
7870       VT = MVT::i8;
7871       break;
7872     case Intrinsic::ppc_altivec_stvehx:
7873       VT = MVT::i16;
7874       break;
7875     case Intrinsic::ppc_altivec_stvewx:
7876       VT = MVT::i32;
7877       break;
7878     }
7879
7880     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7881   }
7882
7883   return false;
7884 }
7885
7886 // Return true is there is a nearyby consecutive load to the one provided
7887 // (regardless of alignment). We search up and down the chain, looking though
7888 // token factors and other loads (but nothing else). As a result, a true result
7889 // indicates that it is safe to create a new consecutive load adjacent to the
7890 // load provided.
7891 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7892   SDValue Chain = LD->getChain();
7893   EVT VT = LD->getMemoryVT();
7894
7895   SmallSet<SDNode *, 16> LoadRoots;
7896   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7897   SmallSet<SDNode *, 16> Visited;
7898
7899   // First, search up the chain, branching to follow all token-factor operands.
7900   // If we find a consecutive load, then we're done, otherwise, record all
7901   // nodes just above the top-level loads and token factors.
7902   while (!Queue.empty()) {
7903     SDNode *ChainNext = Queue.pop_back_val();
7904     if (!Visited.insert(ChainNext).second)
7905       continue;
7906
7907     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7908       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7909         return true;
7910
7911       if (!Visited.count(ChainLD->getChain().getNode()))
7912         Queue.push_back(ChainLD->getChain().getNode());
7913     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7914       for (const SDUse &O : ChainNext->ops())
7915         if (!Visited.count(O.getNode()))
7916           Queue.push_back(O.getNode());
7917     } else
7918       LoadRoots.insert(ChainNext);
7919   }
7920
7921   // Second, search down the chain, starting from the top-level nodes recorded
7922   // in the first phase. These top-level nodes are the nodes just above all
7923   // loads and token factors. Starting with their uses, recursively look though
7924   // all loads (just the chain uses) and token factors to find a consecutive
7925   // load.
7926   Visited.clear();
7927   Queue.clear();
7928
7929   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7930        IE = LoadRoots.end(); I != IE; ++I) {
7931     Queue.push_back(*I);
7932        
7933     while (!Queue.empty()) {
7934       SDNode *LoadRoot = Queue.pop_back_val();
7935       if (!Visited.insert(LoadRoot).second)
7936         continue;
7937
7938       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7939         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7940           return true;
7941
7942       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7943            UE = LoadRoot->use_end(); UI != UE; ++UI)
7944         if (((isa<MemSDNode>(*UI) &&
7945             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7946             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7947           Queue.push_back(*UI);
7948     }
7949   }
7950
7951   return false;
7952 }
7953
7954 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7955                                                   DAGCombinerInfo &DCI) const {
7956   SelectionDAG &DAG = DCI.DAG;
7957   SDLoc dl(N);
7958
7959   assert(Subtarget.useCRBits() &&
7960          "Expecting to be tracking CR bits");
7961   // If we're tracking CR bits, we need to be careful that we don't have:
7962   //   trunc(binary-ops(zext(x), zext(y)))
7963   // or
7964   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7965   // such that we're unnecessarily moving things into GPRs when it would be
7966   // better to keep them in CR bits.
7967
7968   // Note that trunc here can be an actual i1 trunc, or can be the effective
7969   // truncation that comes from a setcc or select_cc.
7970   if (N->getOpcode() == ISD::TRUNCATE &&
7971       N->getValueType(0) != MVT::i1)
7972     return SDValue();
7973
7974   if (N->getOperand(0).getValueType() != MVT::i32 &&
7975       N->getOperand(0).getValueType() != MVT::i64)
7976     return SDValue();
7977
7978   if (N->getOpcode() == ISD::SETCC ||
7979       N->getOpcode() == ISD::SELECT_CC) {
7980     // If we're looking at a comparison, then we need to make sure that the
7981     // high bits (all except for the first) don't matter the result.
7982     ISD::CondCode CC =
7983       cast<CondCodeSDNode>(N->getOperand(
7984         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7985     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7986
7987     if (ISD::isSignedIntSetCC(CC)) {
7988       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7989           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7990         return SDValue();
7991     } else if (ISD::isUnsignedIntSetCC(CC)) {
7992       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7993                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7994           !DAG.MaskedValueIsZero(N->getOperand(1),
7995                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7996         return SDValue();
7997     } else {
7998       // This is neither a signed nor an unsigned comparison, just make sure
7999       // that the high bits are equal.
8000       APInt Op1Zero, Op1One;
8001       APInt Op2Zero, Op2One;
8002       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
8003       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
8004
8005       // We don't really care about what is known about the first bit (if
8006       // anything), so clear it in all masks prior to comparing them.
8007       Op1Zero.clearBit(0); Op1One.clearBit(0);
8008       Op2Zero.clearBit(0); Op2One.clearBit(0);
8009
8010       if (Op1Zero != Op2Zero || Op1One != Op2One)
8011         return SDValue();
8012     }
8013   }
8014
8015   // We now know that the higher-order bits are irrelevant, we just need to
8016   // make sure that all of the intermediate operations are bit operations, and
8017   // all inputs are extensions.
8018   if (N->getOperand(0).getOpcode() != ISD::AND &&
8019       N->getOperand(0).getOpcode() != ISD::OR  &&
8020       N->getOperand(0).getOpcode() != ISD::XOR &&
8021       N->getOperand(0).getOpcode() != ISD::SELECT &&
8022       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
8023       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
8024       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
8025       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
8026       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
8027     return SDValue();
8028
8029   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
8030       N->getOperand(1).getOpcode() != ISD::AND &&
8031       N->getOperand(1).getOpcode() != ISD::OR  &&
8032       N->getOperand(1).getOpcode() != ISD::XOR &&
8033       N->getOperand(1).getOpcode() != ISD::SELECT &&
8034       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
8035       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
8036       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
8037       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
8038       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
8039     return SDValue();
8040
8041   SmallVector<SDValue, 4> Inputs;
8042   SmallVector<SDValue, 8> BinOps, PromOps;
8043   SmallPtrSet<SDNode *, 16> Visited;
8044
8045   for (unsigned i = 0; i < 2; ++i) {
8046     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8047           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8048           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8049           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8050         isa<ConstantSDNode>(N->getOperand(i)))
8051       Inputs.push_back(N->getOperand(i));
8052     else
8053       BinOps.push_back(N->getOperand(i));
8054
8055     if (N->getOpcode() == ISD::TRUNCATE)
8056       break;
8057   }
8058
8059   // Visit all inputs, collect all binary operations (and, or, xor and
8060   // select) that are all fed by extensions. 
8061   while (!BinOps.empty()) {
8062     SDValue BinOp = BinOps.back();
8063     BinOps.pop_back();
8064
8065     if (!Visited.insert(BinOp.getNode()).second)
8066       continue;
8067
8068     PromOps.push_back(BinOp);
8069
8070     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8071       // The condition of the select is not promoted.
8072       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8073         continue;
8074       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8075         continue;
8076
8077       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8078             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8079             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8080            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8081           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8082         Inputs.push_back(BinOp.getOperand(i)); 
8083       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8084                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8085                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8086                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8087                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8088                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8089                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8090                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8091                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8092         BinOps.push_back(BinOp.getOperand(i));
8093       } else {
8094         // We have an input that is not an extension or another binary
8095         // operation; we'll abort this transformation.
8096         return SDValue();
8097       }
8098     }
8099   }
8100
8101   // Make sure that this is a self-contained cluster of operations (which
8102   // is not quite the same thing as saying that everything has only one
8103   // use).
8104   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8105     if (isa<ConstantSDNode>(Inputs[i]))
8106       continue;
8107
8108     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8109                               UE = Inputs[i].getNode()->use_end();
8110          UI != UE; ++UI) {
8111       SDNode *User = *UI;
8112       if (User != N && !Visited.count(User))
8113         return SDValue();
8114
8115       // Make sure that we're not going to promote the non-output-value
8116       // operand(s) or SELECT or SELECT_CC.
8117       // FIXME: Although we could sometimes handle this, and it does occur in
8118       // practice that one of the condition inputs to the select is also one of
8119       // the outputs, we currently can't deal with this.
8120       if (User->getOpcode() == ISD::SELECT) {
8121         if (User->getOperand(0) == Inputs[i])
8122           return SDValue();
8123       } else if (User->getOpcode() == ISD::SELECT_CC) {
8124         if (User->getOperand(0) == Inputs[i] ||
8125             User->getOperand(1) == Inputs[i])
8126           return SDValue();
8127       }
8128     }
8129   }
8130
8131   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8132     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8133                               UE = PromOps[i].getNode()->use_end();
8134          UI != UE; ++UI) {
8135       SDNode *User = *UI;
8136       if (User != N && !Visited.count(User))
8137         return SDValue();
8138
8139       // Make sure that we're not going to promote the non-output-value
8140       // operand(s) or SELECT or SELECT_CC.
8141       // FIXME: Although we could sometimes handle this, and it does occur in
8142       // practice that one of the condition inputs to the select is also one of
8143       // the outputs, we currently can't deal with this.
8144       if (User->getOpcode() == ISD::SELECT) {
8145         if (User->getOperand(0) == PromOps[i])
8146           return SDValue();
8147       } else if (User->getOpcode() == ISD::SELECT_CC) {
8148         if (User->getOperand(0) == PromOps[i] ||
8149             User->getOperand(1) == PromOps[i])
8150           return SDValue();
8151       }
8152     }
8153   }
8154
8155   // Replace all inputs with the extension operand.
8156   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8157     // Constants may have users outside the cluster of to-be-promoted nodes,
8158     // and so we need to replace those as we do the promotions.
8159     if (isa<ConstantSDNode>(Inputs[i]))
8160       continue;
8161     else
8162       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
8163   }
8164
8165   // Replace all operations (these are all the same, but have a different
8166   // (i1) return type). DAG.getNode will validate that the types of
8167   // a binary operator match, so go through the list in reverse so that
8168   // we've likely promoted both operands first. Any intermediate truncations or
8169   // extensions disappear.
8170   while (!PromOps.empty()) {
8171     SDValue PromOp = PromOps.back();
8172     PromOps.pop_back();
8173
8174     if (PromOp.getOpcode() == ISD::TRUNCATE ||
8175         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8176         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8177         PromOp.getOpcode() == ISD::ANY_EXTEND) {
8178       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8179           PromOp.getOperand(0).getValueType() != MVT::i1) {
8180         // The operand is not yet ready (see comment below).
8181         PromOps.insert(PromOps.begin(), PromOp);
8182         continue;
8183       }
8184
8185       SDValue RepValue = PromOp.getOperand(0);
8186       if (isa<ConstantSDNode>(RepValue))
8187         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8188
8189       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8190       continue;
8191     }
8192
8193     unsigned C;
8194     switch (PromOp.getOpcode()) {
8195     default:             C = 0; break;
8196     case ISD::SELECT:    C = 1; break;
8197     case ISD::SELECT_CC: C = 2; break;
8198     }
8199
8200     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8201          PromOp.getOperand(C).getValueType() != MVT::i1) ||
8202         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8203          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8204       // The to-be-promoted operands of this node have not yet been
8205       // promoted (this should be rare because we're going through the
8206       // list backward, but if one of the operands has several users in
8207       // this cluster of to-be-promoted nodes, it is possible).
8208       PromOps.insert(PromOps.begin(), PromOp);
8209       continue;
8210     }
8211
8212     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8213                                 PromOp.getNode()->op_end());
8214
8215     // If there are any constant inputs, make sure they're replaced now.
8216     for (unsigned i = 0; i < 2; ++i)
8217       if (isa<ConstantSDNode>(Ops[C+i]))
8218         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8219
8220     DAG.ReplaceAllUsesOfValueWith(PromOp,
8221       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8222   }
8223
8224   // Now we're left with the initial truncation itself.
8225   if (N->getOpcode() == ISD::TRUNCATE)
8226     return N->getOperand(0);
8227
8228   // Otherwise, this is a comparison. The operands to be compared have just
8229   // changed type (to i1), but everything else is the same.
8230   return SDValue(N, 0);
8231 }
8232
8233 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8234                                                   DAGCombinerInfo &DCI) const {
8235   SelectionDAG &DAG = DCI.DAG;
8236   SDLoc dl(N);
8237
8238   // If we're tracking CR bits, we need to be careful that we don't have:
8239   //   zext(binary-ops(trunc(x), trunc(y)))
8240   // or
8241   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8242   // such that we're unnecessarily moving things into CR bits that can more
8243   // efficiently stay in GPRs. Note that if we're not certain that the high
8244   // bits are set as required by the final extension, we still may need to do
8245   // some masking to get the proper behavior.
8246
8247   // This same functionality is important on PPC64 when dealing with
8248   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8249   // the return values of functions. Because it is so similar, it is handled
8250   // here as well.
8251
8252   if (N->getValueType(0) != MVT::i32 &&
8253       N->getValueType(0) != MVT::i64)
8254     return SDValue();
8255
8256   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8257         Subtarget.useCRBits()) ||
8258        (N->getOperand(0).getValueType() == MVT::i32 &&
8259         Subtarget.isPPC64())))
8260     return SDValue();
8261
8262   if (N->getOperand(0).getOpcode() != ISD::AND &&
8263       N->getOperand(0).getOpcode() != ISD::OR  &&
8264       N->getOperand(0).getOpcode() != ISD::XOR &&
8265       N->getOperand(0).getOpcode() != ISD::SELECT &&
8266       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8267     return SDValue();
8268
8269   SmallVector<SDValue, 4> Inputs;
8270   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8271   SmallPtrSet<SDNode *, 16> Visited;
8272
8273   // Visit all inputs, collect all binary operations (and, or, xor and
8274   // select) that are all fed by truncations. 
8275   while (!BinOps.empty()) {
8276     SDValue BinOp = BinOps.back();
8277     BinOps.pop_back();
8278
8279     if (!Visited.insert(BinOp.getNode()).second)
8280       continue;
8281
8282     PromOps.push_back(BinOp);
8283
8284     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8285       // The condition of the select is not promoted.
8286       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8287         continue;
8288       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8289         continue;
8290
8291       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8292           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8293         Inputs.push_back(BinOp.getOperand(i)); 
8294       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8295                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8296                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8297                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8298                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8299         BinOps.push_back(BinOp.getOperand(i));
8300       } else {
8301         // We have an input that is not a truncation or another binary
8302         // operation; we'll abort this transformation.
8303         return SDValue();
8304       }
8305     }
8306   }
8307
8308   // The operands of a select that must be truncated when the select is
8309   // promoted because the operand is actually part of the to-be-promoted set.
8310   DenseMap<SDNode *, EVT> SelectTruncOp[2];
8311
8312   // Make sure that this is a self-contained cluster of operations (which
8313   // is not quite the same thing as saying that everything has only one
8314   // use).
8315   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8316     if (isa<ConstantSDNode>(Inputs[i]))
8317       continue;
8318
8319     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8320                               UE = Inputs[i].getNode()->use_end();
8321          UI != UE; ++UI) {
8322       SDNode *User = *UI;
8323       if (User != N && !Visited.count(User))
8324         return SDValue();
8325
8326       // If we're going to promote the non-output-value operand(s) or SELECT or
8327       // SELECT_CC, record them for truncation.
8328       if (User->getOpcode() == ISD::SELECT) {
8329         if (User->getOperand(0) == Inputs[i])
8330           SelectTruncOp[0].insert(std::make_pair(User,
8331                                     User->getOperand(0).getValueType()));
8332       } else if (User->getOpcode() == ISD::SELECT_CC) {
8333         if (User->getOperand(0) == Inputs[i])
8334           SelectTruncOp[0].insert(std::make_pair(User,
8335                                     User->getOperand(0).getValueType()));
8336         if (User->getOperand(1) == Inputs[i])
8337           SelectTruncOp[1].insert(std::make_pair(User,
8338                                     User->getOperand(1).getValueType()));
8339       }
8340     }
8341   }
8342
8343   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8344     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8345                               UE = PromOps[i].getNode()->use_end();
8346          UI != UE; ++UI) {
8347       SDNode *User = *UI;
8348       if (User != N && !Visited.count(User))
8349         return SDValue();
8350
8351       // If we're going to promote the non-output-value operand(s) or SELECT or
8352       // SELECT_CC, record them for truncation.
8353       if (User->getOpcode() == ISD::SELECT) {
8354         if (User->getOperand(0) == PromOps[i])
8355           SelectTruncOp[0].insert(std::make_pair(User,
8356                                     User->getOperand(0).getValueType()));
8357       } else if (User->getOpcode() == ISD::SELECT_CC) {
8358         if (User->getOperand(0) == PromOps[i])
8359           SelectTruncOp[0].insert(std::make_pair(User,
8360                                     User->getOperand(0).getValueType()));
8361         if (User->getOperand(1) == PromOps[i])
8362           SelectTruncOp[1].insert(std::make_pair(User,
8363                                     User->getOperand(1).getValueType()));
8364       }
8365     }
8366   }
8367
8368   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8369   bool ReallyNeedsExt = false;
8370   if (N->getOpcode() != ISD::ANY_EXTEND) {
8371     // If all of the inputs are not already sign/zero extended, then
8372     // we'll still need to do that at the end.
8373     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8374       if (isa<ConstantSDNode>(Inputs[i]))
8375         continue;
8376
8377       unsigned OpBits =
8378         Inputs[i].getOperand(0).getValueSizeInBits();
8379       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8380
8381       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8382            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8383                                   APInt::getHighBitsSet(OpBits,
8384                                                         OpBits-PromBits))) ||
8385           (N->getOpcode() == ISD::SIGN_EXTEND &&
8386            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8387              (OpBits-(PromBits-1)))) {
8388         ReallyNeedsExt = true;
8389         break;
8390       }
8391     }
8392   }
8393
8394   // Replace all inputs, either with the truncation operand, or a
8395   // truncation or extension to the final output type.
8396   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8397     // Constant inputs need to be replaced with the to-be-promoted nodes that
8398     // use them because they might have users outside of the cluster of
8399     // promoted nodes.
8400     if (isa<ConstantSDNode>(Inputs[i]))
8401       continue;
8402
8403     SDValue InSrc = Inputs[i].getOperand(0);
8404     if (Inputs[i].getValueType() == N->getValueType(0))
8405       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8406     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8407       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8408         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8409     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8410       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8411         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8412     else
8413       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8414         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8415   }
8416
8417   // Replace all operations (these are all the same, but have a different
8418   // (promoted) return type). DAG.getNode will validate that the types of
8419   // a binary operator match, so go through the list in reverse so that
8420   // we've likely promoted both operands first.
8421   while (!PromOps.empty()) {
8422     SDValue PromOp = PromOps.back();
8423     PromOps.pop_back();
8424
8425     unsigned C;
8426     switch (PromOp.getOpcode()) {
8427     default:             C = 0; break;
8428     case ISD::SELECT:    C = 1; break;
8429     case ISD::SELECT_CC: C = 2; break;
8430     }
8431
8432     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8433          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8434         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8435          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8436       // The to-be-promoted operands of this node have not yet been
8437       // promoted (this should be rare because we're going through the
8438       // list backward, but if one of the operands has several users in
8439       // this cluster of to-be-promoted nodes, it is possible).
8440       PromOps.insert(PromOps.begin(), PromOp);
8441       continue;
8442     }
8443
8444     // For SELECT and SELECT_CC nodes, we do a similar check for any
8445     // to-be-promoted comparison inputs.
8446     if (PromOp.getOpcode() == ISD::SELECT ||
8447         PromOp.getOpcode() == ISD::SELECT_CC) {
8448       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8449            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8450           (SelectTruncOp[1].count(PromOp.getNode()) &&
8451            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8452         PromOps.insert(PromOps.begin(), PromOp);
8453         continue;
8454       }
8455     }
8456
8457     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8458                                 PromOp.getNode()->op_end());
8459
8460     // If this node has constant inputs, then they'll need to be promoted here.
8461     for (unsigned i = 0; i < 2; ++i) {
8462       if (!isa<ConstantSDNode>(Ops[C+i]))
8463         continue;
8464       if (Ops[C+i].getValueType() == N->getValueType(0))
8465         continue;
8466
8467       if (N->getOpcode() == ISD::SIGN_EXTEND)
8468         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8469       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8470         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8471       else
8472         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8473     }
8474
8475     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8476     // truncate them again to the original value type.
8477     if (PromOp.getOpcode() == ISD::SELECT ||
8478         PromOp.getOpcode() == ISD::SELECT_CC) {
8479       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8480       if (SI0 != SelectTruncOp[0].end())
8481         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8482       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8483       if (SI1 != SelectTruncOp[1].end())
8484         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8485     }
8486
8487     DAG.ReplaceAllUsesOfValueWith(PromOp,
8488       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8489   }
8490
8491   // Now we're left with the initial extension itself.
8492   if (!ReallyNeedsExt)
8493     return N->getOperand(0);
8494
8495   // To zero extend, just mask off everything except for the first bit (in the
8496   // i1 case).
8497   if (N->getOpcode() == ISD::ZERO_EXTEND)
8498     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8499                        DAG.getConstant(APInt::getLowBitsSet(
8500                                          N->getValueSizeInBits(0), PromBits),
8501                                        N->getValueType(0)));
8502
8503   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8504          "Invalid extension type");
8505   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8506   SDValue ShiftCst =
8507     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8508   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8509                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8510                                  N->getOperand(0), ShiftCst), ShiftCst);
8511 }
8512
8513 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8514                                               DAGCombinerInfo &DCI) const {
8515   assert((N->getOpcode() == ISD::SINT_TO_FP ||
8516           N->getOpcode() == ISD::UINT_TO_FP) &&
8517          "Need an int -> FP conversion node here");
8518
8519   if (!Subtarget.has64BitSupport())
8520     return SDValue();
8521
8522   SelectionDAG &DAG = DCI.DAG;
8523   SDLoc dl(N);
8524   SDValue Op(N, 0);
8525
8526   // Don't handle ppc_fp128 here or i1 conversions.
8527   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8528     return SDValue();
8529   if (Op.getOperand(0).getValueType() == MVT::i1)
8530     return SDValue();
8531
8532   // For i32 intermediate values, unfortunately, the conversion functions
8533   // leave the upper 32 bits of the value are undefined. Within the set of
8534   // scalar instructions, we have no method for zero- or sign-extending the
8535   // value. Thus, we cannot handle i32 intermediate values here.
8536   if (Op.getOperand(0).getValueType() == MVT::i32)
8537     return SDValue();
8538
8539   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8540          "UINT_TO_FP is supported only with FPCVT");
8541
8542   // If we have FCFIDS, then use it when converting to single-precision.
8543   // Otherwise, convert to double-precision and then round.
8544   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8545                    (Op.getOpcode() == ISD::UINT_TO_FP ?
8546                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
8547                    (Op.getOpcode() == ISD::UINT_TO_FP ?
8548                     PPCISD::FCFIDU : PPCISD::FCFID);
8549   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8550                    MVT::f32 : MVT::f64;
8551
8552   // If we're converting from a float, to an int, and back to a float again,
8553   // then we don't need the store/load pair at all.
8554   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8555        Subtarget.hasFPCVT()) ||
8556       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8557     SDValue Src = Op.getOperand(0).getOperand(0);
8558     if (Src.getValueType() == MVT::f32) {
8559       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8560       DCI.AddToWorklist(Src.getNode());
8561     }
8562
8563     unsigned FCTOp =
8564       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8565                                                         PPCISD::FCTIDUZ;
8566
8567     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8568     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8569
8570     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8571       FP = DAG.getNode(ISD::FP_ROUND, dl,
8572                        MVT::f32, FP, DAG.getIntPtrConstant(0));
8573       DCI.AddToWorklist(FP.getNode());
8574     }
8575
8576     return FP;
8577   }
8578
8579   return SDValue();
8580 }
8581
8582 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8583 // builtins) into loads with swaps.
8584 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8585                                               DAGCombinerInfo &DCI) const {
8586   SelectionDAG &DAG = DCI.DAG;
8587   SDLoc dl(N);
8588   SDValue Chain;
8589   SDValue Base;
8590   MachineMemOperand *MMO;
8591
8592   switch (N->getOpcode()) {
8593   default:
8594     llvm_unreachable("Unexpected opcode for little endian VSX load");
8595   case ISD::LOAD: {
8596     LoadSDNode *LD = cast<LoadSDNode>(N);
8597     Chain = LD->getChain();
8598     Base = LD->getBasePtr();
8599     MMO = LD->getMemOperand();
8600     // If the MMO suggests this isn't a load of a full vector, leave
8601     // things alone.  For a built-in, we have to make the change for
8602     // correctness, so if there is a size problem that will be a bug.
8603     if (MMO->getSize() < 16)
8604       return SDValue();
8605     break;
8606   }
8607   case ISD::INTRINSIC_W_CHAIN: {
8608     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8609     Chain = Intrin->getChain();
8610     Base = Intrin->getBasePtr();
8611     MMO = Intrin->getMemOperand();
8612     break;
8613   }
8614   }
8615
8616   MVT VecTy = N->getValueType(0).getSimpleVT();
8617   SDValue LoadOps[] = { Chain, Base };
8618   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8619                                          DAG.getVTList(VecTy, MVT::Other),
8620                                          LoadOps, VecTy, MMO);
8621   DCI.AddToWorklist(Load.getNode());
8622   Chain = Load.getValue(1);
8623   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8624                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8625   DCI.AddToWorklist(Swap.getNode());
8626   return Swap;
8627 }
8628
8629 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8630 // builtins) into stores with swaps.
8631 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8632                                                DAGCombinerInfo &DCI) const {
8633   SelectionDAG &DAG = DCI.DAG;
8634   SDLoc dl(N);
8635   SDValue Chain;
8636   SDValue Base;
8637   unsigned SrcOpnd;
8638   MachineMemOperand *MMO;
8639
8640   switch (N->getOpcode()) {
8641   default:
8642     llvm_unreachable("Unexpected opcode for little endian VSX store");
8643   case ISD::STORE: {
8644     StoreSDNode *ST = cast<StoreSDNode>(N);
8645     Chain = ST->getChain();
8646     Base = ST->getBasePtr();
8647     MMO = ST->getMemOperand();
8648     SrcOpnd = 1;
8649     // If the MMO suggests this isn't a store of a full vector, leave
8650     // things alone.  For a built-in, we have to make the change for
8651     // correctness, so if there is a size problem that will be a bug.
8652     if (MMO->getSize() < 16)
8653       return SDValue();
8654     break;
8655   }
8656   case ISD::INTRINSIC_VOID: {
8657     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8658     Chain = Intrin->getChain();
8659     // Intrin->getBasePtr() oddly does not get what we want.
8660     Base = Intrin->getOperand(3);
8661     MMO = Intrin->getMemOperand();
8662     SrcOpnd = 2;
8663     break;
8664   }
8665   }
8666
8667   SDValue Src = N->getOperand(SrcOpnd);
8668   MVT VecTy = Src.getValueType().getSimpleVT();
8669   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8670                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8671   DCI.AddToWorklist(Swap.getNode());
8672   Chain = Swap.getValue(1);
8673   SDValue StoreOps[] = { Chain, Swap, Base };
8674   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8675                                           DAG.getVTList(MVT::Other),
8676                                           StoreOps, VecTy, MMO);
8677   DCI.AddToWorklist(Store.getNode());
8678   return Store;
8679 }
8680
8681 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8682                                              DAGCombinerInfo &DCI) const {
8683   const TargetMachine &TM = getTargetMachine();
8684   SelectionDAG &DAG = DCI.DAG;
8685   SDLoc dl(N);
8686   switch (N->getOpcode()) {
8687   default: break;
8688   case PPCISD::SHL:
8689     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8690       if (C->isNullValue())   // 0 << V -> 0.
8691         return N->getOperand(0);
8692     }
8693     break;
8694   case PPCISD::SRL:
8695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8696       if (C->isNullValue())   // 0 >>u V -> 0.
8697         return N->getOperand(0);
8698     }
8699     break;
8700   case PPCISD::SRA:
8701     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8702       if (C->isNullValue() ||   //  0 >>s V -> 0.
8703           C->isAllOnesValue())    // -1 >>s V -> -1.
8704         return N->getOperand(0);
8705     }
8706     break;
8707   case ISD::SIGN_EXTEND:
8708   case ISD::ZERO_EXTEND:
8709   case ISD::ANY_EXTEND: 
8710     return DAGCombineExtBoolTrunc(N, DCI);
8711   case ISD::TRUNCATE:
8712   case ISD::SETCC:
8713   case ISD::SELECT_CC:
8714     return DAGCombineTruncBoolExt(N, DCI);
8715   case ISD::SINT_TO_FP:
8716   case ISD::UINT_TO_FP:
8717     return combineFPToIntToFP(N, DCI);
8718   case ISD::STORE: {
8719     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8720     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8721         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8722         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8723         N->getOperand(1).getValueType() == MVT::i32 &&
8724         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8725       SDValue Val = N->getOperand(1).getOperand(0);
8726       if (Val.getValueType() == MVT::f32) {
8727         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8728         DCI.AddToWorklist(Val.getNode());
8729       }
8730       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8731       DCI.AddToWorklist(Val.getNode());
8732
8733       SDValue Ops[] = {
8734         N->getOperand(0), Val, N->getOperand(2),
8735         DAG.getValueType(N->getOperand(1).getValueType())
8736       };
8737
8738       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8739               DAG.getVTList(MVT::Other), Ops,
8740               cast<StoreSDNode>(N)->getMemoryVT(),
8741               cast<StoreSDNode>(N)->getMemOperand());
8742       DCI.AddToWorklist(Val.getNode());
8743       return Val;
8744     }
8745
8746     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8747     if (cast<StoreSDNode>(N)->isUnindexed() &&
8748         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8749         N->getOperand(1).getNode()->hasOneUse() &&
8750         (N->getOperand(1).getValueType() == MVT::i32 ||
8751          N->getOperand(1).getValueType() == MVT::i16 ||
8752          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8753           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8754           N->getOperand(1).getValueType() == MVT::i64))) {
8755       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8756       // Do an any-extend to 32-bits if this is a half-word input.
8757       if (BSwapOp.getValueType() == MVT::i16)
8758         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8759
8760       SDValue Ops[] = {
8761         N->getOperand(0), BSwapOp, N->getOperand(2),
8762         DAG.getValueType(N->getOperand(1).getValueType())
8763       };
8764       return
8765         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8766                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8767                                 cast<StoreSDNode>(N)->getMemOperand());
8768     }
8769
8770     // For little endian, VSX stores require generating xxswapd/lxvd2x.
8771     EVT VT = N->getOperand(1).getValueType();
8772     if (VT.isSimple()) {
8773       MVT StoreVT = VT.getSimpleVT();
8774       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8775           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8776           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8777            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8778         return expandVSXStoreForLE(N, DCI);
8779     }
8780     break;
8781   }
8782   case ISD::LOAD: {
8783     LoadSDNode *LD = cast<LoadSDNode>(N);
8784     EVT VT = LD->getValueType(0);
8785
8786     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8787     if (VT.isSimple()) {
8788       MVT LoadVT = VT.getSimpleVT();
8789       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8790           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8791           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8792            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8793         return expandVSXLoadForLE(N, DCI);
8794     }
8795
8796     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8797     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8798     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8799         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8800         // P8 and later hardware should just use LOAD.
8801         !TM.getSubtarget<PPCSubtarget>().hasP8Vector() &&
8802         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8803          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8804         LD->getAlignment() < ABIAlignment) {
8805       // This is a type-legal unaligned Altivec load.
8806       SDValue Chain = LD->getChain();
8807       SDValue Ptr = LD->getBasePtr();
8808       bool isLittleEndian = Subtarget.isLittleEndian();
8809
8810       // This implements the loading of unaligned vectors as described in
8811       // the venerable Apple Velocity Engine overview. Specifically:
8812       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8813       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8814       //
8815       // The general idea is to expand a sequence of one or more unaligned
8816       // loads into an alignment-based permutation-control instruction (lvsl
8817       // or lvsr), a series of regular vector loads (which always truncate
8818       // their input address to an aligned address), and a series of
8819       // permutations.  The results of these permutations are the requested
8820       // loaded values.  The trick is that the last "extra" load is not taken
8821       // from the address you might suspect (sizeof(vector) bytes after the
8822       // last requested load), but rather sizeof(vector) - 1 bytes after the
8823       // last requested vector. The point of this is to avoid a page fault if
8824       // the base address happened to be aligned. This works because if the
8825       // base address is aligned, then adding less than a full vector length
8826       // will cause the last vector in the sequence to be (re)loaded.
8827       // Otherwise, the next vector will be fetched as you might suspect was
8828       // necessary.
8829
8830       // We might be able to reuse the permutation generation from
8831       // a different base address offset from this one by an aligned amount.
8832       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8833       // optimization later.
8834       Intrinsic::ID Intr = (isLittleEndian ?
8835                             Intrinsic::ppc_altivec_lvsr :
8836                             Intrinsic::ppc_altivec_lvsl);
8837       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8838
8839       // Create the new MMO for the new base load. It is like the original MMO,
8840       // but represents an area in memory almost twice the vector size centered
8841       // on the original address. If the address is unaligned, we might start
8842       // reading up to (sizeof(vector)-1) bytes below the address of the
8843       // original unaligned load.
8844       MachineFunction &MF = DAG.getMachineFunction();
8845       MachineMemOperand *BaseMMO =
8846         MF.getMachineMemOperand(LD->getMemOperand(),
8847                                 -LD->getMemoryVT().getStoreSize()+1,
8848                                 2*LD->getMemoryVT().getStoreSize()-1);
8849
8850       // Create the new base load.
8851       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8852                                                getPointerTy());
8853       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8854       SDValue BaseLoad =
8855         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8856                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8857                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8858
8859       // Note that the value of IncOffset (which is provided to the next
8860       // load's pointer info offset value, and thus used to calculate the
8861       // alignment), and the value of IncValue (which is actually used to
8862       // increment the pointer value) are different! This is because we
8863       // require the next load to appear to be aligned, even though it
8864       // is actually offset from the base pointer by a lesser amount.
8865       int IncOffset = VT.getSizeInBits() / 8;
8866       int IncValue = IncOffset;
8867
8868       // Walk (both up and down) the chain looking for another load at the real
8869       // (aligned) offset (the alignment of the other load does not matter in
8870       // this case). If found, then do not use the offset reduction trick, as
8871       // that will prevent the loads from being later combined (as they would
8872       // otherwise be duplicates).
8873       if (!findConsecutiveLoad(LD, DAG))
8874         --IncValue;
8875
8876       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8877       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8878
8879       MachineMemOperand *ExtraMMO =
8880         MF.getMachineMemOperand(LD->getMemOperand(),
8881                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
8882       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8883       SDValue ExtraLoad =
8884         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8885                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8886                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8887
8888       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8889         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8890
8891       // Because vperm has a big-endian bias, we must reverse the order
8892       // of the input vectors and complement the permute control vector
8893       // when generating little endian code.  We have already handled the
8894       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8895       // and ExtraLoad here.
8896       SDValue Perm;
8897       if (isLittleEndian)
8898         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8899                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8900       else
8901         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8902                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8903
8904       if (VT != MVT::v4i32)
8905         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8906
8907       // The output of the permutation is our loaded result, the TokenFactor is
8908       // our new chain.
8909       DCI.CombineTo(N, Perm, TF);
8910       return SDValue(N, 0);
8911     }
8912     }
8913     break;
8914   case ISD::INTRINSIC_WO_CHAIN: {
8915     bool isLittleEndian = Subtarget.isLittleEndian();
8916     Intrinsic::ID Intr = (isLittleEndian ?
8917                           Intrinsic::ppc_altivec_lvsr :
8918                           Intrinsic::ppc_altivec_lvsl);
8919     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8920         N->getOperand(1)->getOpcode() == ISD::ADD) {
8921       SDValue Add = N->getOperand(1);
8922
8923       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8924             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8925               Add.getValueType().getScalarType().getSizeInBits()))) {
8926         SDNode *BasePtr = Add->getOperand(0).getNode();
8927         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8928              UE = BasePtr->use_end(); UI != UE; ++UI) {
8929           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8930               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8931                 Intr) {
8932             // We've found another LVSL/LVSR, and this address is an aligned
8933             // multiple of that one. The results will be the same, so use the
8934             // one we've just found instead.
8935
8936             return SDValue(*UI, 0);
8937           }
8938         }
8939       }
8940     }
8941     }
8942
8943     break;
8944   case ISD::INTRINSIC_W_CHAIN: {
8945     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8946     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8947         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8948       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8949       default:
8950         break;
8951       case Intrinsic::ppc_vsx_lxvw4x:
8952       case Intrinsic::ppc_vsx_lxvd2x:
8953         return expandVSXLoadForLE(N, DCI);
8954       }
8955     }
8956     break;
8957   }
8958   case ISD::INTRINSIC_VOID: {
8959     // For little endian, VSX stores require generating xxswapd/stxvd2x.
8960     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8961         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8962       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8963       default:
8964         break;
8965       case Intrinsic::ppc_vsx_stxvw4x:
8966       case Intrinsic::ppc_vsx_stxvd2x:
8967         return expandVSXStoreForLE(N, DCI);
8968       }
8969     }
8970     break;
8971   }
8972   case ISD::BSWAP:
8973     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8974     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8975         N->getOperand(0).hasOneUse() &&
8976         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8977          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8978           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8979           N->getValueType(0) == MVT::i64))) {
8980       SDValue Load = N->getOperand(0);
8981       LoadSDNode *LD = cast<LoadSDNode>(Load);
8982       // Create the byte-swapping load.
8983       SDValue Ops[] = {
8984         LD->getChain(),    // Chain
8985         LD->getBasePtr(),  // Ptr
8986         DAG.getValueType(N->getValueType(0)) // VT
8987       };
8988       SDValue BSLoad =
8989         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8990                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8991                                               MVT::i64 : MVT::i32, MVT::Other),
8992                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8993
8994       // If this is an i16 load, insert the truncate.
8995       SDValue ResVal = BSLoad;
8996       if (N->getValueType(0) == MVT::i16)
8997         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8998
8999       // First, combine the bswap away.  This makes the value produced by the
9000       // load dead.
9001       DCI.CombineTo(N, ResVal);
9002
9003       // Next, combine the load away, we give it a bogus result value but a real
9004       // chain result.  The result value is dead because the bswap is dead.
9005       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
9006
9007       // Return N so it doesn't get rechecked!
9008       return SDValue(N, 0);
9009     }
9010
9011     break;
9012   case PPCISD::VCMP: {
9013     // If a VCMPo node already exists with exactly the same operands as this
9014     // node, use its result instead of this node (VCMPo computes both a CR6 and
9015     // a normal output).
9016     //
9017     if (!N->getOperand(0).hasOneUse() &&
9018         !N->getOperand(1).hasOneUse() &&
9019         !N->getOperand(2).hasOneUse()) {
9020
9021       // Scan all of the users of the LHS, looking for VCMPo's that match.
9022       SDNode *VCMPoNode = nullptr;
9023
9024       SDNode *LHSN = N->getOperand(0).getNode();
9025       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
9026            UI != E; ++UI)
9027         if (UI->getOpcode() == PPCISD::VCMPo &&
9028             UI->getOperand(1) == N->getOperand(1) &&
9029             UI->getOperand(2) == N->getOperand(2) &&
9030             UI->getOperand(0) == N->getOperand(0)) {
9031           VCMPoNode = *UI;
9032           break;
9033         }
9034
9035       // If there is no VCMPo node, or if the flag value has a single use, don't
9036       // transform this.
9037       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
9038         break;
9039
9040       // Look at the (necessarily single) use of the flag value.  If it has a
9041       // chain, this transformation is more complex.  Note that multiple things
9042       // could use the value result, which we should ignore.
9043       SDNode *FlagUser = nullptr;
9044       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
9045            FlagUser == nullptr; ++UI) {
9046         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
9047         SDNode *User = *UI;
9048         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
9049           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
9050             FlagUser = User;
9051             break;
9052           }
9053         }
9054       }
9055
9056       // If the user is a MFOCRF instruction, we know this is safe.
9057       // Otherwise we give up for right now.
9058       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9059         return SDValue(VCMPoNode, 0);
9060     }
9061     break;
9062   }
9063   case ISD::BRCOND: {
9064     SDValue Cond = N->getOperand(1);
9065     SDValue Target = N->getOperand(2);
9066  
9067     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9068         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9069           Intrinsic::ppc_is_decremented_ctr_nonzero) {
9070
9071       // We now need to make the intrinsic dead (it cannot be instruction
9072       // selected).
9073       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9074       assert(Cond.getNode()->hasOneUse() &&
9075              "Counter decrement has more than one use");
9076
9077       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9078                          N->getOperand(0), Target);
9079     }
9080   }
9081   break;
9082   case ISD::BR_CC: {
9083     // If this is a branch on an altivec predicate comparison, lower this so
9084     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
9085     // lowering is done pre-legalize, because the legalizer lowers the predicate
9086     // compare down to code that is difficult to reassemble.
9087     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9088     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9089
9090     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9091     // value. If so, pass-through the AND to get to the intrinsic.
9092     if (LHS.getOpcode() == ISD::AND &&
9093         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9094         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9095           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9096         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9097         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9098           isZero())
9099       LHS = LHS.getOperand(0);
9100
9101     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9102         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9103           Intrinsic::ppc_is_decremented_ctr_nonzero &&
9104         isa<ConstantSDNode>(RHS)) {
9105       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9106              "Counter decrement comparison is not EQ or NE");
9107
9108       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9109       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9110                     (CC == ISD::SETNE && !Val);
9111
9112       // We now need to make the intrinsic dead (it cannot be instruction
9113       // selected).
9114       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9115       assert(LHS.getNode()->hasOneUse() &&
9116              "Counter decrement has more than one use");
9117
9118       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9119                          N->getOperand(0), N->getOperand(4));
9120     }
9121
9122     int CompareOpc;
9123     bool isDot;
9124
9125     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9126         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9127         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9128       assert(isDot && "Can't compare against a vector result!");
9129
9130       // If this is a comparison against something other than 0/1, then we know
9131       // that the condition is never/always true.
9132       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9133       if (Val != 0 && Val != 1) {
9134         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
9135           return N->getOperand(0);
9136         // Always !=, turn it into an unconditional branch.
9137         return DAG.getNode(ISD::BR, dl, MVT::Other,
9138                            N->getOperand(0), N->getOperand(4));
9139       }
9140
9141       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9142
9143       // Create the PPCISD altivec 'dot' comparison node.
9144       SDValue Ops[] = {
9145         LHS.getOperand(2),  // LHS of compare
9146         LHS.getOperand(3),  // RHS of compare
9147         DAG.getConstant(CompareOpc, MVT::i32)
9148       };
9149       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9150       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9151
9152       // Unpack the result based on how the target uses it.
9153       PPC::Predicate CompOpc;
9154       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9155       default:  // Can't happen, don't crash on invalid number though.
9156       case 0:   // Branch on the value of the EQ bit of CR6.
9157         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9158         break;
9159       case 1:   // Branch on the inverted value of the EQ bit of CR6.
9160         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9161         break;
9162       case 2:   // Branch on the value of the LT bit of CR6.
9163         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9164         break;
9165       case 3:   // Branch on the inverted value of the LT bit of CR6.
9166         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9167         break;
9168       }
9169
9170       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9171                          DAG.getConstant(CompOpc, MVT::i32),
9172                          DAG.getRegister(PPC::CR6, MVT::i32),
9173                          N->getOperand(4), CompNode.getValue(1));
9174     }
9175     break;
9176   }
9177   }
9178
9179   return SDValue();
9180 }
9181
9182 SDValue
9183 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9184                                   SelectionDAG &DAG,
9185                                   std::vector<SDNode *> *Created) const {
9186   // fold (sdiv X, pow2)
9187   EVT VT = N->getValueType(0);
9188   if (VT == MVT::i64 && !Subtarget.isPPC64())
9189     return SDValue();
9190   if ((VT != MVT::i32 && VT != MVT::i64) ||
9191       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9192     return SDValue();
9193
9194   SDLoc DL(N);
9195   SDValue N0 = N->getOperand(0);
9196
9197   bool IsNegPow2 = (-Divisor).isPowerOf2();
9198   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9199   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9200
9201   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9202   if (Created)
9203     Created->push_back(Op.getNode());
9204
9205   if (IsNegPow2) {
9206     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9207     if (Created)
9208       Created->push_back(Op.getNode());
9209   }
9210
9211   return Op;
9212 }
9213
9214 //===----------------------------------------------------------------------===//
9215 // Inline Assembly Support
9216 //===----------------------------------------------------------------------===//
9217
9218 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9219                                                       APInt &KnownZero,
9220                                                       APInt &KnownOne,
9221                                                       const SelectionDAG &DAG,
9222                                                       unsigned Depth) const {
9223   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9224   switch (Op.getOpcode()) {
9225   default: break;
9226   case PPCISD::LBRX: {
9227     // lhbrx is known to have the top bits cleared out.
9228     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9229       KnownZero = 0xFFFF0000;
9230     break;
9231   }
9232   case ISD::INTRINSIC_WO_CHAIN: {
9233     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9234     default: break;
9235     case Intrinsic::ppc_altivec_vcmpbfp_p:
9236     case Intrinsic::ppc_altivec_vcmpeqfp_p:
9237     case Intrinsic::ppc_altivec_vcmpequb_p:
9238     case Intrinsic::ppc_altivec_vcmpequh_p:
9239     case Intrinsic::ppc_altivec_vcmpequw_p:
9240     case Intrinsic::ppc_altivec_vcmpgefp_p:
9241     case Intrinsic::ppc_altivec_vcmpgtfp_p:
9242     case Intrinsic::ppc_altivec_vcmpgtsb_p:
9243     case Intrinsic::ppc_altivec_vcmpgtsh_p:
9244     case Intrinsic::ppc_altivec_vcmpgtsw_p:
9245     case Intrinsic::ppc_altivec_vcmpgtub_p:
9246     case Intrinsic::ppc_altivec_vcmpgtuh_p:
9247     case Intrinsic::ppc_altivec_vcmpgtuw_p:
9248       KnownZero = ~1U;  // All bits but the low one are known to be zero.
9249       break;
9250     }
9251   }
9252   }
9253 }
9254
9255 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9256   switch (Subtarget.getDarwinDirective()) {
9257   default: break;
9258   case PPC::DIR_970:
9259   case PPC::DIR_PWR4:
9260   case PPC::DIR_PWR5:
9261   case PPC::DIR_PWR5X:
9262   case PPC::DIR_PWR6:
9263   case PPC::DIR_PWR6X:
9264   case PPC::DIR_PWR7:
9265   case PPC::DIR_PWR8: {
9266     if (!ML)
9267       break;
9268
9269     const PPCInstrInfo *TII =
9270       static_cast<const PPCInstrInfo *>(getTargetMachine().getSubtargetImpl()->
9271                                           getInstrInfo());
9272
9273     // For small loops (between 5 and 8 instructions), align to a 32-byte
9274     // boundary so that the entire loop fits in one instruction-cache line.
9275     uint64_t LoopSize = 0;
9276     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9277       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9278         LoopSize += TII->GetInstSizeInBytes(J);
9279
9280     if (LoopSize > 16 && LoopSize <= 32)
9281       return 5;
9282
9283     break;
9284   }
9285   }
9286
9287   return TargetLowering::getPrefLoopAlignment(ML);
9288 }
9289
9290 /// getConstraintType - Given a constraint, return the type of
9291 /// constraint it is for this target.
9292 PPCTargetLowering::ConstraintType
9293 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9294   if (Constraint.size() == 1) {
9295     switch (Constraint[0]) {
9296     default: break;
9297     case 'b':
9298     case 'r':
9299     case 'f':
9300     case 'v':
9301     case 'y':
9302       return C_RegisterClass;
9303     case 'Z':
9304       // FIXME: While Z does indicate a memory constraint, it specifically
9305       // indicates an r+r address (used in conjunction with the 'y' modifier
9306       // in the replacement string). Currently, we're forcing the base
9307       // register to be r0 in the asm printer (which is interpreted as zero)
9308       // and forming the complete address in the second register. This is
9309       // suboptimal.
9310       return C_Memory;
9311     }
9312   } else if (Constraint == "wc") { // individual CR bits.
9313     return C_RegisterClass;
9314   } else if (Constraint == "wa" || Constraint == "wd" ||
9315              Constraint == "wf" || Constraint == "ws") {
9316     return C_RegisterClass; // VSX registers.
9317   }
9318   return TargetLowering::getConstraintType(Constraint);
9319 }
9320
9321 /// Examine constraint type and operand type and determine a weight value.
9322 /// This object must already have been set up with the operand type
9323 /// and the current alternative constraint selected.
9324 TargetLowering::ConstraintWeight
9325 PPCTargetLowering::getSingleConstraintMatchWeight(
9326     AsmOperandInfo &info, const char *constraint) const {
9327   ConstraintWeight weight = CW_Invalid;
9328   Value *CallOperandVal = info.CallOperandVal;
9329     // If we don't have a value, we can't do a match,
9330     // but allow it at the lowest weight.
9331   if (!CallOperandVal)
9332     return CW_Default;
9333   Type *type = CallOperandVal->getType();
9334
9335   // Look at the constraint type.
9336   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9337     return CW_Register; // an individual CR bit.
9338   else if ((StringRef(constraint) == "wa" ||
9339             StringRef(constraint) == "wd" ||
9340             StringRef(constraint) == "wf") &&
9341            type->isVectorTy())
9342     return CW_Register;
9343   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9344     return CW_Register;
9345
9346   switch (*constraint) {
9347   default:
9348     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9349     break;
9350   case 'b':
9351     if (type->isIntegerTy())
9352       weight = CW_Register;
9353     break;
9354   case 'f':
9355     if (type->isFloatTy())
9356       weight = CW_Register;
9357     break;
9358   case 'd':
9359     if (type->isDoubleTy())
9360       weight = CW_Register;
9361     break;
9362   case 'v':
9363     if (type->isVectorTy())
9364       weight = CW_Register;
9365     break;
9366   case 'y':
9367     weight = CW_Register;
9368     break;
9369   case 'Z':
9370     weight = CW_Memory;
9371     break;
9372   }
9373   return weight;
9374 }
9375
9376 std::pair<unsigned, const TargetRegisterClass*>
9377 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9378                                                 MVT VT) const {
9379   if (Constraint.size() == 1) {
9380     // GCC RS6000 Constraint Letters
9381     switch (Constraint[0]) {
9382     case 'b':   // R1-R31
9383       if (VT == MVT::i64 && Subtarget.isPPC64())
9384         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9385       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9386     case 'r':   // R0-R31
9387       if (VT == MVT::i64 && Subtarget.isPPC64())
9388         return std::make_pair(0U, &PPC::G8RCRegClass);
9389       return std::make_pair(0U, &PPC::GPRCRegClass);
9390     case 'f':
9391       if (VT == MVT::f32 || VT == MVT::i32)
9392         return std::make_pair(0U, &PPC::F4RCRegClass);
9393       if (VT == MVT::f64 || VT == MVT::i64)
9394         return std::make_pair(0U, &PPC::F8RCRegClass);
9395       break;
9396     case 'v':
9397       return std::make_pair(0U, &PPC::VRRCRegClass);
9398     case 'y':   // crrc
9399       return std::make_pair(0U, &PPC::CRRCRegClass);
9400     }
9401   } else if (Constraint == "wc") { // an individual CR bit.
9402     return std::make_pair(0U, &PPC::CRBITRCRegClass);
9403   } else if (Constraint == "wa" || Constraint == "wd" ||
9404              Constraint == "wf") {
9405     return std::make_pair(0U, &PPC::VSRCRegClass);
9406   } else if (Constraint == "ws") {
9407     return std::make_pair(0U, &PPC::VSFRCRegClass);
9408   }
9409
9410   std::pair<unsigned, const TargetRegisterClass*> R =
9411     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9412
9413   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9414   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9415   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9416   // register.
9417   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9418   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9419   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9420       PPC::GPRCRegClass.contains(R.first)) {
9421     const TargetRegisterInfo *TRI =
9422         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
9423     return std::make_pair(TRI->getMatchingSuperReg(R.first,
9424                             PPC::sub_32, &PPC::G8RCRegClass),
9425                           &PPC::G8RCRegClass);
9426   }
9427
9428   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9429   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9430     R.first = PPC::CR0;
9431     R.second = &PPC::CRRCRegClass;
9432   }
9433
9434   return R;
9435 }
9436
9437
9438 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9439 /// vector.  If it is invalid, don't add anything to Ops.
9440 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9441                                                      std::string &Constraint,
9442                                                      std::vector<SDValue>&Ops,
9443                                                      SelectionDAG &DAG) const {
9444   SDValue Result;
9445
9446   // Only support length 1 constraints.
9447   if (Constraint.length() > 1) return;
9448
9449   char Letter = Constraint[0];
9450   switch (Letter) {
9451   default: break;
9452   case 'I':
9453   case 'J':
9454   case 'K':
9455   case 'L':
9456   case 'M':
9457   case 'N':
9458   case 'O':
9459   case 'P': {
9460     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9461     if (!CST) return; // Must be an immediate to match.
9462     int64_t Value = CST->getSExtValue();
9463     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9464                          // numbers are printed as such.
9465     switch (Letter) {
9466     default: llvm_unreachable("Unknown constraint letter!");
9467     case 'I':  // "I" is a signed 16-bit constant.
9468       if (isInt<16>(Value))
9469         Result = DAG.getTargetConstant(Value, TCVT);
9470       break;
9471     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9472       if (isShiftedUInt<16, 16>(Value))
9473         Result = DAG.getTargetConstant(Value, TCVT);
9474       break;
9475     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9476       if (isShiftedInt<16, 16>(Value))
9477         Result = DAG.getTargetConstant(Value, TCVT);
9478       break;
9479     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9480       if (isUInt<16>(Value))
9481         Result = DAG.getTargetConstant(Value, TCVT);
9482       break;
9483     case 'M':  // "M" is a constant that is greater than 31.
9484       if (Value > 31)
9485         Result = DAG.getTargetConstant(Value, TCVT);
9486       break;
9487     case 'N':  // "N" is a positive constant that is an exact power of two.
9488       if (Value > 0 && isPowerOf2_64(Value))
9489         Result = DAG.getTargetConstant(Value, TCVT);
9490       break;
9491     case 'O':  // "O" is the constant zero.
9492       if (Value == 0)
9493         Result = DAG.getTargetConstant(Value, TCVT);
9494       break;
9495     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9496       if (isInt<16>(-Value))
9497         Result = DAG.getTargetConstant(Value, TCVT);
9498       break;
9499     }
9500     break;
9501   }
9502   }
9503
9504   if (Result.getNode()) {
9505     Ops.push_back(Result);
9506     return;
9507   }
9508
9509   // Handle standard constraint letters.
9510   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9511 }
9512
9513 // isLegalAddressingMode - Return true if the addressing mode represented
9514 // by AM is legal for this target, for a load/store of the specified type.
9515 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9516                                               Type *Ty) const {
9517   // FIXME: PPC does not allow r+i addressing modes for vectors!
9518
9519   // PPC allows a sign-extended 16-bit immediate field.
9520   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9521     return false;
9522
9523   // No global is ever allowed as a base.
9524   if (AM.BaseGV)
9525     return false;
9526
9527   // PPC only support r+r,
9528   switch (AM.Scale) {
9529   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9530     break;
9531   case 1:
9532     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9533       return false;
9534     // Otherwise we have r+r or r+i.
9535     break;
9536   case 2:
9537     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9538       return false;
9539     // Allow 2*r as r+r.
9540     break;
9541   default:
9542     // No other scales are supported.
9543     return false;
9544   }
9545
9546   return true;
9547 }
9548
9549 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9550                                            SelectionDAG &DAG) const {
9551   MachineFunction &MF = DAG.getMachineFunction();
9552   MachineFrameInfo *MFI = MF.getFrameInfo();
9553   MFI->setReturnAddressIsTaken(true);
9554
9555   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9556     return SDValue();
9557
9558   SDLoc dl(Op);
9559   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9560
9561   // Make sure the function does not optimize away the store of the RA to
9562   // the stack.
9563   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9564   FuncInfo->setLRStoreRequired();
9565   bool isPPC64 = Subtarget.isPPC64();
9566   bool isDarwinABI = Subtarget.isDarwinABI();
9567
9568   if (Depth > 0) {
9569     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9570     SDValue Offset =
9571
9572       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9573                       isPPC64? MVT::i64 : MVT::i32);
9574     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9575                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9576                                    FrameAddr, Offset),
9577                        MachinePointerInfo(), false, false, false, 0);
9578   }
9579
9580   // Just load the return address off the stack.
9581   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9582   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9583                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9584 }
9585
9586 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9587                                           SelectionDAG &DAG) const {
9588   SDLoc dl(Op);
9589   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9590
9591   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9592   bool isPPC64 = PtrVT == MVT::i64;
9593
9594   MachineFunction &MF = DAG.getMachineFunction();
9595   MachineFrameInfo *MFI = MF.getFrameInfo();
9596   MFI->setFrameAddressIsTaken(true);
9597
9598   // Naked functions never have a frame pointer, and so we use r1. For all
9599   // other functions, this decision must be delayed until during PEI.
9600   unsigned FrameReg;
9601   if (MF.getFunction()->getAttributes().hasAttribute(
9602         AttributeSet::FunctionIndex, Attribute::Naked))
9603     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9604   else
9605     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9606
9607   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9608                                          PtrVT);
9609   while (Depth--)
9610     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9611                             FrameAddr, MachinePointerInfo(), false, false,
9612                             false, 0);
9613   return FrameAddr;
9614 }
9615
9616 // FIXME? Maybe this could be a TableGen attribute on some registers and
9617 // this table could be generated automatically from RegInfo.
9618 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9619                                               EVT VT) const {
9620   bool isPPC64 = Subtarget.isPPC64();
9621   bool isDarwinABI = Subtarget.isDarwinABI();
9622
9623   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9624       (!isPPC64 && VT != MVT::i32))
9625     report_fatal_error("Invalid register global variable type");
9626
9627   bool is64Bit = isPPC64 && VT == MVT::i64;
9628   unsigned Reg = StringSwitch<unsigned>(RegName)
9629                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9630                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9631                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9632                                   (is64Bit ? PPC::X13 : PPC::R13))
9633                    .Default(0);
9634
9635   if (Reg)
9636     return Reg;
9637   report_fatal_error("Invalid register name global variable");
9638 }
9639
9640 bool
9641 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9642   // The PowerPC target isn't yet aware of offsets.
9643   return false;
9644 }
9645
9646 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9647                                            const CallInst &I,
9648                                            unsigned Intrinsic) const {
9649
9650   switch (Intrinsic) {
9651   case Intrinsic::ppc_altivec_lvx:
9652   case Intrinsic::ppc_altivec_lvxl:
9653   case Intrinsic::ppc_altivec_lvebx:
9654   case Intrinsic::ppc_altivec_lvehx:
9655   case Intrinsic::ppc_altivec_lvewx:
9656   case Intrinsic::ppc_vsx_lxvd2x:
9657   case Intrinsic::ppc_vsx_lxvw4x: {
9658     EVT VT;
9659     switch (Intrinsic) {
9660     case Intrinsic::ppc_altivec_lvebx:
9661       VT = MVT::i8;
9662       break;
9663     case Intrinsic::ppc_altivec_lvehx:
9664       VT = MVT::i16;
9665       break;
9666     case Intrinsic::ppc_altivec_lvewx:
9667       VT = MVT::i32;
9668       break;
9669     case Intrinsic::ppc_vsx_lxvd2x:
9670       VT = MVT::v2f64;
9671       break;
9672     default:
9673       VT = MVT::v4i32;
9674       break;
9675     }
9676
9677     Info.opc = ISD::INTRINSIC_W_CHAIN;
9678     Info.memVT = VT;
9679     Info.ptrVal = I.getArgOperand(0);
9680     Info.offset = -VT.getStoreSize()+1;
9681     Info.size = 2*VT.getStoreSize()-1;
9682     Info.align = 1;
9683     Info.vol = false;
9684     Info.readMem = true;
9685     Info.writeMem = false;
9686     return true;
9687   }
9688   case Intrinsic::ppc_altivec_stvx:
9689   case Intrinsic::ppc_altivec_stvxl:
9690   case Intrinsic::ppc_altivec_stvebx:
9691   case Intrinsic::ppc_altivec_stvehx:
9692   case Intrinsic::ppc_altivec_stvewx:
9693   case Intrinsic::ppc_vsx_stxvd2x:
9694   case Intrinsic::ppc_vsx_stxvw4x: {
9695     EVT VT;
9696     switch (Intrinsic) {
9697     case Intrinsic::ppc_altivec_stvebx:
9698       VT = MVT::i8;
9699       break;
9700     case Intrinsic::ppc_altivec_stvehx:
9701       VT = MVT::i16;
9702       break;
9703     case Intrinsic::ppc_altivec_stvewx:
9704       VT = MVT::i32;
9705       break;
9706     case Intrinsic::ppc_vsx_stxvd2x:
9707       VT = MVT::v2f64;
9708       break;
9709     default:
9710       VT = MVT::v4i32;
9711       break;
9712     }
9713
9714     Info.opc = ISD::INTRINSIC_VOID;
9715     Info.memVT = VT;
9716     Info.ptrVal = I.getArgOperand(1);
9717     Info.offset = -VT.getStoreSize()+1;
9718     Info.size = 2*VT.getStoreSize()-1;
9719     Info.align = 1;
9720     Info.vol = false;
9721     Info.readMem = false;
9722     Info.writeMem = true;
9723     return true;
9724   }
9725   default:
9726     break;
9727   }
9728
9729   return false;
9730 }
9731
9732 /// getOptimalMemOpType - Returns the target specific optimal type for load
9733 /// and store operations as a result of memset, memcpy, and memmove
9734 /// lowering. If DstAlign is zero that means it's safe to destination
9735 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9736 /// means there isn't a need to check it against alignment requirement,
9737 /// probably because the source does not need to be loaded. If 'IsMemset' is
9738 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9739 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9740 /// source is constant so it does not need to be loaded.
9741 /// It returns EVT::Other if the type should be determined using generic
9742 /// target-independent logic.
9743 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9744                                            unsigned DstAlign, unsigned SrcAlign,
9745                                            bool IsMemset, bool ZeroMemset,
9746                                            bool MemcpyStrSrc,
9747                                            MachineFunction &MF) const {
9748   if (Subtarget.isPPC64()) {
9749     return MVT::i64;
9750   } else {
9751     return MVT::i32;
9752   }
9753 }
9754
9755 /// \brief Returns true if it is beneficial to convert a load of a constant
9756 /// to just the constant itself.
9757 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9758                                                           Type *Ty) const {
9759   assert(Ty->isIntegerTy());
9760
9761   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9762   if (BitSize == 0 || BitSize > 64)
9763     return false;
9764   return true;
9765 }
9766
9767 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9768   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9769     return false;
9770   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9771   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9772   return NumBits1 == 64 && NumBits2 == 32;
9773 }
9774
9775 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9776   if (!VT1.isInteger() || !VT2.isInteger())
9777     return false;
9778   unsigned NumBits1 = VT1.getSizeInBits();
9779   unsigned NumBits2 = VT2.getSizeInBits();
9780   return NumBits1 == 64 && NumBits2 == 32;
9781 }
9782
9783 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9784   return isInt<16>(Imm) || isUInt<16>(Imm);
9785 }
9786
9787 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9788   return isInt<16>(Imm) || isUInt<16>(Imm);
9789 }
9790
9791 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9792                                                        unsigned,
9793                                                        unsigned,
9794                                                        bool *Fast) const {
9795   if (DisablePPCUnaligned)
9796     return false;
9797
9798   // PowerPC supports unaligned memory access for simple non-vector types.
9799   // Although accessing unaligned addresses is not as efficient as accessing
9800   // aligned addresses, it is generally more efficient than manual expansion,
9801   // and generally only traps for software emulation when crossing page
9802   // boundaries.
9803
9804   if (!VT.isSimple())
9805     return false;
9806
9807   if (VT.getSimpleVT().isVector()) {
9808     if (Subtarget.hasVSX()) {
9809       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9810           VT != MVT::v4f32 && VT != MVT::v4i32)
9811         return false;
9812     } else {
9813       return false;
9814     }
9815   }
9816
9817   if (VT == MVT::ppcf128)
9818     return false;
9819
9820   if (Fast)
9821     *Fast = true;
9822
9823   return true;
9824 }
9825
9826 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9827   VT = VT.getScalarType();
9828
9829   if (!VT.isSimple())
9830     return false;
9831
9832   switch (VT.getSimpleVT().SimpleTy) {
9833   case MVT::f32:
9834   case MVT::f64:
9835     return true;
9836   default:
9837     break;
9838   }
9839
9840   return false;
9841 }
9842
9843 bool
9844 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9845                      EVT VT , unsigned DefinedValues) const {
9846   if (VT == MVT::v2i64)
9847     return false;
9848
9849   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9850 }
9851
9852 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9853   if (DisableILPPref || Subtarget.enableMachineScheduler())
9854     return TargetLowering::getSchedulingPreference(N);
9855
9856   return Sched::ILP;
9857 }
9858
9859 // Create a fast isel object.
9860 FastISel *
9861 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9862                                   const TargetLibraryInfo *LibInfo) const {
9863   return PPC::createFastISel(FuncInfo, LibInfo);
9864 }