Don't use 128bit functions on PPC32.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
40 using namespace llvm;
41
42 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
43 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
44
45 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
46 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
49 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
50
51 // FIXME: Remove this once the bug has been fixed!
52 extern cl::opt<bool> ANDIGlueBug;
53
54 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
55   // If it isn't a Mach-O file then it's going to be a linux ELF
56   // object file.
57   if (TT.isOSDarwin())
58     return new TargetLoweringObjectFileMachO();
59
60   return new PPC64LinuxTargetObjectFile();
61 }
62
63 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
64     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
65       Subtarget(*TM.getSubtargetImpl()) {
66   setPow2DivIsCheap();
67
68   // Use _setjmp/_longjmp instead of setjmp/longjmp.
69   setUseUnderscoreSetJmp(true);
70   setUseUnderscoreLongJmp(true);
71
72   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73   // arguments are at least 4/8 bytes aligned.
74   bool isPPC64 = Subtarget.isPPC64();
75   setMinStackArgumentAlignment(isPPC64 ? 8:4);
76
77   // Set up the register classes.
78   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
81
82   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
85
86   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87
88   // PowerPC has pre-inc load and store's.
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99
100   if (Subtarget.useCRBits()) {
101     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
102
103     if (isPPC64 || Subtarget.hasFPCVT()) {
104       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106                          isPPC64 ? MVT::i64 : MVT::i32);
107       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
109                          isPPC64 ? MVT::i64 : MVT::i32);
110     } else {
111       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
113     }
114
115     // PowerPC does not support direct load / store of condition registers
116     setOperationAction(ISD::LOAD, MVT::i1, Custom);
117     setOperationAction(ISD::STORE, MVT::i1, Custom);
118
119     // FIXME: Remove this once the ANDI glue bug is fixed:
120     if (ANDIGlueBug)
121       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
122
123     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
129
130     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
131   }
132
133   // This is used in the ppcf128->int sequence.  Note it has different semantics
134   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
135   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
136
137   // We do not currently implement these libm ops for PowerPC.
138   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
140   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
142   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
144
145   // PowerPC has no SREM/UREM instructions
146   setOperationAction(ISD::SREM, MVT::i32, Expand);
147   setOperationAction(ISD::UREM, MVT::i32, Expand);
148   setOperationAction(ISD::SREM, MVT::i64, Expand);
149   setOperationAction(ISD::UREM, MVT::i64, Expand);
150
151   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
160
161   // We don't support sin/cos/sqrt/fmod/pow
162   setOperationAction(ISD::FSIN , MVT::f64, Expand);
163   setOperationAction(ISD::FCOS , MVT::f64, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165   setOperationAction(ISD::FREM , MVT::f64, Expand);
166   setOperationAction(ISD::FPOW , MVT::f64, Expand);
167   setOperationAction(ISD::FMA  , MVT::f64, Legal);
168   setOperationAction(ISD::FSIN , MVT::f32, Expand);
169   setOperationAction(ISD::FCOS , MVT::f32, Expand);
170   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171   setOperationAction(ISD::FREM , MVT::f32, Expand);
172   setOperationAction(ISD::FPOW , MVT::f32, Expand);
173   setOperationAction(ISD::FMA  , MVT::f32, Legal);
174
175   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
176
177   // If we're enabling GP optimizations, use hardware square root
178   if (!Subtarget.hasFSQRT() &&
179       !(TM.Options.UnsafeFPMath &&
180         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget.hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath &&
185         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
186     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
187
188   if (Subtarget.hasFCPSGN()) {
189     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
191   } else {
192     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
194   }
195
196   if (Subtarget.hasFPRND()) {
197     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
199     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200     setOperationAction(ISD::FROUND, MVT::f64, Legal);
201
202     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
204     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205     setOperationAction(ISD::FROUND, MVT::f32, Legal);
206   }
207
208   // PowerPC does not have BSWAP, CTPOP or CTTZ
209   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
210   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
214   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
217
218   if (Subtarget.hasPOPCNTD()) {
219     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
220     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
221   } else {
222     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
223     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
224   }
225
226   // PowerPC does not have ROTR
227   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
228   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
229
230   if (!Subtarget.useCRBits()) {
231     // PowerPC does not have Select
232     setOperationAction(ISD::SELECT, MVT::i32, Expand);
233     setOperationAction(ISD::SELECT, MVT::i64, Expand);
234     setOperationAction(ISD::SELECT, MVT::f32, Expand);
235     setOperationAction(ISD::SELECT, MVT::f64, Expand);
236   }
237
238   // PowerPC wants to turn select_cc of FP into fsel when possible.
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
241
242   // PowerPC wants to optimize integer setcc a bit
243   if (!Subtarget.useCRBits())
244     setOperationAction(ISD::SETCC, MVT::i32, Custom);
245
246   // PowerPC does not have BRCOND which requires SetCC
247   if (!Subtarget.useCRBits())
248     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
249
250   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
251
252   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254
255   // PowerPC does not have [U|S]INT_TO_FP
256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
258
259   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
263
264   // We cannot sextinreg(i1).  Expand to shifts.
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
266
267   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269   // support continuation, user-level threading, and etc.. As a result, no
270   // other SjLj exception interfaces are implemented and please don't build
271   // your own exception handling based on them.
272   // LLVM/Clang supports zero-cost DWARF exception handling.
273   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
275
276   // We want to legalize GlobalAddress and ConstantPool nodes into the
277   // appropriate instructions to materialize the address.
278   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
281   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
282   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
283   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
286   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
287   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
288
289   // TRAP is legal.
290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
291
292   // TRAMPOLINE is custom lowered.
293   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
295
296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
298
299   if (Subtarget.isSVR4ABI()) {
300     if (isPPC64) {
301       // VAARG always uses double-word chunks, so promote anything smaller.
302       setOperationAction(ISD::VAARG, MVT::i1, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::i8, Promote);
305       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306       setOperationAction(ISD::VAARG, MVT::i16, Promote);
307       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308       setOperationAction(ISD::VAARG, MVT::i32, Promote);
309       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310       setOperationAction(ISD::VAARG, MVT::Other, Expand);
311     } else {
312       // VAARG is custom lowered with the 32-bit SVR4 ABI.
313       setOperationAction(ISD::VAARG, MVT::Other, Custom);
314       setOperationAction(ISD::VAARG, MVT::i64, Custom);
315     }
316   } else
317     setOperationAction(ISD::VAARG, MVT::Other, Expand);
318
319   if (Subtarget.isSVR4ABI() && !isPPC64)
320     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
322   else
323     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
324
325   // Use the default implementation.
326   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
327   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
328   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
329   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
331
332   // We want to custom lower some of our intrinsics.
333   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
334
335   // To handle counter-based loop conditions.
336   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
337
338   // Comparisons that require checking two conditions.
339   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
351
352   if (Subtarget.has64BitSupport()) {
353     // They also have instructions for converting between i64 and fp.
354     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358     // This is just the low 32 bits of a (signed) fp->i64 conversion.
359     // We cannot do this with Promote because i64 is not a legal type.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
361
362     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
364   } else {
365     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
367   }
368
369   // With the instructions enabled under FPCVT, we can do everything.
370   if (Subtarget.hasFPCVT()) {
371     if (Subtarget.has64BitSupport()) {
372       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
376     }
377
378     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
382   }
383
384   if (Subtarget.use64BitRegs()) {
385     // 64-bit PowerPC implementations can support i64 types directly
386     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389     // 64-bit PowerPC wants to expand i128 shifts itself.
390     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
393   } else {
394     // 32-bit PowerPC wants to expand i64 shifts itself.
395     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
398   }
399
400   if (Subtarget.hasAltivec()) {
401     // First set operation action for all vector types to expand. Then we
402     // will selectively turn on ones that can be effectively codegen'd.
403     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
406
407       // add/sub are legal for all supported vector VT's.
408       setOperationAction(ISD::ADD , VT, Legal);
409       setOperationAction(ISD::SUB , VT, Legal);
410
411       // We promote all shuffles to v16i8.
412       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
414
415       // We promote all non-typed operations to v4i32.
416       setOperationAction(ISD::AND   , VT, Promote);
417       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
418       setOperationAction(ISD::OR    , VT, Promote);
419       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
420       setOperationAction(ISD::XOR   , VT, Promote);
421       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
422       setOperationAction(ISD::LOAD  , VT, Promote);
423       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
424       setOperationAction(ISD::SELECT, VT, Promote);
425       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426       setOperationAction(ISD::STORE, VT, Promote);
427       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
428
429       // No other operations are legal.
430       setOperationAction(ISD::MUL , VT, Expand);
431       setOperationAction(ISD::SDIV, VT, Expand);
432       setOperationAction(ISD::SREM, VT, Expand);
433       setOperationAction(ISD::UDIV, VT, Expand);
434       setOperationAction(ISD::UREM, VT, Expand);
435       setOperationAction(ISD::FDIV, VT, Expand);
436       setOperationAction(ISD::FREM, VT, Expand);
437       setOperationAction(ISD::FNEG, VT, Expand);
438       setOperationAction(ISD::FSQRT, VT, Expand);
439       setOperationAction(ISD::FLOG, VT, Expand);
440       setOperationAction(ISD::FLOG10, VT, Expand);
441       setOperationAction(ISD::FLOG2, VT, Expand);
442       setOperationAction(ISD::FEXP, VT, Expand);
443       setOperationAction(ISD::FEXP2, VT, Expand);
444       setOperationAction(ISD::FSIN, VT, Expand);
445       setOperationAction(ISD::FCOS, VT, Expand);
446       setOperationAction(ISD::FABS, VT, Expand);
447       setOperationAction(ISD::FPOWI, VT, Expand);
448       setOperationAction(ISD::FFLOOR, VT, Expand);
449       setOperationAction(ISD::FCEIL,  VT, Expand);
450       setOperationAction(ISD::FTRUNC, VT, Expand);
451       setOperationAction(ISD::FRINT,  VT, Expand);
452       setOperationAction(ISD::FNEARBYINT, VT, Expand);
453       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458       setOperationAction(ISD::UDIVREM, VT, Expand);
459       setOperationAction(ISD::SDIVREM, VT, Expand);
460       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461       setOperationAction(ISD::FPOW, VT, Expand);
462       setOperationAction(ISD::BSWAP, VT, Expand);
463       setOperationAction(ISD::CTPOP, VT, Expand);
464       setOperationAction(ISD::CTLZ, VT, Expand);
465       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
466       setOperationAction(ISD::CTTZ, VT, Expand);
467       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
468       setOperationAction(ISD::VSELECT, VT, Expand);
469       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
470
471       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
472            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
473         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
474         setTruncStoreAction(VT, InnerVT, Expand);
475       }
476       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
477       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
478       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
479     }
480
481     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
482     // with merges, splats, etc.
483     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
484
485     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
486     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
487     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
488     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
489     setOperationAction(ISD::SELECT, MVT::v4i32,
490                        Subtarget.useCRBits() ? Legal : Expand);
491     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
492     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
493     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
494     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
495     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
497     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
498     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
499     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
500
501     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
502     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
503     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
504     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
505
506     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
507     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
508
509     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
510       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
511       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
512     }
513
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
517
518     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
519     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
520
521     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
522     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
523     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
524     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
525
526     // Altivec does not contain unordered floating-point compare instructions
527     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
528     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
529     setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
530     setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
531     setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
532     setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
533
534     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
535     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
536
537     if (Subtarget.hasVSX()) {
538       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
540
541       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
542       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
543       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
544       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
545       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
546
547       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
548
549       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
550       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
551
552       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
553       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
554
555       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
556       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
557       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
558       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
559       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
560
561       // Share the Altivec comparison restrictions.
562       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
563       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
564       setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
565       setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
566       setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
567       setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
568
569       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
570       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
571
572       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
573       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
574
575       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
576
577       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
578
579       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
580       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
581
582       // VSX v2i64 only supports non-arithmetic operations.
583       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
584       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
585
586       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
587       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
588       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
589
590       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
591
592       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
593       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
594       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
595       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
596
597       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
598
599       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
600       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
601       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
602       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
603
604       // Vector operation legalization checks the result type of
605       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
606       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
607       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
608       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
609       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
610
611       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
612     }
613   }
614
615   if (Subtarget.has64BitSupport()) {
616     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
617     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
618   }
619
620   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
621   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
622   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
623   setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
624
625   setBooleanContents(ZeroOrOneBooleanContent);
626   // Altivec instructions set fields to all zeros or all ones.
627   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
628
629   if (!isPPC64) {
630     // These libcalls are not available in 32-bit.
631     setLibcallName(RTLIB::SHL_I128, nullptr);
632     setLibcallName(RTLIB::SRL_I128, nullptr);
633     setLibcallName(RTLIB::SRA_I128, nullptr);
634   }
635
636   if (isPPC64) {
637     setStackPointerRegisterToSaveRestore(PPC::X1);
638     setExceptionPointerRegister(PPC::X3);
639     setExceptionSelectorRegister(PPC::X4);
640   } else {
641     setStackPointerRegisterToSaveRestore(PPC::R1);
642     setExceptionPointerRegister(PPC::R3);
643     setExceptionSelectorRegister(PPC::R4);
644   }
645
646   // We have target-specific dag combine patterns for the following nodes:
647   setTargetDAGCombine(ISD::SINT_TO_FP);
648   setTargetDAGCombine(ISD::LOAD);
649   setTargetDAGCombine(ISD::STORE);
650   setTargetDAGCombine(ISD::BR_CC);
651   if (Subtarget.useCRBits())
652     setTargetDAGCombine(ISD::BRCOND);
653   setTargetDAGCombine(ISD::BSWAP);
654   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
655
656   setTargetDAGCombine(ISD::SIGN_EXTEND);
657   setTargetDAGCombine(ISD::ZERO_EXTEND);
658   setTargetDAGCombine(ISD::ANY_EXTEND);
659
660   if (Subtarget.useCRBits()) {
661     setTargetDAGCombine(ISD::TRUNCATE);
662     setTargetDAGCombine(ISD::SETCC);
663     setTargetDAGCombine(ISD::SELECT_CC);
664   }
665
666   // Use reciprocal estimates.
667   if (TM.Options.UnsafeFPMath) {
668     setTargetDAGCombine(ISD::FDIV);
669     setTargetDAGCombine(ISD::FSQRT);
670   }
671
672   // Darwin long double math library functions have $LDBL128 appended.
673   if (Subtarget.isDarwin()) {
674     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
675     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
676     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
677     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
678     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
679     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
680     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
681     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
682     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
683     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
684   }
685
686   // With 32 condition bits, we don't need to sink (and duplicate) compares
687   // aggressively in CodeGenPrep.
688   if (Subtarget.useCRBits())
689     setHasMultipleConditionRegisters();
690
691   setMinFunctionAlignment(2);
692   if (Subtarget.isDarwin())
693     setPrefFunctionAlignment(4);
694
695   if (isPPC64 && Subtarget.isJITCodeModel())
696     // Temporary workaround for the inability of PPC64 JIT to handle jump
697     // tables.
698     setSupportJumpTables(false);
699
700   setInsertFencesForAtomic(true);
701
702   if (Subtarget.enableMachineScheduler())
703     setSchedulingPreference(Sched::Source);
704   else
705     setSchedulingPreference(Sched::Hybrid);
706
707   computeRegisterProperties();
708
709   // The Freescale cores does better with aggressive inlining of memcpy and
710   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
711   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
712       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
713     MaxStoresPerMemset = 32;
714     MaxStoresPerMemsetOptSize = 16;
715     MaxStoresPerMemcpy = 32;
716     MaxStoresPerMemcpyOptSize = 8;
717     MaxStoresPerMemmove = 32;
718     MaxStoresPerMemmoveOptSize = 8;
719
720     setPrefFunctionAlignment(4);
721   }
722 }
723
724 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
725 /// the desired ByVal argument alignment.
726 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
727                              unsigned MaxMaxAlign) {
728   if (MaxAlign == MaxMaxAlign)
729     return;
730   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
731     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
732       MaxAlign = 32;
733     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
734       MaxAlign = 16;
735   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
736     unsigned EltAlign = 0;
737     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
738     if (EltAlign > MaxAlign)
739       MaxAlign = EltAlign;
740   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
741     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
742       unsigned EltAlign = 0;
743       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
744       if (EltAlign > MaxAlign)
745         MaxAlign = EltAlign;
746       if (MaxAlign == MaxMaxAlign)
747         break;
748     }
749   }
750 }
751
752 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
753 /// function arguments in the caller parameter area.
754 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
755   // Darwin passes everything on 4 byte boundary.
756   if (Subtarget.isDarwin())
757     return 4;
758
759   // 16byte and wider vectors are passed on 16byte boundary.
760   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
761   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
762   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
763     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
764   return Align;
765 }
766
767 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
768   switch (Opcode) {
769   default: return nullptr;
770   case PPCISD::FSEL:            return "PPCISD::FSEL";
771   case PPCISD::FCFID:           return "PPCISD::FCFID";
772   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
773   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
774   case PPCISD::FRE:             return "PPCISD::FRE";
775   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
776   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
777   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
778   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
779   case PPCISD::VPERM:           return "PPCISD::VPERM";
780   case PPCISD::Hi:              return "PPCISD::Hi";
781   case PPCISD::Lo:              return "PPCISD::Lo";
782   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
783   case PPCISD::LOAD:            return "PPCISD::LOAD";
784   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
785   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
786   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
787   case PPCISD::SRL:             return "PPCISD::SRL";
788   case PPCISD::SRA:             return "PPCISD::SRA";
789   case PPCISD::SHL:             return "PPCISD::SHL";
790   case PPCISD::CALL:            return "PPCISD::CALL";
791   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
792   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
793   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
794   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
795   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
796   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
797   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
798   case PPCISD::VCMP:            return "PPCISD::VCMP";
799   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
800   case PPCISD::LBRX:            return "PPCISD::LBRX";
801   case PPCISD::STBRX:           return "PPCISD::STBRX";
802   case PPCISD::LARX:            return "PPCISD::LARX";
803   case PPCISD::STCX:            return "PPCISD::STCX";
804   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
805   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
806   case PPCISD::BDZ:             return "PPCISD::BDZ";
807   case PPCISD::MFFS:            return "PPCISD::MFFS";
808   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
809   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
810   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
811   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
812   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
813   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
814   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
815   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
816   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
817   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
818   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
819   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
820   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
821   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
822   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
823   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
824   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
825   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
826   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
827   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
828   case PPCISD::SC:              return "PPCISD::SC";
829   }
830 }
831
832 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
833   if (!VT.isVector())
834     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
835   return VT.changeVectorElementTypeToInteger();
836 }
837
838 //===----------------------------------------------------------------------===//
839 // Node matching predicates, for use by the tblgen matching code.
840 //===----------------------------------------------------------------------===//
841
842 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
843 static bool isFloatingPointZero(SDValue Op) {
844   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
845     return CFP->getValueAPF().isZero();
846   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
847     // Maybe this has already been legalized into the constant pool?
848     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
849       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
850         return CFP->getValueAPF().isZero();
851   }
852   return false;
853 }
854
855 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
856 /// true if Op is undef or if it matches the specified value.
857 static bool isConstantOrUndef(int Op, int Val) {
858   return Op < 0 || Op == Val;
859 }
860
861 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
862 /// VPKUHUM instruction.
863 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
864                                SelectionDAG &DAG) {
865   unsigned j = DAG.getTarget().getDataLayout()->isLittleEndian() ? 0 : 1;
866   if (!isUnary) {
867     for (unsigned i = 0; i != 16; ++i)
868       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+j))
869         return false;
870   } else {
871     for (unsigned i = 0; i != 8; ++i)
872       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
873           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
874         return false;
875   }
876   return true;
877 }
878
879 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
880 /// VPKUWUM instruction.
881 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
882                                SelectionDAG &DAG) {
883   unsigned j, k;
884   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
885     j = 0;
886     k = 1;
887   } else {
888     j = 2;
889     k = 3;
890   }
891   if (!isUnary) {
892     for (unsigned i = 0; i != 16; i += 2)
893       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
894           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k))
895         return false;
896   } else {
897     for (unsigned i = 0; i != 8; i += 2)
898       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
899           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k) ||
900           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j) ||
901           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+k))
902         return false;
903   }
904   return true;
905 }
906
907 /// isVMerge - Common function, used to match vmrg* shuffles.
908 ///
909 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
910                      unsigned LHSStart, unsigned RHSStart) {
911   if (N->getValueType(0) != MVT::v16i8)
912     return false;
913   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
914          "Unsupported merge size!");
915
916   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
917     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
918       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
919                              LHSStart+j+i*UnitSize) ||
920           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
921                              RHSStart+j+i*UnitSize))
922         return false;
923     }
924   return true;
925 }
926
927 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
928 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
929 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
930                              bool isUnary, SelectionDAG &DAG) {
931   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
932     if (!isUnary)
933       return isVMerge(N, UnitSize, 0, 16);
934     return isVMerge(N, UnitSize, 0, 0);
935   } else {
936     if (!isUnary)
937       return isVMerge(N, UnitSize, 8, 24);
938     return isVMerge(N, UnitSize, 8, 8);
939   }
940 }
941
942 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
943 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
944 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
945                              bool isUnary, SelectionDAG &DAG) {
946   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
947     if (!isUnary)
948       return isVMerge(N, UnitSize, 8, 24);
949     return isVMerge(N, UnitSize, 8, 8);
950   } else {
951     if (!isUnary)
952       return isVMerge(N, UnitSize, 0, 16);
953     return isVMerge(N, UnitSize, 0, 0);
954   }
955 }
956
957
958 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
959 /// amount, otherwise return -1.
960 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary, SelectionDAG &DAG) {
961   if (N->getValueType(0) != MVT::v16i8)
962     return -1;
963
964   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
965
966   // Find the first non-undef value in the shuffle mask.
967   unsigned i;
968   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
969     /*search*/;
970
971   if (i == 16) return -1;  // all undef.
972
973   // Otherwise, check to see if the rest of the elements are consecutively
974   // numbered from this value.
975   unsigned ShiftAmt = SVOp->getMaskElt(i);
976   if (ShiftAmt < i) return -1;
977
978   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
979
980     ShiftAmt += i;
981
982     if (!isUnary) {
983       // Check the rest of the elements to see if they are consecutive.
984       for (++i; i != 16; ++i)
985         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt - i))
986           return -1;
987     } else {
988       // Check the rest of the elements to see if they are consecutive.
989       for (++i; i != 16; ++i)
990         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt - i) & 15))
991           return -1;
992     }
993
994   } else {  // Big Endian
995
996     ShiftAmt -= i;
997
998     if (!isUnary) {
999       // Check the rest of the elements to see if they are consecutive.
1000       for (++i; i != 16; ++i)
1001         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1002           return -1;
1003     } else {
1004       // Check the rest of the elements to see if they are consecutive.
1005       for (++i; i != 16; ++i)
1006         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1007           return -1;
1008     }
1009   }
1010   return ShiftAmt;
1011 }
1012
1013 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1014 /// specifies a splat of a single element that is suitable for input to
1015 /// VSPLTB/VSPLTH/VSPLTW.
1016 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1017   assert(N->getValueType(0) == MVT::v16i8 &&
1018          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1019
1020   // This is a splat operation if each element of the permute is the same, and
1021   // if the value doesn't reference the second vector.
1022   unsigned ElementBase = N->getMaskElt(0);
1023
1024   // FIXME: Handle UNDEF elements too!
1025   if (ElementBase >= 16)
1026     return false;
1027
1028   // Check that the indices are consecutive, in the case of a multi-byte element
1029   // splatted with a v16i8 mask.
1030   for (unsigned i = 1; i != EltSize; ++i)
1031     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1032       return false;
1033
1034   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1035     if (N->getMaskElt(i) < 0) continue;
1036     for (unsigned j = 0; j != EltSize; ++j)
1037       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1038         return false;
1039   }
1040   return true;
1041 }
1042
1043 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1044 /// are -0.0.
1045 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1046   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1047
1048   APInt APVal, APUndef;
1049   unsigned BitSize;
1050   bool HasAnyUndefs;
1051
1052   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1053     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1054       return CFP->getValueAPF().isNegZero();
1055
1056   return false;
1057 }
1058
1059 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1060 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1061 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1062                                 SelectionDAG &DAG) {
1063   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1064   assert(isSplatShuffleMask(SVOp, EltSize));
1065   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1066     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1067   else
1068     return SVOp->getMaskElt(0) / EltSize;
1069 }
1070
1071 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1072 /// by using a vspltis[bhw] instruction of the specified element size, return
1073 /// the constant being splatted.  The ByteSize field indicates the number of
1074 /// bytes of each element [124] -> [bhw].
1075 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1076   SDValue OpVal(nullptr, 0);
1077
1078   // If ByteSize of the splat is bigger than the element size of the
1079   // build_vector, then we have a case where we are checking for a splat where
1080   // multiple elements of the buildvector are folded together into a single
1081   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1082   unsigned EltSize = 16/N->getNumOperands();
1083   if (EltSize < ByteSize) {
1084     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1085     SDValue UniquedVals[4];
1086     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1087
1088     // See if all of the elements in the buildvector agree across.
1089     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1090       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1091       // If the element isn't a constant, bail fully out.
1092       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1093
1094
1095       if (!UniquedVals[i&(Multiple-1)].getNode())
1096         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1097       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1098         return SDValue();  // no match.
1099     }
1100
1101     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1102     // either constant or undef values that are identical for each chunk.  See
1103     // if these chunks can form into a larger vspltis*.
1104
1105     // Check to see if all of the leading entries are either 0 or -1.  If
1106     // neither, then this won't fit into the immediate field.
1107     bool LeadingZero = true;
1108     bool LeadingOnes = true;
1109     for (unsigned i = 0; i != Multiple-1; ++i) {
1110       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1111
1112       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1113       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1114     }
1115     // Finally, check the least significant entry.
1116     if (LeadingZero) {
1117       if (!UniquedVals[Multiple-1].getNode())
1118         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1119       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1120       if (Val < 16)
1121         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1122     }
1123     if (LeadingOnes) {
1124       if (!UniquedVals[Multiple-1].getNode())
1125         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1126       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1127       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1128         return DAG.getTargetConstant(Val, MVT::i32);
1129     }
1130
1131     return SDValue();
1132   }
1133
1134   // Check to see if this buildvec has a single non-undef value in its elements.
1135   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1136     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1137     if (!OpVal.getNode())
1138       OpVal = N->getOperand(i);
1139     else if (OpVal != N->getOperand(i))
1140       return SDValue();
1141   }
1142
1143   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1144
1145   unsigned ValSizeInBytes = EltSize;
1146   uint64_t Value = 0;
1147   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1148     Value = CN->getZExtValue();
1149   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1150     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1151     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1152   }
1153
1154   // If the splat value is larger than the element value, then we can never do
1155   // this splat.  The only case that we could fit the replicated bits into our
1156   // immediate field for would be zero, and we prefer to use vxor for it.
1157   if (ValSizeInBytes < ByteSize) return SDValue();
1158
1159   // If the element value is larger than the splat value, cut it in half and
1160   // check to see if the two halves are equal.  Continue doing this until we
1161   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1162   while (ValSizeInBytes > ByteSize) {
1163     ValSizeInBytes >>= 1;
1164
1165     // If the top half equals the bottom half, we're still ok.
1166     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1167          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1168       return SDValue();
1169   }
1170
1171   // Properly sign extend the value.
1172   int MaskVal = SignExtend32(Value, ByteSize * 8);
1173
1174   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1175   if (MaskVal == 0) return SDValue();
1176
1177   // Finally, if this value fits in a 5 bit sext field, return it
1178   if (SignExtend32<5>(MaskVal) == MaskVal)
1179     return DAG.getTargetConstant(MaskVal, MVT::i32);
1180   return SDValue();
1181 }
1182
1183 //===----------------------------------------------------------------------===//
1184 //  Addressing Mode Selection
1185 //===----------------------------------------------------------------------===//
1186
1187 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1188 /// or 64-bit immediate, and if the value can be accurately represented as a
1189 /// sign extension from a 16-bit value.  If so, this returns true and the
1190 /// immediate.
1191 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1192   if (!isa<ConstantSDNode>(N))
1193     return false;
1194
1195   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1196   if (N->getValueType(0) == MVT::i32)
1197     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1198   else
1199     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1200 }
1201 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1202   return isIntS16Immediate(Op.getNode(), Imm);
1203 }
1204
1205
1206 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1207 /// can be represented as an indexed [r+r] operation.  Returns false if it
1208 /// can be more efficiently represented with [r+imm].
1209 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1210                                             SDValue &Index,
1211                                             SelectionDAG &DAG) const {
1212   short imm = 0;
1213   if (N.getOpcode() == ISD::ADD) {
1214     if (isIntS16Immediate(N.getOperand(1), imm))
1215       return false;    // r+i
1216     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1217       return false;    // r+i
1218
1219     Base = N.getOperand(0);
1220     Index = N.getOperand(1);
1221     return true;
1222   } else if (N.getOpcode() == ISD::OR) {
1223     if (isIntS16Immediate(N.getOperand(1), imm))
1224       return false;    // r+i can fold it if we can.
1225
1226     // If this is an or of disjoint bitfields, we can codegen this as an add
1227     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1228     // disjoint.
1229     APInt LHSKnownZero, LHSKnownOne;
1230     APInt RHSKnownZero, RHSKnownOne;
1231     DAG.computeKnownBits(N.getOperand(0),
1232                          LHSKnownZero, LHSKnownOne);
1233
1234     if (LHSKnownZero.getBoolValue()) {
1235       DAG.computeKnownBits(N.getOperand(1),
1236                            RHSKnownZero, RHSKnownOne);
1237       // If all of the bits are known zero on the LHS or RHS, the add won't
1238       // carry.
1239       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1240         Base = N.getOperand(0);
1241         Index = N.getOperand(1);
1242         return true;
1243       }
1244     }
1245   }
1246
1247   return false;
1248 }
1249
1250 // If we happen to be doing an i64 load or store into a stack slot that has
1251 // less than a 4-byte alignment, then the frame-index elimination may need to
1252 // use an indexed load or store instruction (because the offset may not be a
1253 // multiple of 4). The extra register needed to hold the offset comes from the
1254 // register scavenger, and it is possible that the scavenger will need to use
1255 // an emergency spill slot. As a result, we need to make sure that a spill slot
1256 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1257 // stack slot.
1258 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1259   // FIXME: This does not handle the LWA case.
1260   if (VT != MVT::i64)
1261     return;
1262
1263   // NOTE: We'll exclude negative FIs here, which come from argument
1264   // lowering, because there are no known test cases triggering this problem
1265   // using packed structures (or similar). We can remove this exclusion if
1266   // we find such a test case. The reason why this is so test-case driven is
1267   // because this entire 'fixup' is only to prevent crashes (from the
1268   // register scavenger) on not-really-valid inputs. For example, if we have:
1269   //   %a = alloca i1
1270   //   %b = bitcast i1* %a to i64*
1271   //   store i64* a, i64 b
1272   // then the store should really be marked as 'align 1', but is not. If it
1273   // were marked as 'align 1' then the indexed form would have been
1274   // instruction-selected initially, and the problem this 'fixup' is preventing
1275   // won't happen regardless.
1276   if (FrameIdx < 0)
1277     return;
1278
1279   MachineFunction &MF = DAG.getMachineFunction();
1280   MachineFrameInfo *MFI = MF.getFrameInfo();
1281
1282   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1283   if (Align >= 4)
1284     return;
1285
1286   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1287   FuncInfo->setHasNonRISpills();
1288 }
1289
1290 /// Returns true if the address N can be represented by a base register plus
1291 /// a signed 16-bit displacement [r+imm], and if it is not better
1292 /// represented as reg+reg.  If Aligned is true, only accept displacements
1293 /// suitable for STD and friends, i.e. multiples of 4.
1294 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1295                                             SDValue &Base,
1296                                             SelectionDAG &DAG,
1297                                             bool Aligned) const {
1298   // FIXME dl should come from parent load or store, not from address
1299   SDLoc dl(N);
1300   // If this can be more profitably realized as r+r, fail.
1301   if (SelectAddressRegReg(N, Disp, Base, DAG))
1302     return false;
1303
1304   if (N.getOpcode() == ISD::ADD) {
1305     short imm = 0;
1306     if (isIntS16Immediate(N.getOperand(1), imm) &&
1307         (!Aligned || (imm & 3) == 0)) {
1308       Disp = DAG.getTargetConstant(imm, N.getValueType());
1309       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1310         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1311         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1312       } else {
1313         Base = N.getOperand(0);
1314       }
1315       return true; // [r+i]
1316     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1317       // Match LOAD (ADD (X, Lo(G))).
1318       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1319              && "Cannot handle constant offsets yet!");
1320       Disp = N.getOperand(1).getOperand(0);  // The global address.
1321       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1322              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1323              Disp.getOpcode() == ISD::TargetConstantPool ||
1324              Disp.getOpcode() == ISD::TargetJumpTable);
1325       Base = N.getOperand(0);
1326       return true;  // [&g+r]
1327     }
1328   } else if (N.getOpcode() == ISD::OR) {
1329     short imm = 0;
1330     if (isIntS16Immediate(N.getOperand(1), imm) &&
1331         (!Aligned || (imm & 3) == 0)) {
1332       // If this is an or of disjoint bitfields, we can codegen this as an add
1333       // (for better address arithmetic) if the LHS and RHS of the OR are
1334       // provably disjoint.
1335       APInt LHSKnownZero, LHSKnownOne;
1336       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1337
1338       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1339         // If all of the bits are known zero on the LHS or RHS, the add won't
1340         // carry.
1341         if (FrameIndexSDNode *FI =
1342               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1343           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1344           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1345         } else {
1346           Base = N.getOperand(0);
1347         }
1348         Disp = DAG.getTargetConstant(imm, N.getValueType());
1349         return true;
1350       }
1351     }
1352   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1353     // Loading from a constant address.
1354
1355     // If this address fits entirely in a 16-bit sext immediate field, codegen
1356     // this as "d, 0"
1357     short Imm;
1358     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1359       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1360       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1361                              CN->getValueType(0));
1362       return true;
1363     }
1364
1365     // Handle 32-bit sext immediates with LIS + addr mode.
1366     if ((CN->getValueType(0) == MVT::i32 ||
1367          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1368         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1369       int Addr = (int)CN->getZExtValue();
1370
1371       // Otherwise, break this down into an LIS + disp.
1372       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1373
1374       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1375       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1376       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1377       return true;
1378     }
1379   }
1380
1381   Disp = DAG.getTargetConstant(0, getPointerTy());
1382   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1383     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1384     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1385   } else
1386     Base = N;
1387   return true;      // [r+0]
1388 }
1389
1390 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1391 /// represented as an indexed [r+r] operation.
1392 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1393                                                 SDValue &Index,
1394                                                 SelectionDAG &DAG) const {
1395   // Check to see if we can easily represent this as an [r+r] address.  This
1396   // will fail if it thinks that the address is more profitably represented as
1397   // reg+imm, e.g. where imm = 0.
1398   if (SelectAddressRegReg(N, Base, Index, DAG))
1399     return true;
1400
1401   // If the operand is an addition, always emit this as [r+r], since this is
1402   // better (for code size, and execution, as the memop does the add for free)
1403   // than emitting an explicit add.
1404   if (N.getOpcode() == ISD::ADD) {
1405     Base = N.getOperand(0);
1406     Index = N.getOperand(1);
1407     return true;
1408   }
1409
1410   // Otherwise, do it the hard way, using R0 as the base register.
1411   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1412                          N.getValueType());
1413   Index = N;
1414   return true;
1415 }
1416
1417 /// getPreIndexedAddressParts - returns true by value, base pointer and
1418 /// offset pointer and addressing mode by reference if the node's address
1419 /// can be legally represented as pre-indexed load / store address.
1420 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1421                                                   SDValue &Offset,
1422                                                   ISD::MemIndexedMode &AM,
1423                                                   SelectionDAG &DAG) const {
1424   if (DisablePPCPreinc) return false;
1425
1426   bool isLoad = true;
1427   SDValue Ptr;
1428   EVT VT;
1429   unsigned Alignment;
1430   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1431     Ptr = LD->getBasePtr();
1432     VT = LD->getMemoryVT();
1433     Alignment = LD->getAlignment();
1434   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1435     Ptr = ST->getBasePtr();
1436     VT  = ST->getMemoryVT();
1437     Alignment = ST->getAlignment();
1438     isLoad = false;
1439   } else
1440     return false;
1441
1442   // PowerPC doesn't have preinc load/store instructions for vectors.
1443   if (VT.isVector())
1444     return false;
1445
1446   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1447
1448     // Common code will reject creating a pre-inc form if the base pointer
1449     // is a frame index, or if N is a store and the base pointer is either
1450     // the same as or a predecessor of the value being stored.  Check for
1451     // those situations here, and try with swapped Base/Offset instead.
1452     bool Swap = false;
1453
1454     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1455       Swap = true;
1456     else if (!isLoad) {
1457       SDValue Val = cast<StoreSDNode>(N)->getValue();
1458       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1459         Swap = true;
1460     }
1461
1462     if (Swap)
1463       std::swap(Base, Offset);
1464
1465     AM = ISD::PRE_INC;
1466     return true;
1467   }
1468
1469   // LDU/STU can only handle immediates that are a multiple of 4.
1470   if (VT != MVT::i64) {
1471     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1472       return false;
1473   } else {
1474     // LDU/STU need an address with at least 4-byte alignment.
1475     if (Alignment < 4)
1476       return false;
1477
1478     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1479       return false;
1480   }
1481
1482   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1483     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1484     // sext i32 to i64 when addr mode is r+i.
1485     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1486         LD->getExtensionType() == ISD::SEXTLOAD &&
1487         isa<ConstantSDNode>(Offset))
1488       return false;
1489   }
1490
1491   AM = ISD::PRE_INC;
1492   return true;
1493 }
1494
1495 //===----------------------------------------------------------------------===//
1496 //  LowerOperation implementation
1497 //===----------------------------------------------------------------------===//
1498
1499 /// GetLabelAccessInfo - Return true if we should reference labels using a
1500 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1501 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1502                                unsigned &LoOpFlags,
1503                                const GlobalValue *GV = nullptr) {
1504   HiOpFlags = PPCII::MO_HA;
1505   LoOpFlags = PPCII::MO_LO;
1506
1507   // Don't use the pic base if not in PIC relocation model.
1508   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1509
1510   if (isPIC) {
1511     HiOpFlags |= PPCII::MO_PIC_FLAG;
1512     LoOpFlags |= PPCII::MO_PIC_FLAG;
1513   }
1514
1515   // If this is a reference to a global value that requires a non-lazy-ptr, make
1516   // sure that instruction lowering adds it.
1517   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1518     HiOpFlags |= PPCII::MO_NLP_FLAG;
1519     LoOpFlags |= PPCII::MO_NLP_FLAG;
1520
1521     if (GV->hasHiddenVisibility()) {
1522       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1523       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1524     }
1525   }
1526
1527   return isPIC;
1528 }
1529
1530 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1531                              SelectionDAG &DAG) {
1532   EVT PtrVT = HiPart.getValueType();
1533   SDValue Zero = DAG.getConstant(0, PtrVT);
1534   SDLoc DL(HiPart);
1535
1536   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1537   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1538
1539   // With PIC, the first instruction is actually "GR+hi(&G)".
1540   if (isPIC)
1541     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1542                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1543
1544   // Generate non-pic code that has direct accesses to the constant pool.
1545   // The address of the global is just (hi(&g)+lo(&g)).
1546   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1547 }
1548
1549 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1550                                              SelectionDAG &DAG) const {
1551   EVT PtrVT = Op.getValueType();
1552   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1553   const Constant *C = CP->getConstVal();
1554
1555   // 64-bit SVR4 ABI code is always position-independent.
1556   // The actual address of the GlobalValue is stored in the TOC.
1557   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1558     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1559     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1560                        DAG.getRegister(PPC::X2, MVT::i64));
1561   }
1562
1563   unsigned MOHiFlag, MOLoFlag;
1564   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1565
1566   if (isPIC && Subtarget.isSVR4ABI()) {
1567     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1568                                            PPCII::MO_PIC_FLAG);
1569     SDLoc DL(CP);
1570     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1571                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1572   }
1573
1574   SDValue CPIHi =
1575     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1576   SDValue CPILo =
1577     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1578   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1579 }
1580
1581 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1582   EVT PtrVT = Op.getValueType();
1583   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1584
1585   // 64-bit SVR4 ABI code is always position-independent.
1586   // The actual address of the GlobalValue is stored in the TOC.
1587   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1588     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1589     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1590                        DAG.getRegister(PPC::X2, MVT::i64));
1591   }
1592
1593   unsigned MOHiFlag, MOLoFlag;
1594   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1595
1596   if (isPIC && Subtarget.isSVR4ABI()) {
1597     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1598                                         PPCII::MO_PIC_FLAG);
1599     SDLoc DL(GA);
1600     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1601                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1602   }
1603
1604   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1605   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1606   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1607 }
1608
1609 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1610                                              SelectionDAG &DAG) const {
1611   EVT PtrVT = Op.getValueType();
1612
1613   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1614
1615   unsigned MOHiFlag, MOLoFlag;
1616   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1617   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1618   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1619   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1620 }
1621
1622 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1623                                               SelectionDAG &DAG) const {
1624
1625   // FIXME: TLS addresses currently use medium model code sequences,
1626   // which is the most useful form.  Eventually support for small and
1627   // large models could be added if users need it, at the cost of
1628   // additional complexity.
1629   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1630   SDLoc dl(GA);
1631   const GlobalValue *GV = GA->getGlobal();
1632   EVT PtrVT = getPointerTy();
1633   bool is64bit = Subtarget.isPPC64();
1634
1635   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1636
1637   if (Model == TLSModel::LocalExec) {
1638     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1639                                                PPCII::MO_TPREL_HA);
1640     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1641                                                PPCII::MO_TPREL_LO);
1642     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1643                                      is64bit ? MVT::i64 : MVT::i32);
1644     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1645     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1646   }
1647
1648   if (Model == TLSModel::InitialExec) {
1649     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1650     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1651                                                 PPCII::MO_TLS);
1652     SDValue GOTPtr;
1653     if (is64bit) {
1654       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1655       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1656                            PtrVT, GOTReg, TGA);
1657     } else
1658       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1659     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1660                                    PtrVT, TGA, GOTPtr);
1661     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1662   }
1663
1664   if (Model == TLSModel::GeneralDynamic) {
1665     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1666     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1667     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1668                                      GOTReg, TGA);
1669     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1670                                    GOTEntryHi, TGA);
1671
1672     // We need a chain node, and don't have one handy.  The underlying
1673     // call has no side effects, so using the function entry node
1674     // suffices.
1675     SDValue Chain = DAG.getEntryNode();
1676     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1677     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1678     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1679                                   PtrVT, ParmReg, TGA);
1680     // The return value from GET_TLS_ADDR really is in X3 already, but
1681     // some hacks are needed here to tie everything together.  The extra
1682     // copies dissolve during subsequent transforms.
1683     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1684     return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1685   }
1686
1687   if (Model == TLSModel::LocalDynamic) {
1688     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1689     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1690     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1691                                      GOTReg, TGA);
1692     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1693                                    GOTEntryHi, TGA);
1694
1695     // We need a chain node, and don't have one handy.  The underlying
1696     // call has no side effects, so using the function entry node
1697     // suffices.
1698     SDValue Chain = DAG.getEntryNode();
1699     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1700     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1701     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1702                                   PtrVT, ParmReg, TGA);
1703     // The return value from GET_TLSLD_ADDR really is in X3 already, but
1704     // some hacks are needed here to tie everything together.  The extra
1705     // copies dissolve during subsequent transforms.
1706     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1707     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1708                                       Chain, ParmReg, TGA);
1709     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1710   }
1711
1712   llvm_unreachable("Unknown TLS model!");
1713 }
1714
1715 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1716                                               SelectionDAG &DAG) const {
1717   EVT PtrVT = Op.getValueType();
1718   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1719   SDLoc DL(GSDN);
1720   const GlobalValue *GV = GSDN->getGlobal();
1721
1722   // 64-bit SVR4 ABI code is always position-independent.
1723   // The actual address of the GlobalValue is stored in the TOC.
1724   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1725     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1726     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1727                        DAG.getRegister(PPC::X2, MVT::i64));
1728   }
1729
1730   unsigned MOHiFlag, MOLoFlag;
1731   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1732
1733   if (isPIC && Subtarget.isSVR4ABI()) {
1734     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1735                                             GSDN->getOffset(),
1736                                             PPCII::MO_PIC_FLAG);
1737     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1738                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1739   }
1740
1741   SDValue GAHi =
1742     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1743   SDValue GALo =
1744     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1745
1746   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1747
1748   // If the global reference is actually to a non-lazy-pointer, we have to do an
1749   // extra load to get the address of the global.
1750   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1751     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1752                       false, false, false, 0);
1753   return Ptr;
1754 }
1755
1756 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1757   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1758   SDLoc dl(Op);
1759
1760   if (Op.getValueType() == MVT::v2i64) {
1761     // When the operands themselves are v2i64 values, we need to do something
1762     // special because VSX has no underlying comparison operations for these.
1763     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1764       // Equality can be handled by casting to the legal type for Altivec
1765       // comparisons, everything else needs to be expanded.
1766       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1767         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1768                  DAG.getSetCC(dl, MVT::v4i32,
1769                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1770                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1771                    CC));
1772       }
1773
1774       return SDValue();
1775     }
1776
1777     // We handle most of these in the usual way.
1778     return Op;
1779   }
1780
1781   // If we're comparing for equality to zero, expose the fact that this is
1782   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1783   // fold the new nodes.
1784   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1785     if (C->isNullValue() && CC == ISD::SETEQ) {
1786       EVT VT = Op.getOperand(0).getValueType();
1787       SDValue Zext = Op.getOperand(0);
1788       if (VT.bitsLT(MVT::i32)) {
1789         VT = MVT::i32;
1790         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1791       }
1792       unsigned Log2b = Log2_32(VT.getSizeInBits());
1793       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1794       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1795                                 DAG.getConstant(Log2b, MVT::i32));
1796       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1797     }
1798     // Leave comparisons against 0 and -1 alone for now, since they're usually
1799     // optimized.  FIXME: revisit this when we can custom lower all setcc
1800     // optimizations.
1801     if (C->isAllOnesValue() || C->isNullValue())
1802       return SDValue();
1803   }
1804
1805   // If we have an integer seteq/setne, turn it into a compare against zero
1806   // by xor'ing the rhs with the lhs, which is faster than setting a
1807   // condition register, reading it back out, and masking the correct bit.  The
1808   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1809   // the result to other bit-twiddling opportunities.
1810   EVT LHSVT = Op.getOperand(0).getValueType();
1811   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1812     EVT VT = Op.getValueType();
1813     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1814                                 Op.getOperand(1));
1815     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1816   }
1817   return SDValue();
1818 }
1819
1820 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1821                                       const PPCSubtarget &Subtarget) const {
1822   SDNode *Node = Op.getNode();
1823   EVT VT = Node->getValueType(0);
1824   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1825   SDValue InChain = Node->getOperand(0);
1826   SDValue VAListPtr = Node->getOperand(1);
1827   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1828   SDLoc dl(Node);
1829
1830   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1831
1832   // gpr_index
1833   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1834                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1835                                     false, false, 0);
1836   InChain = GprIndex.getValue(1);
1837
1838   if (VT == MVT::i64) {
1839     // Check if GprIndex is even
1840     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1841                                  DAG.getConstant(1, MVT::i32));
1842     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1843                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1844     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1845                                           DAG.getConstant(1, MVT::i32));
1846     // Align GprIndex to be even if it isn't
1847     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1848                            GprIndex);
1849   }
1850
1851   // fpr index is 1 byte after gpr
1852   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1853                                DAG.getConstant(1, MVT::i32));
1854
1855   // fpr
1856   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1857                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1858                                     false, false, 0);
1859   InChain = FprIndex.getValue(1);
1860
1861   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1862                                        DAG.getConstant(8, MVT::i32));
1863
1864   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1865                                         DAG.getConstant(4, MVT::i32));
1866
1867   // areas
1868   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1869                                      MachinePointerInfo(), false, false,
1870                                      false, 0);
1871   InChain = OverflowArea.getValue(1);
1872
1873   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1874                                     MachinePointerInfo(), false, false,
1875                                     false, 0);
1876   InChain = RegSaveArea.getValue(1);
1877
1878   // select overflow_area if index > 8
1879   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1880                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1881
1882   // adjustment constant gpr_index * 4/8
1883   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1884                                     VT.isInteger() ? GprIndex : FprIndex,
1885                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1886                                                     MVT::i32));
1887
1888   // OurReg = RegSaveArea + RegConstant
1889   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1890                                RegConstant);
1891
1892   // Floating types are 32 bytes into RegSaveArea
1893   if (VT.isFloatingPoint())
1894     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1895                          DAG.getConstant(32, MVT::i32));
1896
1897   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1898   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1899                                    VT.isInteger() ? GprIndex : FprIndex,
1900                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1901                                                    MVT::i32));
1902
1903   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1904                               VT.isInteger() ? VAListPtr : FprPtr,
1905                               MachinePointerInfo(SV),
1906                               MVT::i8, false, false, 0);
1907
1908   // determine if we should load from reg_save_area or overflow_area
1909   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1910
1911   // increase overflow_area by 4/8 if gpr/fpr > 8
1912   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1913                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1914                                           MVT::i32));
1915
1916   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1917                              OverflowAreaPlusN);
1918
1919   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1920                               OverflowAreaPtr,
1921                               MachinePointerInfo(),
1922                               MVT::i32, false, false, 0);
1923
1924   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1925                      false, false, false, 0);
1926 }
1927
1928 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1929                                        const PPCSubtarget &Subtarget) const {
1930   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1931
1932   // We have to copy the entire va_list struct:
1933   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1934   return DAG.getMemcpy(Op.getOperand(0), Op,
1935                        Op.getOperand(1), Op.getOperand(2),
1936                        DAG.getConstant(12, MVT::i32), 8, false, true,
1937                        MachinePointerInfo(), MachinePointerInfo());
1938 }
1939
1940 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1941                                                   SelectionDAG &DAG) const {
1942   return Op.getOperand(0);
1943 }
1944
1945 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1946                                                 SelectionDAG &DAG) const {
1947   SDValue Chain = Op.getOperand(0);
1948   SDValue Trmp = Op.getOperand(1); // trampoline
1949   SDValue FPtr = Op.getOperand(2); // nested function
1950   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1951   SDLoc dl(Op);
1952
1953   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1954   bool isPPC64 = (PtrVT == MVT::i64);
1955   Type *IntPtrTy =
1956     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1957                                                              *DAG.getContext());
1958
1959   TargetLowering::ArgListTy Args;
1960   TargetLowering::ArgListEntry Entry;
1961
1962   Entry.Ty = IntPtrTy;
1963   Entry.Node = Trmp; Args.push_back(Entry);
1964
1965   // TrampSize == (isPPC64 ? 48 : 40);
1966   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1967                                isPPC64 ? MVT::i64 : MVT::i32);
1968   Args.push_back(Entry);
1969
1970   Entry.Node = FPtr; Args.push_back(Entry);
1971   Entry.Node = Nest; Args.push_back(Entry);
1972
1973   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1974   TargetLowering::CallLoweringInfo CLI(DAG);
1975   CLI.setDebugLoc(dl).setChain(Chain)
1976     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
1977                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1978                std::move(Args), 0);
1979
1980   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1981   return CallResult.second;
1982 }
1983
1984 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1985                                         const PPCSubtarget &Subtarget) const {
1986   MachineFunction &MF = DAG.getMachineFunction();
1987   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1988
1989   SDLoc dl(Op);
1990
1991   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1992     // vastart just stores the address of the VarArgsFrameIndex slot into the
1993     // memory location argument.
1994     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1995     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1996     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1997     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1998                         MachinePointerInfo(SV),
1999                         false, false, 0);
2000   }
2001
2002   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2003   // We suppose the given va_list is already allocated.
2004   //
2005   // typedef struct {
2006   //  char gpr;     /* index into the array of 8 GPRs
2007   //                 * stored in the register save area
2008   //                 * gpr=0 corresponds to r3,
2009   //                 * gpr=1 to r4, etc.
2010   //                 */
2011   //  char fpr;     /* index into the array of 8 FPRs
2012   //                 * stored in the register save area
2013   //                 * fpr=0 corresponds to f1,
2014   //                 * fpr=1 to f2, etc.
2015   //                 */
2016   //  char *overflow_arg_area;
2017   //                /* location on stack that holds
2018   //                 * the next overflow argument
2019   //                 */
2020   //  char *reg_save_area;
2021   //               /* where r3:r10 and f1:f8 (if saved)
2022   //                * are stored
2023   //                */
2024   // } va_list[1];
2025
2026
2027   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2028   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2029
2030
2031   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2032
2033   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2034                                             PtrVT);
2035   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2036                                  PtrVT);
2037
2038   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2039   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2040
2041   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2042   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2043
2044   uint64_t FPROffset = 1;
2045   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2046
2047   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2048
2049   // Store first byte : number of int regs
2050   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2051                                          Op.getOperand(1),
2052                                          MachinePointerInfo(SV),
2053                                          MVT::i8, false, false, 0);
2054   uint64_t nextOffset = FPROffset;
2055   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2056                                   ConstFPROffset);
2057
2058   // Store second byte : number of float regs
2059   SDValue secondStore =
2060     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2061                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2062                       false, false, 0);
2063   nextOffset += StackOffset;
2064   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2065
2066   // Store second word : arguments given on stack
2067   SDValue thirdStore =
2068     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2069                  MachinePointerInfo(SV, nextOffset),
2070                  false, false, 0);
2071   nextOffset += FrameOffset;
2072   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2073
2074   // Store third word : arguments given in registers
2075   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2076                       MachinePointerInfo(SV, nextOffset),
2077                       false, false, 0);
2078
2079 }
2080
2081 #include "PPCGenCallingConv.inc"
2082
2083 // Function whose sole purpose is to kill compiler warnings 
2084 // stemming from unused functions included from PPCGenCallingConv.inc.
2085 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2086   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2087 }
2088
2089 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2090                                       CCValAssign::LocInfo &LocInfo,
2091                                       ISD::ArgFlagsTy &ArgFlags,
2092                                       CCState &State) {
2093   return true;
2094 }
2095
2096 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2097                                              MVT &LocVT,
2098                                              CCValAssign::LocInfo &LocInfo,
2099                                              ISD::ArgFlagsTy &ArgFlags,
2100                                              CCState &State) {
2101   static const MCPhysReg ArgRegs[] = {
2102     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2103     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2104   };
2105   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2106
2107   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2108
2109   // Skip one register if the first unallocated register has an even register
2110   // number and there are still argument registers available which have not been
2111   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2112   // need to skip a register if RegNum is odd.
2113   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2114     State.AllocateReg(ArgRegs[RegNum]);
2115   }
2116
2117   // Always return false here, as this function only makes sure that the first
2118   // unallocated register has an odd register number and does not actually
2119   // allocate a register for the current argument.
2120   return false;
2121 }
2122
2123 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2124                                                MVT &LocVT,
2125                                                CCValAssign::LocInfo &LocInfo,
2126                                                ISD::ArgFlagsTy &ArgFlags,
2127                                                CCState &State) {
2128   static const MCPhysReg ArgRegs[] = {
2129     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2130     PPC::F8
2131   };
2132
2133   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2134
2135   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2136
2137   // If there is only one Floating-point register left we need to put both f64
2138   // values of a split ppc_fp128 value on the stack.
2139   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2140     State.AllocateReg(ArgRegs[RegNum]);
2141   }
2142
2143   // Always return false here, as this function only makes sure that the two f64
2144   // values a ppc_fp128 value is split into are both passed in registers or both
2145   // passed on the stack and does not actually allocate a register for the
2146   // current argument.
2147   return false;
2148 }
2149
2150 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2151 /// on Darwin.
2152 static const MCPhysReg *GetFPR() {
2153   static const MCPhysReg FPR[] = {
2154     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2155     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2156   };
2157
2158   return FPR;
2159 }
2160
2161 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2162 /// the stack.
2163 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2164                                        unsigned PtrByteSize) {
2165   unsigned ArgSize = ArgVT.getStoreSize();
2166   if (Flags.isByVal())
2167     ArgSize = Flags.getByValSize();
2168
2169   // Round up to multiples of the pointer size, except for array members,
2170   // which are always packed.
2171   if (!Flags.isInConsecutiveRegs())
2172     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2173
2174   return ArgSize;
2175 }
2176
2177 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2178 /// on the stack.
2179 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2180                                             ISD::ArgFlagsTy Flags,
2181                                             unsigned PtrByteSize) {
2182   unsigned Align = PtrByteSize;
2183
2184   // Altivec parameters are padded to a 16 byte boundary.
2185   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2186       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2187       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2188     Align = 16;
2189
2190   // ByVal parameters are aligned as requested.
2191   if (Flags.isByVal()) {
2192     unsigned BVAlign = Flags.getByValAlign();
2193     if (BVAlign > PtrByteSize) {
2194       if (BVAlign % PtrByteSize != 0)
2195           llvm_unreachable(
2196             "ByVal alignment is not a multiple of the pointer size");
2197
2198       Align = BVAlign;
2199     }
2200   }
2201
2202   // Array members are always packed to their original alignment.
2203   if (Flags.isInConsecutiveRegs()) {
2204     // If the array member was split into multiple registers, the first
2205     // needs to be aligned to the size of the full type.  (Except for
2206     // ppcf128, which is only aligned as its f64 components.)
2207     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2208       Align = OrigVT.getStoreSize();
2209     else
2210       Align = ArgVT.getStoreSize();
2211   }
2212
2213   return Align;
2214 }
2215
2216 /// CalculateStackSlotUsed - Return whether this argument will use its
2217 /// stack slot (instead of being passed in registers).  ArgOffset,
2218 /// AvailableFPRs, and AvailableVRs must hold the current argument
2219 /// position, and will be updated to account for this argument.
2220 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2221                                    ISD::ArgFlagsTy Flags,
2222                                    unsigned PtrByteSize,
2223                                    unsigned LinkageSize,
2224                                    unsigned ParamAreaSize,
2225                                    unsigned &ArgOffset,
2226                                    unsigned &AvailableFPRs,
2227                                    unsigned &AvailableVRs) {
2228   bool UseMemory = false;
2229
2230   // Respect alignment of argument on the stack.
2231   unsigned Align =
2232     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2233   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2234   // If there's no space left in the argument save area, we must
2235   // use memory (this check also catches zero-sized arguments).
2236   if (ArgOffset >= LinkageSize + ParamAreaSize)
2237     UseMemory = true;
2238
2239   // Allocate argument on the stack.
2240   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2241   if (Flags.isInConsecutiveRegsLast())
2242     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2243   // If we overran the argument save area, we must use memory
2244   // (this check catches arguments passed partially in memory)
2245   if (ArgOffset > LinkageSize + ParamAreaSize)
2246     UseMemory = true;
2247
2248   // However, if the argument is actually passed in an FPR or a VR,
2249   // we don't use memory after all.
2250   if (!Flags.isByVal()) {
2251     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2252       if (AvailableFPRs > 0) {
2253         --AvailableFPRs;
2254         return false;
2255       }
2256     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2257         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2258         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2259       if (AvailableVRs > 0) {
2260         --AvailableVRs;
2261         return false;
2262       }
2263   }
2264
2265   return UseMemory;
2266 }
2267
2268 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2269 /// ensure minimum alignment required for target.
2270 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2271                                      unsigned NumBytes) {
2272   unsigned TargetAlign = Target.getFrameLowering()->getStackAlignment();
2273   unsigned AlignMask = TargetAlign - 1;
2274   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2275   return NumBytes;
2276 }
2277
2278 SDValue
2279 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2280                                         CallingConv::ID CallConv, bool isVarArg,
2281                                         const SmallVectorImpl<ISD::InputArg>
2282                                           &Ins,
2283                                         SDLoc dl, SelectionDAG &DAG,
2284                                         SmallVectorImpl<SDValue> &InVals)
2285                                           const {
2286   if (Subtarget.isSVR4ABI()) {
2287     if (Subtarget.isPPC64())
2288       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2289                                          dl, DAG, InVals);
2290     else
2291       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2292                                          dl, DAG, InVals);
2293   } else {
2294     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2295                                        dl, DAG, InVals);
2296   }
2297 }
2298
2299 SDValue
2300 PPCTargetLowering::LowerFormalArguments_32SVR4(
2301                                       SDValue Chain,
2302                                       CallingConv::ID CallConv, bool isVarArg,
2303                                       const SmallVectorImpl<ISD::InputArg>
2304                                         &Ins,
2305                                       SDLoc dl, SelectionDAG &DAG,
2306                                       SmallVectorImpl<SDValue> &InVals) const {
2307
2308   // 32-bit SVR4 ABI Stack Frame Layout:
2309   //              +-----------------------------------+
2310   //        +-->  |            Back chain             |
2311   //        |     +-----------------------------------+
2312   //        |     | Floating-point register save area |
2313   //        |     +-----------------------------------+
2314   //        |     |    General register save area     |
2315   //        |     +-----------------------------------+
2316   //        |     |          CR save word             |
2317   //        |     +-----------------------------------+
2318   //        |     |         VRSAVE save word          |
2319   //        |     +-----------------------------------+
2320   //        |     |         Alignment padding         |
2321   //        |     +-----------------------------------+
2322   //        |     |     Vector register save area     |
2323   //        |     +-----------------------------------+
2324   //        |     |       Local variable space        |
2325   //        |     +-----------------------------------+
2326   //        |     |        Parameter list area        |
2327   //        |     +-----------------------------------+
2328   //        |     |           LR save word            |
2329   //        |     +-----------------------------------+
2330   // SP-->  +---  |            Back chain             |
2331   //              +-----------------------------------+
2332   //
2333   // Specifications:
2334   //   System V Application Binary Interface PowerPC Processor Supplement
2335   //   AltiVec Technology Programming Interface Manual
2336
2337   MachineFunction &MF = DAG.getMachineFunction();
2338   MachineFrameInfo *MFI = MF.getFrameInfo();
2339   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2340
2341   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2342   // Potential tail calls could cause overwriting of argument stack slots.
2343   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2344                        (CallConv == CallingConv::Fast));
2345   unsigned PtrByteSize = 4;
2346
2347   // Assign locations to all of the incoming arguments.
2348   SmallVector<CCValAssign, 16> ArgLocs;
2349   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2350                  getTargetMachine(), ArgLocs, *DAG.getContext());
2351
2352   // Reserve space for the linkage area on the stack.
2353   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2354   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2355
2356   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2357
2358   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2359     CCValAssign &VA = ArgLocs[i];
2360
2361     // Arguments stored in registers.
2362     if (VA.isRegLoc()) {
2363       const TargetRegisterClass *RC;
2364       EVT ValVT = VA.getValVT();
2365
2366       switch (ValVT.getSimpleVT().SimpleTy) {
2367         default:
2368           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2369         case MVT::i1:
2370         case MVT::i32:
2371           RC = &PPC::GPRCRegClass;
2372           break;
2373         case MVT::f32:
2374           RC = &PPC::F4RCRegClass;
2375           break;
2376         case MVT::f64:
2377           if (Subtarget.hasVSX())
2378             RC = &PPC::VSFRCRegClass;
2379           else
2380             RC = &PPC::F8RCRegClass;
2381           break;
2382         case MVT::v16i8:
2383         case MVT::v8i16:
2384         case MVT::v4i32:
2385         case MVT::v4f32:
2386           RC = &PPC::VRRCRegClass;
2387           break;
2388         case MVT::v2f64:
2389         case MVT::v2i64:
2390           RC = &PPC::VSHRCRegClass;
2391           break;
2392       }
2393
2394       // Transform the arguments stored in physical registers into virtual ones.
2395       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2396       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2397                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2398
2399       if (ValVT == MVT::i1)
2400         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2401
2402       InVals.push_back(ArgValue);
2403     } else {
2404       // Argument stored in memory.
2405       assert(VA.isMemLoc());
2406
2407       unsigned ArgSize = VA.getLocVT().getStoreSize();
2408       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2409                                       isImmutable);
2410
2411       // Create load nodes to retrieve arguments from the stack.
2412       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2413       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2414                                    MachinePointerInfo(),
2415                                    false, false, false, 0));
2416     }
2417   }
2418
2419   // Assign locations to all of the incoming aggregate by value arguments.
2420   // Aggregates passed by value are stored in the local variable space of the
2421   // caller's stack frame, right above the parameter list area.
2422   SmallVector<CCValAssign, 16> ByValArgLocs;
2423   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2424                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
2425
2426   // Reserve stack space for the allocations in CCInfo.
2427   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2428
2429   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2430
2431   // Area that is at least reserved in the caller of this function.
2432   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2433   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2434
2435   // Set the size that is at least reserved in caller of this function.  Tail
2436   // call optimized function's reserved stack space needs to be aligned so that
2437   // taking the difference between two stack areas will result in an aligned
2438   // stack.
2439   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2440   FuncInfo->setMinReservedArea(MinReservedArea);
2441
2442   SmallVector<SDValue, 8> MemOps;
2443
2444   // If the function takes variable number of arguments, make a frame index for
2445   // the start of the first vararg value... for expansion of llvm.va_start.
2446   if (isVarArg) {
2447     static const MCPhysReg GPArgRegs[] = {
2448       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2449       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2450     };
2451     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2452
2453     static const MCPhysReg FPArgRegs[] = {
2454       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2455       PPC::F8
2456     };
2457     const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2458
2459     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2460                                                           NumGPArgRegs));
2461     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2462                                                           NumFPArgRegs));
2463
2464     // Make room for NumGPArgRegs and NumFPArgRegs.
2465     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2466                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2467
2468     FuncInfo->setVarArgsStackOffset(
2469       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2470                              CCInfo.getNextStackOffset(), true));
2471
2472     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2473     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2474
2475     // The fixed integer arguments of a variadic function are stored to the
2476     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2477     // the result of va_next.
2478     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2479       // Get an existing live-in vreg, or add a new one.
2480       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2481       if (!VReg)
2482         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2483
2484       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2485       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2486                                    MachinePointerInfo(), false, false, 0);
2487       MemOps.push_back(Store);
2488       // Increment the address by four for the next argument to store
2489       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2490       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2491     }
2492
2493     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2494     // is set.
2495     // The double arguments are stored to the VarArgsFrameIndex
2496     // on the stack.
2497     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2498       // Get an existing live-in vreg, or add a new one.
2499       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2500       if (!VReg)
2501         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2502
2503       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2504       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2505                                    MachinePointerInfo(), false, false, 0);
2506       MemOps.push_back(Store);
2507       // Increment the address by eight for the next argument to store
2508       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2509                                          PtrVT);
2510       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2511     }
2512   }
2513
2514   if (!MemOps.empty())
2515     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2516
2517   return Chain;
2518 }
2519
2520 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2521 // value to MVT::i64 and then truncate to the correct register size.
2522 SDValue
2523 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2524                                      SelectionDAG &DAG, SDValue ArgVal,
2525                                      SDLoc dl) const {
2526   if (Flags.isSExt())
2527     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2528                          DAG.getValueType(ObjectVT));
2529   else if (Flags.isZExt())
2530     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2531                          DAG.getValueType(ObjectVT));
2532
2533   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2534 }
2535
2536 SDValue
2537 PPCTargetLowering::LowerFormalArguments_64SVR4(
2538                                       SDValue Chain,
2539                                       CallingConv::ID CallConv, bool isVarArg,
2540                                       const SmallVectorImpl<ISD::InputArg>
2541                                         &Ins,
2542                                       SDLoc dl, SelectionDAG &DAG,
2543                                       SmallVectorImpl<SDValue> &InVals) const {
2544   // TODO: add description of PPC stack frame format, or at least some docs.
2545   //
2546   bool isELFv2ABI = Subtarget.isELFv2ABI();
2547   bool isLittleEndian = Subtarget.isLittleEndian();
2548   MachineFunction &MF = DAG.getMachineFunction();
2549   MachineFrameInfo *MFI = MF.getFrameInfo();
2550   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2551
2552   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2553   // Potential tail calls could cause overwriting of argument stack slots.
2554   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2555                        (CallConv == CallingConv::Fast));
2556   unsigned PtrByteSize = 8;
2557
2558   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2559                                                           isELFv2ABI);
2560
2561   static const MCPhysReg GPR[] = {
2562     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2563     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2564   };
2565
2566   static const MCPhysReg *FPR = GetFPR();
2567
2568   static const MCPhysReg VR[] = {
2569     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2570     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2571   };
2572   static const MCPhysReg VSRH[] = {
2573     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2574     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2575   };
2576
2577   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2578   const unsigned Num_FPR_Regs = 13;
2579   const unsigned Num_VR_Regs  = array_lengthof(VR);
2580
2581   // Do a first pass over the arguments to determine whether the ABI
2582   // guarantees that our caller has allocated the parameter save area
2583   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2584   // in the ELFv2 ABI, it is true if this is a vararg function or if
2585   // any parameter is located in a stack slot.
2586
2587   bool HasParameterArea = !isELFv2ABI || isVarArg;
2588   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2589   unsigned NumBytes = LinkageSize;
2590   unsigned AvailableFPRs = Num_FPR_Regs;
2591   unsigned AvailableVRs = Num_VR_Regs;
2592   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2593     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2594                                PtrByteSize, LinkageSize, ParamAreaSize,
2595                                NumBytes, AvailableFPRs, AvailableVRs))
2596       HasParameterArea = true;
2597
2598   // Add DAG nodes to load the arguments or copy them out of registers.  On
2599   // entry to a function on PPC, the arguments start after the linkage area,
2600   // although the first ones are often in registers.
2601
2602   unsigned ArgOffset = LinkageSize;
2603   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2604   SmallVector<SDValue, 8> MemOps;
2605   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2606   unsigned CurArgIdx = 0;
2607   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2608     SDValue ArgVal;
2609     bool needsLoad = false;
2610     EVT ObjectVT = Ins[ArgNo].VT;
2611     EVT OrigVT = Ins[ArgNo].ArgVT;
2612     unsigned ObjSize = ObjectVT.getStoreSize();
2613     unsigned ArgSize = ObjSize;
2614     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2615     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2616     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2617
2618     /* Respect alignment of argument on the stack.  */
2619     unsigned Align =
2620       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2621     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2622     unsigned CurArgOffset = ArgOffset;
2623
2624     /* Compute GPR index associated with argument offset.  */
2625     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2626     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2627
2628     // FIXME the codegen can be much improved in some cases.
2629     // We do not have to keep everything in memory.
2630     if (Flags.isByVal()) {
2631       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2632       ObjSize = Flags.getByValSize();
2633       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2634       // Empty aggregate parameters do not take up registers.  Examples:
2635       //   struct { } a;
2636       //   union  { } b;
2637       //   int c[0];
2638       // etc.  However, we have to provide a place-holder in InVals, so
2639       // pretend we have an 8-byte item at the current address for that
2640       // purpose.
2641       if (!ObjSize) {
2642         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2643         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2644         InVals.push_back(FIN);
2645         continue;
2646       }
2647
2648       // Create a stack object covering all stack doublewords occupied
2649       // by the argument.  If the argument is (fully or partially) on
2650       // the stack, or if the argument is fully in registers but the
2651       // caller has allocated the parameter save anyway, we can refer
2652       // directly to the caller's stack frame.  Otherwise, create a
2653       // local copy in our own frame.
2654       int FI;
2655       if (HasParameterArea ||
2656           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2657         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
2658       else
2659         FI = MFI->CreateStackObject(ArgSize, Align, false);
2660       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2661
2662       // Handle aggregates smaller than 8 bytes.
2663       if (ObjSize < PtrByteSize) {
2664         // The value of the object is its address, which differs from the
2665         // address of the enclosing doubleword on big-endian systems.
2666         SDValue Arg = FIN;
2667         if (!isLittleEndian) {
2668           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2669           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2670         }
2671         InVals.push_back(Arg);
2672
2673         if (GPR_idx != Num_GPR_Regs) {
2674           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2675           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2676           SDValue Store;
2677
2678           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2679             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2680                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2681             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2682                                       MachinePointerInfo(FuncArg),
2683                                       ObjType, false, false, 0);
2684           } else {
2685             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2686             // store the whole register as-is to the parameter save area
2687             // slot.
2688             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2689                                  MachinePointerInfo(FuncArg),
2690                                  false, false, 0);
2691           }
2692
2693           MemOps.push_back(Store);
2694         }
2695         // Whether we copied from a register or not, advance the offset
2696         // into the parameter save area by a full doubleword.
2697         ArgOffset += PtrByteSize;
2698         continue;
2699       }
2700
2701       // The value of the object is its address, which is the address of
2702       // its first stack doubleword.
2703       InVals.push_back(FIN);
2704
2705       // Store whatever pieces of the object are in registers to memory.
2706       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2707         if (GPR_idx == Num_GPR_Regs)
2708           break;
2709
2710         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2711         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2712         SDValue Addr = FIN;
2713         if (j) {
2714           SDValue Off = DAG.getConstant(j, PtrVT);
2715           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2716         }
2717         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2718                                      MachinePointerInfo(FuncArg, j),
2719                                      false, false, 0);
2720         MemOps.push_back(Store);
2721         ++GPR_idx;
2722       }
2723       ArgOffset += ArgSize;
2724       continue;
2725     }
2726
2727     switch (ObjectVT.getSimpleVT().SimpleTy) {
2728     default: llvm_unreachable("Unhandled argument type!");
2729     case MVT::i1:
2730     case MVT::i32:
2731     case MVT::i64:
2732       // These can be scalar arguments or elements of an integer array type
2733       // passed directly.  Clang may use those instead of "byval" aggregate
2734       // types to avoid forcing arguments to memory unnecessarily.
2735       if (GPR_idx != Num_GPR_Regs) {
2736         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2737         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2738
2739         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2740           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2741           // value to MVT::i64 and then truncate to the correct register size.
2742           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2743       } else {
2744         needsLoad = true;
2745         ArgSize = PtrByteSize;
2746       }
2747       ArgOffset += 8;
2748       break;
2749
2750     case MVT::f32:
2751     case MVT::f64:
2752       // These can be scalar arguments or elements of a float array type
2753       // passed directly.  The latter are used to implement ELFv2 homogenous
2754       // float aggregates.
2755       if (FPR_idx != Num_FPR_Regs) {
2756         unsigned VReg;
2757
2758         if (ObjectVT == MVT::f32)
2759           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2760         else
2761           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2762                                             &PPC::VSFRCRegClass :
2763                                             &PPC::F8RCRegClass);
2764
2765         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2766         ++FPR_idx;
2767       } else if (GPR_idx != Num_GPR_Regs) {
2768         // This can only ever happen in the presence of f32 array types,
2769         // since otherwise we never run out of FPRs before running out
2770         // of GPRs.
2771         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2772         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2773
2774         if (ObjectVT == MVT::f32) {
2775           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2776             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2777                                  DAG.getConstant(32, MVT::i32));
2778           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2779         }
2780
2781         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2782       } else {
2783         needsLoad = true;
2784       }
2785
2786       // When passing an array of floats, the array occupies consecutive
2787       // space in the argument area; only round up to the next doubleword
2788       // at the end of the array.  Otherwise, each float takes 8 bytes.
2789       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2790       ArgOffset += ArgSize;
2791       if (Flags.isInConsecutiveRegsLast())
2792         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2793       break;
2794     case MVT::v4f32:
2795     case MVT::v4i32:
2796     case MVT::v8i16:
2797     case MVT::v16i8:
2798     case MVT::v2f64:
2799     case MVT::v2i64:
2800       // These can be scalar arguments or elements of a vector array type
2801       // passed directly.  The latter are used to implement ELFv2 homogenous
2802       // vector aggregates.
2803       if (VR_idx != Num_VR_Regs) {
2804         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2805                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2806                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2807         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2808         ++VR_idx;
2809       } else {
2810         needsLoad = true;
2811       }
2812       ArgOffset += 16;
2813       break;
2814     }
2815
2816     // We need to load the argument to a virtual register if we determined
2817     // above that we ran out of physical registers of the appropriate type.
2818     if (needsLoad) {
2819       if (ObjSize < ArgSize && !isLittleEndian)
2820         CurArgOffset += ArgSize - ObjSize;
2821       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2822       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2823       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2824                            false, false, false, 0);
2825     }
2826
2827     InVals.push_back(ArgVal);
2828   }
2829
2830   // Area that is at least reserved in the caller of this function.
2831   unsigned MinReservedArea;
2832   if (HasParameterArea)
2833     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2834   else
2835     MinReservedArea = LinkageSize;
2836
2837   // Set the size that is at least reserved in caller of this function.  Tail
2838   // call optimized functions' reserved stack space needs to be aligned so that
2839   // taking the difference between two stack areas will result in an aligned
2840   // stack.
2841   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2842   FuncInfo->setMinReservedArea(MinReservedArea);
2843
2844   // If the function takes variable number of arguments, make a frame index for
2845   // the start of the first vararg value... for expansion of llvm.va_start.
2846   if (isVarArg) {
2847     int Depth = ArgOffset;
2848
2849     FuncInfo->setVarArgsFrameIndex(
2850       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2851     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2852
2853     // If this function is vararg, store any remaining integer argument regs
2854     // to their spots on the stack so that they may be loaded by deferencing the
2855     // result of va_next.
2856     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2857          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2858       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2859       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2860       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2861                                    MachinePointerInfo(), false, false, 0);
2862       MemOps.push_back(Store);
2863       // Increment the address by four for the next argument to store
2864       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2865       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2866     }
2867   }
2868
2869   if (!MemOps.empty())
2870     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2871
2872   return Chain;
2873 }
2874
2875 SDValue
2876 PPCTargetLowering::LowerFormalArguments_Darwin(
2877                                       SDValue Chain,
2878                                       CallingConv::ID CallConv, bool isVarArg,
2879                                       const SmallVectorImpl<ISD::InputArg>
2880                                         &Ins,
2881                                       SDLoc dl, SelectionDAG &DAG,
2882                                       SmallVectorImpl<SDValue> &InVals) const {
2883   // TODO: add description of PPC stack frame format, or at least some docs.
2884   //
2885   MachineFunction &MF = DAG.getMachineFunction();
2886   MachineFrameInfo *MFI = MF.getFrameInfo();
2887   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2888
2889   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2890   bool isPPC64 = PtrVT == MVT::i64;
2891   // Potential tail calls could cause overwriting of argument stack slots.
2892   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2893                        (CallConv == CallingConv::Fast));
2894   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2895
2896   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2897                                                           false);
2898   unsigned ArgOffset = LinkageSize;
2899   // Area that is at least reserved in caller of this function.
2900   unsigned MinReservedArea = ArgOffset;
2901
2902   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2903     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2904     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2905   };
2906   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2907     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2908     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2909   };
2910
2911   static const MCPhysReg *FPR = GetFPR();
2912
2913   static const MCPhysReg VR[] = {
2914     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2915     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2916   };
2917
2918   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2919   const unsigned Num_FPR_Regs = 13;
2920   const unsigned Num_VR_Regs  = array_lengthof( VR);
2921
2922   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2923
2924   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2925
2926   // In 32-bit non-varargs functions, the stack space for vectors is after the
2927   // stack space for non-vectors.  We do not use this space unless we have
2928   // too many vectors to fit in registers, something that only occurs in
2929   // constructed examples:), but we have to walk the arglist to figure
2930   // that out...for the pathological case, compute VecArgOffset as the
2931   // start of the vector parameter area.  Computing VecArgOffset is the
2932   // entire point of the following loop.
2933   unsigned VecArgOffset = ArgOffset;
2934   if (!isVarArg && !isPPC64) {
2935     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2936          ++ArgNo) {
2937       EVT ObjectVT = Ins[ArgNo].VT;
2938       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2939
2940       if (Flags.isByVal()) {
2941         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2942         unsigned ObjSize = Flags.getByValSize();
2943         unsigned ArgSize =
2944                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2945         VecArgOffset += ArgSize;
2946         continue;
2947       }
2948
2949       switch(ObjectVT.getSimpleVT().SimpleTy) {
2950       default: llvm_unreachable("Unhandled argument type!");
2951       case MVT::i1:
2952       case MVT::i32:
2953       case MVT::f32:
2954         VecArgOffset += 4;
2955         break;
2956       case MVT::i64:  // PPC64
2957       case MVT::f64:
2958         // FIXME: We are guaranteed to be !isPPC64 at this point.
2959         // Does MVT::i64 apply?
2960         VecArgOffset += 8;
2961         break;
2962       case MVT::v4f32:
2963       case MVT::v4i32:
2964       case MVT::v8i16:
2965       case MVT::v16i8:
2966         // Nothing to do, we're only looking at Nonvector args here.
2967         break;
2968       }
2969     }
2970   }
2971   // We've found where the vector parameter area in memory is.  Skip the
2972   // first 12 parameters; these don't use that memory.
2973   VecArgOffset = ((VecArgOffset+15)/16)*16;
2974   VecArgOffset += 12*16;
2975
2976   // Add DAG nodes to load the arguments or copy them out of registers.  On
2977   // entry to a function on PPC, the arguments start after the linkage area,
2978   // although the first ones are often in registers.
2979
2980   SmallVector<SDValue, 8> MemOps;
2981   unsigned nAltivecParamsAtEnd = 0;
2982   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2983   unsigned CurArgIdx = 0;
2984   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2985     SDValue ArgVal;
2986     bool needsLoad = false;
2987     EVT ObjectVT = Ins[ArgNo].VT;
2988     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2989     unsigned ArgSize = ObjSize;
2990     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2991     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2992     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2993
2994     unsigned CurArgOffset = ArgOffset;
2995
2996     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2997     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2998         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2999       if (isVarArg || isPPC64) {
3000         MinReservedArea = ((MinReservedArea+15)/16)*16;
3001         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3002                                                   Flags,
3003                                                   PtrByteSize);
3004       } else  nAltivecParamsAtEnd++;
3005     } else
3006       // Calculate min reserved area.
3007       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3008                                                 Flags,
3009                                                 PtrByteSize);
3010
3011     // FIXME the codegen can be much improved in some cases.
3012     // We do not have to keep everything in memory.
3013     if (Flags.isByVal()) {
3014       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3015       ObjSize = Flags.getByValSize();
3016       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3017       // Objects of size 1 and 2 are right justified, everything else is
3018       // left justified.  This means the memory address is adjusted forwards.
3019       if (ObjSize==1 || ObjSize==2) {
3020         CurArgOffset = CurArgOffset + (4 - ObjSize);
3021       }
3022       // The value of the object is its address.
3023       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
3024       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3025       InVals.push_back(FIN);
3026       if (ObjSize==1 || ObjSize==2) {
3027         if (GPR_idx != Num_GPR_Regs) {
3028           unsigned VReg;
3029           if (isPPC64)
3030             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3031           else
3032             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3033           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3034           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3035           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3036                                             MachinePointerInfo(FuncArg),
3037                                             ObjType, false, false, 0);
3038           MemOps.push_back(Store);
3039           ++GPR_idx;
3040         }
3041
3042         ArgOffset += PtrByteSize;
3043
3044         continue;
3045       }
3046       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3047         // Store whatever pieces of the object are in registers
3048         // to memory.  ArgOffset will be the address of the beginning
3049         // of the object.
3050         if (GPR_idx != Num_GPR_Regs) {
3051           unsigned VReg;
3052           if (isPPC64)
3053             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3054           else
3055             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3056           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3057           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3058           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3059           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3060                                        MachinePointerInfo(FuncArg, j),
3061                                        false, false, 0);
3062           MemOps.push_back(Store);
3063           ++GPR_idx;
3064           ArgOffset += PtrByteSize;
3065         } else {
3066           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3067           break;
3068         }
3069       }
3070       continue;
3071     }
3072
3073     switch (ObjectVT.getSimpleVT().SimpleTy) {
3074     default: llvm_unreachable("Unhandled argument type!");
3075     case MVT::i1:
3076     case MVT::i32:
3077       if (!isPPC64) {
3078         if (GPR_idx != Num_GPR_Regs) {
3079           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3080           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3081
3082           if (ObjectVT == MVT::i1)
3083             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3084
3085           ++GPR_idx;
3086         } else {
3087           needsLoad = true;
3088           ArgSize = PtrByteSize;
3089         }
3090         // All int arguments reserve stack space in the Darwin ABI.
3091         ArgOffset += PtrByteSize;
3092         break;
3093       }
3094       // FALLTHROUGH
3095     case MVT::i64:  // PPC64
3096       if (GPR_idx != Num_GPR_Regs) {
3097         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3098         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3099
3100         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3101           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3102           // value to MVT::i64 and then truncate to the correct register size.
3103           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3104
3105         ++GPR_idx;
3106       } else {
3107         needsLoad = true;
3108         ArgSize = PtrByteSize;
3109       }
3110       // All int arguments reserve stack space in the Darwin ABI.
3111       ArgOffset += 8;
3112       break;
3113
3114     case MVT::f32:
3115     case MVT::f64:
3116       // Every 4 bytes of argument space consumes one of the GPRs available for
3117       // argument passing.
3118       if (GPR_idx != Num_GPR_Regs) {
3119         ++GPR_idx;
3120         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3121           ++GPR_idx;
3122       }
3123       if (FPR_idx != Num_FPR_Regs) {
3124         unsigned VReg;
3125
3126         if (ObjectVT == MVT::f32)
3127           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3128         else
3129           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3130
3131         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3132         ++FPR_idx;
3133       } else {
3134         needsLoad = true;
3135       }
3136
3137       // All FP arguments reserve stack space in the Darwin ABI.
3138       ArgOffset += isPPC64 ? 8 : ObjSize;
3139       break;
3140     case MVT::v4f32:
3141     case MVT::v4i32:
3142     case MVT::v8i16:
3143     case MVT::v16i8:
3144       // Note that vector arguments in registers don't reserve stack space,
3145       // except in varargs functions.
3146       if (VR_idx != Num_VR_Regs) {
3147         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3148         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3149         if (isVarArg) {
3150           while ((ArgOffset % 16) != 0) {
3151             ArgOffset += PtrByteSize;
3152             if (GPR_idx != Num_GPR_Regs)
3153               GPR_idx++;
3154           }
3155           ArgOffset += 16;
3156           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3157         }
3158         ++VR_idx;
3159       } else {
3160         if (!isVarArg && !isPPC64) {
3161           // Vectors go after all the nonvectors.
3162           CurArgOffset = VecArgOffset;
3163           VecArgOffset += 16;
3164         } else {
3165           // Vectors are aligned.
3166           ArgOffset = ((ArgOffset+15)/16)*16;
3167           CurArgOffset = ArgOffset;
3168           ArgOffset += 16;
3169         }
3170         needsLoad = true;
3171       }
3172       break;
3173     }
3174
3175     // We need to load the argument to a virtual register if we determined above
3176     // that we ran out of physical registers of the appropriate type.
3177     if (needsLoad) {
3178       int FI = MFI->CreateFixedObject(ObjSize,
3179                                       CurArgOffset + (ArgSize - ObjSize),
3180                                       isImmutable);
3181       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3182       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3183                            false, false, false, 0);
3184     }
3185
3186     InVals.push_back(ArgVal);
3187   }
3188
3189   // Allow for Altivec parameters at the end, if needed.
3190   if (nAltivecParamsAtEnd) {
3191     MinReservedArea = ((MinReservedArea+15)/16)*16;
3192     MinReservedArea += 16*nAltivecParamsAtEnd;
3193   }
3194
3195   // Area that is at least reserved in the caller of this function.
3196   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3197
3198   // Set the size that is at least reserved in caller of this function.  Tail
3199   // call optimized functions' reserved stack space needs to be aligned so that
3200   // taking the difference between two stack areas will result in an aligned
3201   // stack.
3202   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3203   FuncInfo->setMinReservedArea(MinReservedArea);
3204
3205   // If the function takes variable number of arguments, make a frame index for
3206   // the start of the first vararg value... for expansion of llvm.va_start.
3207   if (isVarArg) {
3208     int Depth = ArgOffset;
3209
3210     FuncInfo->setVarArgsFrameIndex(
3211       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3212                              Depth, true));
3213     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3214
3215     // If this function is vararg, store any remaining integer argument regs
3216     // to their spots on the stack so that they may be loaded by deferencing the
3217     // result of va_next.
3218     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3219       unsigned VReg;
3220
3221       if (isPPC64)
3222         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3223       else
3224         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3225
3226       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3227       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3228                                    MachinePointerInfo(), false, false, 0);
3229       MemOps.push_back(Store);
3230       // Increment the address by four for the next argument to store
3231       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3232       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3233     }
3234   }
3235
3236   if (!MemOps.empty())
3237     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3238
3239   return Chain;
3240 }
3241
3242 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3243 /// adjusted to accommodate the arguments for the tailcall.
3244 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3245                                    unsigned ParamSize) {
3246
3247   if (!isTailCall) return 0;
3248
3249   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3250   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3251   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3252   // Remember only if the new adjustement is bigger.
3253   if (SPDiff < FI->getTailCallSPDelta())
3254     FI->setTailCallSPDelta(SPDiff);
3255
3256   return SPDiff;
3257 }
3258
3259 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3260 /// for tail call optimization. Targets which want to do tail call
3261 /// optimization should implement this function.
3262 bool
3263 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3264                                                      CallingConv::ID CalleeCC,
3265                                                      bool isVarArg,
3266                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3267                                                      SelectionDAG& DAG) const {
3268   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3269     return false;
3270
3271   // Variable argument functions are not supported.
3272   if (isVarArg)
3273     return false;
3274
3275   MachineFunction &MF = DAG.getMachineFunction();
3276   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3277   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3278     // Functions containing by val parameters are not supported.
3279     for (unsigned i = 0; i != Ins.size(); i++) {
3280        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3281        if (Flags.isByVal()) return false;
3282     }
3283
3284     // Non-PIC/GOT tail calls are supported.
3285     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3286       return true;
3287
3288     // At the moment we can only do local tail calls (in same module, hidden
3289     // or protected) if we are generating PIC.
3290     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3291       return G->getGlobal()->hasHiddenVisibility()
3292           || G->getGlobal()->hasProtectedVisibility();
3293   }
3294
3295   return false;
3296 }
3297
3298 /// isCallCompatibleAddress - Return the immediate to use if the specified
3299 /// 32-bit value is representable in the immediate field of a BxA instruction.
3300 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3301   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3302   if (!C) return nullptr;
3303
3304   int Addr = C->getZExtValue();
3305   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3306       SignExtend32<26>(Addr) != Addr)
3307     return nullptr;  // Top 6 bits have to be sext of immediate.
3308
3309   return DAG.getConstant((int)C->getZExtValue() >> 2,
3310                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3311 }
3312
3313 namespace {
3314
3315 struct TailCallArgumentInfo {
3316   SDValue Arg;
3317   SDValue FrameIdxOp;
3318   int       FrameIdx;
3319
3320   TailCallArgumentInfo() : FrameIdx(0) {}
3321 };
3322
3323 }
3324
3325 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3326 static void
3327 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3328                                            SDValue Chain,
3329                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3330                    SmallVectorImpl<SDValue> &MemOpChains,
3331                    SDLoc dl) {
3332   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3333     SDValue Arg = TailCallArgs[i].Arg;
3334     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3335     int FI = TailCallArgs[i].FrameIdx;
3336     // Store relative to framepointer.
3337     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3338                                        MachinePointerInfo::getFixedStack(FI),
3339                                        false, false, 0));
3340   }
3341 }
3342
3343 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3344 /// the appropriate stack slot for the tail call optimized function call.
3345 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3346                                                MachineFunction &MF,
3347                                                SDValue Chain,
3348                                                SDValue OldRetAddr,
3349                                                SDValue OldFP,
3350                                                int SPDiff,
3351                                                bool isPPC64,
3352                                                bool isDarwinABI,
3353                                                SDLoc dl) {
3354   if (SPDiff) {
3355     // Calculate the new stack slot for the return address.
3356     int SlotSize = isPPC64 ? 8 : 4;
3357     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3358                                                                    isDarwinABI);
3359     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3360                                                           NewRetAddrLoc, true);
3361     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3362     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3363     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3364                          MachinePointerInfo::getFixedStack(NewRetAddr),
3365                          false, false, 0);
3366
3367     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3368     // slot as the FP is never overwritten.
3369     if (isDarwinABI) {
3370       int NewFPLoc =
3371         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3372       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3373                                                           true);
3374       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3375       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3376                            MachinePointerInfo::getFixedStack(NewFPIdx),
3377                            false, false, 0);
3378     }
3379   }
3380   return Chain;
3381 }
3382
3383 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3384 /// the position of the argument.
3385 static void
3386 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3387                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3388                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3389   int Offset = ArgOffset + SPDiff;
3390   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3391   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3392   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3393   SDValue FIN = DAG.getFrameIndex(FI, VT);
3394   TailCallArgumentInfo Info;
3395   Info.Arg = Arg;
3396   Info.FrameIdxOp = FIN;
3397   Info.FrameIdx = FI;
3398   TailCallArguments.push_back(Info);
3399 }
3400
3401 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3402 /// stack slot. Returns the chain as result and the loaded frame pointers in
3403 /// LROpOut/FPOpout. Used when tail calling.
3404 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3405                                                         int SPDiff,
3406                                                         SDValue Chain,
3407                                                         SDValue &LROpOut,
3408                                                         SDValue &FPOpOut,
3409                                                         bool isDarwinABI,
3410                                                         SDLoc dl) const {
3411   if (SPDiff) {
3412     // Load the LR and FP stack slot for later adjusting.
3413     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3414     LROpOut = getReturnAddrFrameIndex(DAG);
3415     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3416                           false, false, false, 0);
3417     Chain = SDValue(LROpOut.getNode(), 1);
3418
3419     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3420     // slot as the FP is never overwritten.
3421     if (isDarwinABI) {
3422       FPOpOut = getFramePointerFrameIndex(DAG);
3423       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3424                             false, false, false, 0);
3425       Chain = SDValue(FPOpOut.getNode(), 1);
3426     }
3427   }
3428   return Chain;
3429 }
3430
3431 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3432 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3433 /// specified by the specific parameter attribute. The copy will be passed as
3434 /// a byval function parameter.
3435 /// Sometimes what we are copying is the end of a larger object, the part that
3436 /// does not fit in registers.
3437 static SDValue
3438 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3439                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3440                           SDLoc dl) {
3441   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3442   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3443                        false, false, MachinePointerInfo(),
3444                        MachinePointerInfo());
3445 }
3446
3447 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3448 /// tail calls.
3449 static void
3450 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3451                  SDValue Arg, SDValue PtrOff, int SPDiff,
3452                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3453                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3454                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3455                  SDLoc dl) {
3456   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3457   if (!isTailCall) {
3458     if (isVector) {
3459       SDValue StackPtr;
3460       if (isPPC64)
3461         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3462       else
3463         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3464       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3465                            DAG.getConstant(ArgOffset, PtrVT));
3466     }
3467     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3468                                        MachinePointerInfo(), false, false, 0));
3469   // Calculate and remember argument location.
3470   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3471                                   TailCallArguments);
3472 }
3473
3474 static
3475 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3476                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3477                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3478                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3479   MachineFunction &MF = DAG.getMachineFunction();
3480
3481   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3482   // might overwrite each other in case of tail call optimization.
3483   SmallVector<SDValue, 8> MemOpChains2;
3484   // Do not flag preceding copytoreg stuff together with the following stuff.
3485   InFlag = SDValue();
3486   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3487                                     MemOpChains2, dl);
3488   if (!MemOpChains2.empty())
3489     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3490
3491   // Store the return address to the appropriate stack slot.
3492   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3493                                         isPPC64, isDarwinABI, dl);
3494
3495   // Emit callseq_end just before tailcall node.
3496   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3497                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3498   InFlag = Chain.getValue(1);
3499 }
3500
3501 static
3502 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3503                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3504                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3505                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3506                      const PPCSubtarget &Subtarget) {
3507
3508   bool isPPC64 = Subtarget.isPPC64();
3509   bool isSVR4ABI = Subtarget.isSVR4ABI();
3510   bool isELFv2ABI = Subtarget.isELFv2ABI();
3511
3512   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3513   NodeTys.push_back(MVT::Other);   // Returns a chain
3514   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3515
3516   unsigned CallOpc = PPCISD::CALL;
3517
3518   bool needIndirectCall = true;
3519   if (!isSVR4ABI || !isPPC64)
3520     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3521       // If this is an absolute destination address, use the munged value.
3522       Callee = SDValue(Dest, 0);
3523       needIndirectCall = false;
3524     }
3525
3526   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3527     // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3528     // Use indirect calls for ALL functions calls in JIT mode, since the
3529     // far-call stubs may be outside relocation limits for a BL instruction.
3530     if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3531       unsigned OpFlags = 0;
3532       if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3533           (Subtarget.getTargetTriple().isMacOSX() &&
3534            Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3535           (G->getGlobal()->isDeclaration() ||
3536            G->getGlobal()->isWeakForLinker())) ||
3537           (Subtarget.isTargetELF() && !isPPC64 &&
3538            !G->getGlobal()->hasLocalLinkage() &&
3539            DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3540         // PC-relative references to external symbols should go through $stub,
3541         // unless we're building with the leopard linker or later, which
3542         // automatically synthesizes these stubs.
3543         OpFlags = PPCII::MO_PLT_OR_STUB;
3544       }
3545
3546       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3547       // every direct call is) turn it into a TargetGlobalAddress /
3548       // TargetExternalSymbol node so that legalize doesn't hack it.
3549       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3550                                           Callee.getValueType(),
3551                                           0, OpFlags);
3552       needIndirectCall = false;
3553     }
3554   }
3555
3556   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3557     unsigned char OpFlags = 0;
3558
3559     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3560          (Subtarget.getTargetTriple().isMacOSX() &&
3561           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3562         (Subtarget.isTargetELF() && !isPPC64 &&
3563          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3564       // PC-relative references to external symbols should go through $stub,
3565       // unless we're building with the leopard linker or later, which
3566       // automatically synthesizes these stubs.
3567       OpFlags = PPCII::MO_PLT_OR_STUB;
3568     }
3569
3570     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3571                                          OpFlags);
3572     needIndirectCall = false;
3573   }
3574
3575   if (needIndirectCall) {
3576     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3577     // to do the call, we can't use PPCISD::CALL.
3578     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3579
3580     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3581       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3582       // entry point, but to the function descriptor (the function entry point
3583       // address is part of the function descriptor though).
3584       // The function descriptor is a three doubleword structure with the
3585       // following fields: function entry point, TOC base address and
3586       // environment pointer.
3587       // Thus for a call through a function pointer, the following actions need
3588       // to be performed:
3589       //   1. Save the TOC of the caller in the TOC save area of its stack
3590       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3591       //   2. Load the address of the function entry point from the function
3592       //      descriptor.
3593       //   3. Load the TOC of the callee from the function descriptor into r2.
3594       //   4. Load the environment pointer from the function descriptor into
3595       //      r11.
3596       //   5. Branch to the function entry point address.
3597       //   6. On return of the callee, the TOC of the caller needs to be
3598       //      restored (this is done in FinishCall()).
3599       //
3600       // All those operations are flagged together to ensure that no other
3601       // operations can be scheduled in between. E.g. without flagging the
3602       // operations together, a TOC access in the caller could be scheduled
3603       // between the load of the callee TOC and the branch to the callee, which
3604       // results in the TOC access going through the TOC of the callee instead
3605       // of going through the TOC of the caller, which leads to incorrect code.
3606
3607       // Load the address of the function entry point from the function
3608       // descriptor.
3609       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3610       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3611                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3612       Chain = LoadFuncPtr.getValue(1);
3613       InFlag = LoadFuncPtr.getValue(2);
3614
3615       // Load environment pointer into r11.
3616       // Offset of the environment pointer within the function descriptor.
3617       SDValue PtrOff = DAG.getIntPtrConstant(16);
3618
3619       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3620       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3621                                        InFlag);
3622       Chain = LoadEnvPtr.getValue(1);
3623       InFlag = LoadEnvPtr.getValue(2);
3624
3625       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3626                                         InFlag);
3627       Chain = EnvVal.getValue(0);
3628       InFlag = EnvVal.getValue(1);
3629
3630       // Load TOC of the callee into r2. We are using a target-specific load
3631       // with r2 hard coded, because the result of a target-independent load
3632       // would never go directly into r2, since r2 is a reserved register (which
3633       // prevents the register allocator from allocating it), resulting in an
3634       // additional register being allocated and an unnecessary move instruction
3635       // being generated.
3636       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3637       SDValue TOCOff = DAG.getIntPtrConstant(8);
3638       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3639       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3640                                        AddTOC, InFlag);
3641       Chain = LoadTOCPtr.getValue(0);
3642       InFlag = LoadTOCPtr.getValue(1);
3643
3644       MTCTROps[0] = Chain;
3645       MTCTROps[1] = LoadFuncPtr;
3646       MTCTROps[2] = InFlag;
3647     }
3648
3649     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3650                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3651     InFlag = Chain.getValue(1);
3652
3653     NodeTys.clear();
3654     NodeTys.push_back(MVT::Other);
3655     NodeTys.push_back(MVT::Glue);
3656     Ops.push_back(Chain);
3657     CallOpc = PPCISD::BCTRL;
3658     Callee.setNode(nullptr);
3659     // Add use of X11 (holding environment pointer)
3660     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3661       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3662     // Add CTR register as callee so a bctr can be emitted later.
3663     if (isTailCall)
3664       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3665   }
3666
3667   // If this is a direct call, pass the chain and the callee.
3668   if (Callee.getNode()) {
3669     Ops.push_back(Chain);
3670     Ops.push_back(Callee);
3671   }
3672   // If this is a tail call add stack pointer delta.
3673   if (isTailCall)
3674     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3675
3676   // Add argument registers to the end of the list so that they are known live
3677   // into the call.
3678   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3679     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3680                                   RegsToPass[i].second.getValueType()));
3681
3682   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3683   if (Callee.getNode() && isELFv2ABI)
3684     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3685
3686   return CallOpc;
3687 }
3688
3689 static
3690 bool isLocalCall(const SDValue &Callee)
3691 {
3692   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3693     return !G->getGlobal()->isDeclaration() &&
3694            !G->getGlobal()->isWeakForLinker();
3695   return false;
3696 }
3697
3698 SDValue
3699 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3700                                    CallingConv::ID CallConv, bool isVarArg,
3701                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3702                                    SDLoc dl, SelectionDAG &DAG,
3703                                    SmallVectorImpl<SDValue> &InVals) const {
3704
3705   SmallVector<CCValAssign, 16> RVLocs;
3706   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3707                     getTargetMachine(), RVLocs, *DAG.getContext());
3708   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3709
3710   // Copy all of the result registers out of their specified physreg.
3711   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3712     CCValAssign &VA = RVLocs[i];
3713     assert(VA.isRegLoc() && "Can only return in registers!");
3714
3715     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3716                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3717     Chain = Val.getValue(1);
3718     InFlag = Val.getValue(2);
3719
3720     switch (VA.getLocInfo()) {
3721     default: llvm_unreachable("Unknown loc info!");
3722     case CCValAssign::Full: break;
3723     case CCValAssign::AExt:
3724       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3725       break;
3726     case CCValAssign::ZExt:
3727       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3728                         DAG.getValueType(VA.getValVT()));
3729       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3730       break;
3731     case CCValAssign::SExt:
3732       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3733                         DAG.getValueType(VA.getValVT()));
3734       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3735       break;
3736     }
3737
3738     InVals.push_back(Val);
3739   }
3740
3741   return Chain;
3742 }
3743
3744 SDValue
3745 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3746                               bool isTailCall, bool isVarArg,
3747                               SelectionDAG &DAG,
3748                               SmallVector<std::pair<unsigned, SDValue>, 8>
3749                                 &RegsToPass,
3750                               SDValue InFlag, SDValue Chain,
3751                               SDValue &Callee,
3752                               int SPDiff, unsigned NumBytes,
3753                               const SmallVectorImpl<ISD::InputArg> &Ins,
3754                               SmallVectorImpl<SDValue> &InVals) const {
3755
3756   bool isELFv2ABI = Subtarget.isELFv2ABI();
3757   std::vector<EVT> NodeTys;
3758   SmallVector<SDValue, 8> Ops;
3759   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3760                                  isTailCall, RegsToPass, Ops, NodeTys,
3761                                  Subtarget);
3762
3763   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3764   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3765     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3766
3767   // When performing tail call optimization the callee pops its arguments off
3768   // the stack. Account for this here so these bytes can be pushed back on in
3769   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3770   int BytesCalleePops =
3771     (CallConv == CallingConv::Fast &&
3772      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3773
3774   // Add a register mask operand representing the call-preserved registers.
3775   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3776   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3777   assert(Mask && "Missing call preserved mask for calling convention");
3778   Ops.push_back(DAG.getRegisterMask(Mask));
3779
3780   if (InFlag.getNode())
3781     Ops.push_back(InFlag);
3782
3783   // Emit tail call.
3784   if (isTailCall) {
3785     assert(((Callee.getOpcode() == ISD::Register &&
3786              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3787             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3788             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3789             isa<ConstantSDNode>(Callee)) &&
3790     "Expecting an global address, external symbol, absolute value or register");
3791
3792     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3793   }
3794
3795   // Add a NOP immediately after the branch instruction when using the 64-bit
3796   // SVR4 ABI. At link time, if caller and callee are in a different module and
3797   // thus have a different TOC, the call will be replaced with a call to a stub
3798   // function which saves the current TOC, loads the TOC of the callee and
3799   // branches to the callee. The NOP will be replaced with a load instruction
3800   // which restores the TOC of the caller from the TOC save slot of the current
3801   // stack frame. If caller and callee belong to the same module (and have the
3802   // same TOC), the NOP will remain unchanged.
3803
3804   bool needsTOCRestore = false;
3805   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3806     if (CallOpc == PPCISD::BCTRL) {
3807       // This is a call through a function pointer.
3808       // Restore the caller TOC from the save area into R2.
3809       // See PrepareCall() for more information about calls through function
3810       // pointers in the 64-bit SVR4 ABI.
3811       // We are using a target-specific load with r2 hard coded, because the
3812       // result of a target-independent load would never go directly into r2,
3813       // since r2 is a reserved register (which prevents the register allocator
3814       // from allocating it), resulting in an additional register being
3815       // allocated and an unnecessary move instruction being generated.
3816       needsTOCRestore = true;
3817     } else if ((CallOpc == PPCISD::CALL) &&
3818                (!isLocalCall(Callee) ||
3819                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3820       // Otherwise insert NOP for non-local calls.
3821       CallOpc = PPCISD::CALL_NOP;
3822     }
3823   }
3824
3825   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3826   InFlag = Chain.getValue(1);
3827
3828   if (needsTOCRestore) {
3829     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3830     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3831     SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3832     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3833     SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3834     SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3835     Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3836     InFlag = Chain.getValue(1);
3837   }
3838
3839   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3840                              DAG.getIntPtrConstant(BytesCalleePops, true),
3841                              InFlag, dl);
3842   if (!Ins.empty())
3843     InFlag = Chain.getValue(1);
3844
3845   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3846                          Ins, dl, DAG, InVals);
3847 }
3848
3849 SDValue
3850 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3851                              SmallVectorImpl<SDValue> &InVals) const {
3852   SelectionDAG &DAG                     = CLI.DAG;
3853   SDLoc &dl                             = CLI.DL;
3854   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3855   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3856   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3857   SDValue Chain                         = CLI.Chain;
3858   SDValue Callee                        = CLI.Callee;
3859   bool &isTailCall                      = CLI.IsTailCall;
3860   CallingConv::ID CallConv              = CLI.CallConv;
3861   bool isVarArg                         = CLI.IsVarArg;
3862
3863   if (isTailCall)
3864     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3865                                                    Ins, DAG);
3866
3867   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3868     report_fatal_error("failed to perform tail call elimination on a call "
3869                        "site marked musttail");
3870
3871   if (Subtarget.isSVR4ABI()) {
3872     if (Subtarget.isPPC64())
3873       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3874                               isTailCall, Outs, OutVals, Ins,
3875                               dl, DAG, InVals);
3876     else
3877       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3878                               isTailCall, Outs, OutVals, Ins,
3879                               dl, DAG, InVals);
3880   }
3881
3882   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3883                           isTailCall, Outs, OutVals, Ins,
3884                           dl, DAG, InVals);
3885 }
3886
3887 SDValue
3888 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3889                                     CallingConv::ID CallConv, bool isVarArg,
3890                                     bool isTailCall,
3891                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3892                                     const SmallVectorImpl<SDValue> &OutVals,
3893                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3894                                     SDLoc dl, SelectionDAG &DAG,
3895                                     SmallVectorImpl<SDValue> &InVals) const {
3896   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3897   // of the 32-bit SVR4 ABI stack frame layout.
3898
3899   assert((CallConv == CallingConv::C ||
3900           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3901
3902   unsigned PtrByteSize = 4;
3903
3904   MachineFunction &MF = DAG.getMachineFunction();
3905
3906   // Mark this function as potentially containing a function that contains a
3907   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3908   // and restoring the callers stack pointer in this functions epilog. This is
3909   // done because by tail calling the called function might overwrite the value
3910   // in this function's (MF) stack pointer stack slot 0(SP).
3911   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3912       CallConv == CallingConv::Fast)
3913     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3914
3915   // Count how many bytes are to be pushed on the stack, including the linkage
3916   // area, parameter list area and the part of the local variable space which
3917   // contains copies of aggregates which are passed by value.
3918
3919   // Assign locations to all of the outgoing arguments.
3920   SmallVector<CCValAssign, 16> ArgLocs;
3921   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3922                  getTargetMachine(), ArgLocs, *DAG.getContext());
3923
3924   // Reserve space for the linkage area on the stack.
3925   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3926                        PtrByteSize);
3927
3928   if (isVarArg) {
3929     // Handle fixed and variable vector arguments differently.
3930     // Fixed vector arguments go into registers as long as registers are
3931     // available. Variable vector arguments always go into memory.
3932     unsigned NumArgs = Outs.size();
3933
3934     for (unsigned i = 0; i != NumArgs; ++i) {
3935       MVT ArgVT = Outs[i].VT;
3936       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3937       bool Result;
3938
3939       if (Outs[i].IsFixed) {
3940         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3941                                CCInfo);
3942       } else {
3943         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3944                                       ArgFlags, CCInfo);
3945       }
3946
3947       if (Result) {
3948 #ifndef NDEBUG
3949         errs() << "Call operand #" << i << " has unhandled type "
3950              << EVT(ArgVT).getEVTString() << "\n";
3951 #endif
3952         llvm_unreachable(nullptr);
3953       }
3954     }
3955   } else {
3956     // All arguments are treated the same.
3957     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3958   }
3959
3960   // Assign locations to all of the outgoing aggregate by value arguments.
3961   SmallVector<CCValAssign, 16> ByValArgLocs;
3962   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3963                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
3964
3965   // Reserve stack space for the allocations in CCInfo.
3966   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3967
3968   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3969
3970   // Size of the linkage area, parameter list area and the part of the local
3971   // space variable where copies of aggregates which are passed by value are
3972   // stored.
3973   unsigned NumBytes = CCByValInfo.getNextStackOffset();
3974
3975   // Calculate by how many bytes the stack has to be adjusted in case of tail
3976   // call optimization.
3977   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3978
3979   // Adjust the stack pointer for the new arguments...
3980   // These operations are automatically eliminated by the prolog/epilog pass
3981   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3982                                dl);
3983   SDValue CallSeqStart = Chain;
3984
3985   // Load the return address and frame pointer so it can be moved somewhere else
3986   // later.
3987   SDValue LROp, FPOp;
3988   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3989                                        dl);
3990
3991   // Set up a copy of the stack pointer for use loading and storing any
3992   // arguments that may not fit in the registers available for argument
3993   // passing.
3994   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3995
3996   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3997   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3998   SmallVector<SDValue, 8> MemOpChains;
3999
4000   bool seenFloatArg = false;
4001   // Walk the register/memloc assignments, inserting copies/loads.
4002   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4003        i != e;
4004        ++i) {
4005     CCValAssign &VA = ArgLocs[i];
4006     SDValue Arg = OutVals[i];
4007     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4008
4009     if (Flags.isByVal()) {
4010       // Argument is an aggregate which is passed by value, thus we need to
4011       // create a copy of it in the local variable space of the current stack
4012       // frame (which is the stack frame of the caller) and pass the address of
4013       // this copy to the callee.
4014       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4015       CCValAssign &ByValVA = ByValArgLocs[j++];
4016       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4017
4018       // Memory reserved in the local variable space of the callers stack frame.
4019       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4020
4021       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4022       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4023
4024       // Create a copy of the argument in the local area of the current
4025       // stack frame.
4026       SDValue MemcpyCall =
4027         CreateCopyOfByValArgument(Arg, PtrOff,
4028                                   CallSeqStart.getNode()->getOperand(0),
4029                                   Flags, DAG, dl);
4030
4031       // This must go outside the CALLSEQ_START..END.
4032       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4033                            CallSeqStart.getNode()->getOperand(1),
4034                            SDLoc(MemcpyCall));
4035       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4036                              NewCallSeqStart.getNode());
4037       Chain = CallSeqStart = NewCallSeqStart;
4038
4039       // Pass the address of the aggregate copy on the stack either in a
4040       // physical register or in the parameter list area of the current stack
4041       // frame to the callee.
4042       Arg = PtrOff;
4043     }
4044
4045     if (VA.isRegLoc()) {
4046       if (Arg.getValueType() == MVT::i1)
4047         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4048
4049       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4050       // Put argument in a physical register.
4051       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4052     } else {
4053       // Put argument in the parameter list area of the current stack frame.
4054       assert(VA.isMemLoc());
4055       unsigned LocMemOffset = VA.getLocMemOffset();
4056
4057       if (!isTailCall) {
4058         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4059         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4060
4061         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4062                                            MachinePointerInfo(),
4063                                            false, false, 0));
4064       } else {
4065         // Calculate and remember argument location.
4066         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4067                                  TailCallArguments);
4068       }
4069     }
4070   }
4071
4072   if (!MemOpChains.empty())
4073     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4074
4075   // Build a sequence of copy-to-reg nodes chained together with token chain
4076   // and flag operands which copy the outgoing args into the appropriate regs.
4077   SDValue InFlag;
4078   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4079     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4080                              RegsToPass[i].second, InFlag);
4081     InFlag = Chain.getValue(1);
4082   }
4083
4084   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4085   // registers.
4086   if (isVarArg) {
4087     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4088     SDValue Ops[] = { Chain, InFlag };
4089
4090     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4091                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4092
4093     InFlag = Chain.getValue(1);
4094   }
4095
4096   if (isTailCall)
4097     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4098                     false, TailCallArguments);
4099
4100   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4101                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4102                     Ins, InVals);
4103 }
4104
4105 // Copy an argument into memory, being careful to do this outside the
4106 // call sequence for the call to which the argument belongs.
4107 SDValue
4108 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4109                                               SDValue CallSeqStart,
4110                                               ISD::ArgFlagsTy Flags,
4111                                               SelectionDAG &DAG,
4112                                               SDLoc dl) const {
4113   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4114                         CallSeqStart.getNode()->getOperand(0),
4115                         Flags, DAG, dl);
4116   // The MEMCPY must go outside the CALLSEQ_START..END.
4117   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4118                              CallSeqStart.getNode()->getOperand(1),
4119                              SDLoc(MemcpyCall));
4120   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4121                          NewCallSeqStart.getNode());
4122   return NewCallSeqStart;
4123 }
4124
4125 SDValue
4126 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4127                                     CallingConv::ID CallConv, bool isVarArg,
4128                                     bool isTailCall,
4129                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4130                                     const SmallVectorImpl<SDValue> &OutVals,
4131                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4132                                     SDLoc dl, SelectionDAG &DAG,
4133                                     SmallVectorImpl<SDValue> &InVals) const {
4134
4135   bool isELFv2ABI = Subtarget.isELFv2ABI();
4136   bool isLittleEndian = Subtarget.isLittleEndian();
4137   unsigned NumOps = Outs.size();
4138
4139   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4140   unsigned PtrByteSize = 8;
4141
4142   MachineFunction &MF = DAG.getMachineFunction();
4143
4144   // Mark this function as potentially containing a function that contains a
4145   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4146   // and restoring the callers stack pointer in this functions epilog. This is
4147   // done because by tail calling the called function might overwrite the value
4148   // in this function's (MF) stack pointer stack slot 0(SP).
4149   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4150       CallConv == CallingConv::Fast)
4151     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4152
4153   // Count how many bytes are to be pushed on the stack, including the linkage
4154   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4155   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4156   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4157   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4158                                                           isELFv2ABI);
4159   unsigned NumBytes = LinkageSize;
4160
4161   // Add up all the space actually used.
4162   for (unsigned i = 0; i != NumOps; ++i) {
4163     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4164     EVT ArgVT = Outs[i].VT;
4165     EVT OrigVT = Outs[i].ArgVT;
4166
4167     /* Respect alignment of argument on the stack.  */
4168     unsigned Align =
4169       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4170     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4171
4172     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4173     if (Flags.isInConsecutiveRegsLast())
4174       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4175   }
4176
4177   unsigned NumBytesActuallyUsed = NumBytes;
4178
4179   // The prolog code of the callee may store up to 8 GPR argument registers to
4180   // the stack, allowing va_start to index over them in memory if its varargs.
4181   // Because we cannot tell if this is needed on the caller side, we have to
4182   // conservatively assume that it is needed.  As such, make sure we have at
4183   // least enough stack space for the caller to store the 8 GPRs.
4184   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4185   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4186
4187   // Tail call needs the stack to be aligned.
4188   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4189       CallConv == CallingConv::Fast)
4190     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4191
4192   // Calculate by how many bytes the stack has to be adjusted in case of tail
4193   // call optimization.
4194   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4195
4196   // To protect arguments on the stack from being clobbered in a tail call,
4197   // force all the loads to happen before doing any other lowering.
4198   if (isTailCall)
4199     Chain = DAG.getStackArgumentTokenFactor(Chain);
4200
4201   // Adjust the stack pointer for the new arguments...
4202   // These operations are automatically eliminated by the prolog/epilog pass
4203   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4204                                dl);
4205   SDValue CallSeqStart = Chain;
4206
4207   // Load the return address and frame pointer so it can be move somewhere else
4208   // later.
4209   SDValue LROp, FPOp;
4210   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4211                                        dl);
4212
4213   // Set up a copy of the stack pointer for use loading and storing any
4214   // arguments that may not fit in the registers available for argument
4215   // passing.
4216   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4217
4218   // Figure out which arguments are going to go in registers, and which in
4219   // memory.  Also, if this is a vararg function, floating point operations
4220   // must be stored to our stack, and loaded into integer regs as well, if
4221   // any integer regs are available for argument passing.
4222   unsigned ArgOffset = LinkageSize;
4223   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4224
4225   static const MCPhysReg GPR[] = {
4226     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4227     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4228   };
4229   static const MCPhysReg *FPR = GetFPR();
4230
4231   static const MCPhysReg VR[] = {
4232     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4233     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4234   };
4235   static const MCPhysReg VSRH[] = {
4236     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4237     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4238   };
4239
4240   const unsigned NumGPRs = array_lengthof(GPR);
4241   const unsigned NumFPRs = 13;
4242   const unsigned NumVRs  = array_lengthof(VR);
4243
4244   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4245   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4246
4247   SmallVector<SDValue, 8> MemOpChains;
4248   for (unsigned i = 0; i != NumOps; ++i) {
4249     SDValue Arg = OutVals[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     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4258
4259     /* Compute GPR index associated with argument offset.  */
4260     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4261     GPR_idx = std::min(GPR_idx, NumGPRs);
4262
4263     // PtrOff will be used to store the current argument to the stack if a
4264     // register cannot be found for it.
4265     SDValue PtrOff;
4266
4267     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4268
4269     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4270
4271     // Promote integers to 64-bit values.
4272     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4273       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4274       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4275       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4276     }
4277
4278     // FIXME memcpy is used way more than necessary.  Correctness first.
4279     // Note: "by value" is code for passing a structure by value, not
4280     // basic types.
4281     if (Flags.isByVal()) {
4282       // Note: Size includes alignment padding, so
4283       //   struct x { short a; char b; }
4284       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4285       // These are the proper values we need for right-justifying the
4286       // aggregate in a parameter register.
4287       unsigned Size = Flags.getByValSize();
4288
4289       // An empty aggregate parameter takes up no storage and no
4290       // registers.
4291       if (Size == 0)
4292         continue;
4293
4294       // All aggregates smaller than 8 bytes must be passed right-justified.
4295       if (Size==1 || Size==2 || Size==4) {
4296         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4297         if (GPR_idx != NumGPRs) {
4298           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4299                                         MachinePointerInfo(), VT,
4300                                         false, false, 0);
4301           MemOpChains.push_back(Load.getValue(1));
4302           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4303
4304           ArgOffset += PtrByteSize;
4305           continue;
4306         }
4307       }
4308
4309       if (GPR_idx == NumGPRs && Size < 8) {
4310         SDValue AddPtr = PtrOff;
4311         if (!isLittleEndian) {
4312           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4313                                           PtrOff.getValueType());
4314           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4315         }
4316         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4317                                                           CallSeqStart,
4318                                                           Flags, DAG, dl);
4319         ArgOffset += PtrByteSize;
4320         continue;
4321       }
4322       // Copy entire object into memory.  There are cases where gcc-generated
4323       // code assumes it is there, even if it could be put entirely into
4324       // registers.  (This is not what the doc says.)
4325
4326       // FIXME: The above statement is likely due to a misunderstanding of the
4327       // documents.  All arguments must be copied into the parameter area BY
4328       // THE CALLEE in the event that the callee takes the address of any
4329       // formal argument.  That has not yet been implemented.  However, it is
4330       // reasonable to use the stack area as a staging area for the register
4331       // load.
4332
4333       // Skip this for small aggregates, as we will use the same slot for a
4334       // right-justified copy, below.
4335       if (Size >= 8)
4336         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4337                                                           CallSeqStart,
4338                                                           Flags, DAG, dl);
4339
4340       // When a register is available, pass a small aggregate right-justified.
4341       if (Size < 8 && GPR_idx != NumGPRs) {
4342         // The easiest way to get this right-justified in a register
4343         // is to copy the structure into the rightmost portion of a
4344         // local variable slot, then load the whole slot into the
4345         // register.
4346         // FIXME: The memcpy seems to produce pretty awful code for
4347         // small aggregates, particularly for packed ones.
4348         // FIXME: It would be preferable to use the slot in the
4349         // parameter save area instead of a new local variable.
4350         SDValue AddPtr = PtrOff;
4351         if (!isLittleEndian) {
4352           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4353           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4354         }
4355         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4356                                                           CallSeqStart,
4357                                                           Flags, DAG, dl);
4358
4359         // Load the slot into the register.
4360         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4361                                    MachinePointerInfo(),
4362                                    false, false, false, 0);
4363         MemOpChains.push_back(Load.getValue(1));
4364         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4365
4366         // Done with this argument.
4367         ArgOffset += PtrByteSize;
4368         continue;
4369       }
4370
4371       // For aggregates larger than PtrByteSize, copy the pieces of the
4372       // object that fit into registers from the parameter save area.
4373       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4374         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4375         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4376         if (GPR_idx != NumGPRs) {
4377           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4378                                      MachinePointerInfo(),
4379                                      false, false, false, 0);
4380           MemOpChains.push_back(Load.getValue(1));
4381           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4382           ArgOffset += PtrByteSize;
4383         } else {
4384           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4385           break;
4386         }
4387       }
4388       continue;
4389     }
4390
4391     switch (Arg.getSimpleValueType().SimpleTy) {
4392     default: llvm_unreachable("Unexpected ValueType for argument!");
4393     case MVT::i1:
4394     case MVT::i32:
4395     case MVT::i64:
4396       // These can be scalar arguments or elements of an integer array type
4397       // passed directly.  Clang may use those instead of "byval" aggregate
4398       // types to avoid forcing arguments to memory unnecessarily.
4399       if (GPR_idx != NumGPRs) {
4400         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4401       } else {
4402         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4403                          true, isTailCall, false, MemOpChains,
4404                          TailCallArguments, dl);
4405       }
4406       ArgOffset += PtrByteSize;
4407       break;
4408     case MVT::f32:
4409     case MVT::f64: {
4410       // These can be scalar arguments or elements of a float array type
4411       // passed directly.  The latter are used to implement ELFv2 homogenous
4412       // float aggregates.
4413
4414       // Named arguments go into FPRs first, and once they overflow, the
4415       // remaining arguments go into GPRs and then the parameter save area.
4416       // Unnamed arguments for vararg functions always go to GPRs and
4417       // then the parameter save area.  For now, put all arguments to vararg
4418       // routines always in both locations (FPR *and* GPR or stack slot).
4419       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4420
4421       // First load the argument into the next available FPR.
4422       if (FPR_idx != NumFPRs)
4423         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4424
4425       // Next, load the argument into GPR or stack slot if needed.
4426       if (!NeedGPROrStack)
4427         ;
4428       else if (GPR_idx != NumGPRs) {
4429         // In the non-vararg case, this can only ever happen in the
4430         // presence of f32 array types, since otherwise we never run
4431         // out of FPRs before running out of GPRs.
4432         SDValue ArgVal;
4433
4434         // Double values are always passed in a single GPR.
4435         if (Arg.getValueType() != MVT::f32) {
4436           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4437
4438         // Non-array float values are extended and passed in a GPR.
4439         } else if (!Flags.isInConsecutiveRegs()) {
4440           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4441           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4442
4443         // If we have an array of floats, we collect every odd element
4444         // together with its predecessor into one GPR.
4445         } else if (ArgOffset % PtrByteSize != 0) {
4446           SDValue Lo, Hi;
4447           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4448           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4449           if (!isLittleEndian)
4450             std::swap(Lo, Hi);
4451           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4452
4453         // The final element, if even, goes into the first half of a GPR.
4454         } else if (Flags.isInConsecutiveRegsLast()) {
4455           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4456           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4457           if (!isLittleEndian)
4458             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4459                                  DAG.getConstant(32, MVT::i32));
4460
4461         // Non-final even elements are skipped; they will be handled
4462         // together the with subsequent argument on the next go-around.
4463         } else
4464           ArgVal = SDValue();
4465
4466         if (ArgVal.getNode())
4467           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4468       } else {
4469         // Single-precision floating-point values are mapped to the
4470         // second (rightmost) word of the stack doubleword.
4471         if (Arg.getValueType() == MVT::f32 &&
4472             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4473           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4474           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4475         }
4476
4477         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4478                          true, isTailCall, false, MemOpChains,
4479                          TailCallArguments, dl);
4480       }
4481       // When passing an array of floats, the array occupies consecutive
4482       // space in the argument area; only round up to the next doubleword
4483       // at the end of the array.  Otherwise, each float takes 8 bytes.
4484       ArgOffset += (Arg.getValueType() == MVT::f32 &&
4485                     Flags.isInConsecutiveRegs()) ? 4 : 8;
4486       if (Flags.isInConsecutiveRegsLast())
4487         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4488       break;
4489     }
4490     case MVT::v4f32:
4491     case MVT::v4i32:
4492     case MVT::v8i16:
4493     case MVT::v16i8:
4494     case MVT::v2f64:
4495     case MVT::v2i64:
4496       // These can be scalar arguments or elements of a vector array type
4497       // passed directly.  The latter are used to implement ELFv2 homogenous
4498       // vector aggregates.
4499
4500       // For a varargs call, named arguments go into VRs or on the stack as
4501       // usual; unnamed arguments always go to the stack or the corresponding
4502       // GPRs when within range.  For now, we always put the value in both
4503       // locations (or even all three).
4504       if (isVarArg) {
4505         // We could elide this store in the case where the object fits
4506         // entirely in R registers.  Maybe later.
4507         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4508                                      MachinePointerInfo(), false, false, 0);
4509         MemOpChains.push_back(Store);
4510         if (VR_idx != NumVRs) {
4511           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4512                                      MachinePointerInfo(),
4513                                      false, false, false, 0);
4514           MemOpChains.push_back(Load.getValue(1));
4515
4516           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4517                            Arg.getSimpleValueType() == MVT::v2i64) ?
4518                           VSRH[VR_idx] : VR[VR_idx];
4519           ++VR_idx;
4520
4521           RegsToPass.push_back(std::make_pair(VReg, Load));
4522         }
4523         ArgOffset += 16;
4524         for (unsigned i=0; i<16; i+=PtrByteSize) {
4525           if (GPR_idx == NumGPRs)
4526             break;
4527           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4528                                   DAG.getConstant(i, PtrVT));
4529           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4530                                      false, false, false, 0);
4531           MemOpChains.push_back(Load.getValue(1));
4532           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4533         }
4534         break;
4535       }
4536
4537       // Non-varargs Altivec params go into VRs or on the stack.
4538       if (VR_idx != NumVRs) {
4539         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4540                          Arg.getSimpleValueType() == MVT::v2i64) ?
4541                         VSRH[VR_idx] : VR[VR_idx];
4542         ++VR_idx;
4543
4544         RegsToPass.push_back(std::make_pair(VReg, Arg));
4545       } else {
4546         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4547                          true, isTailCall, true, MemOpChains,
4548                          TailCallArguments, dl);
4549       }
4550       ArgOffset += 16;
4551       break;
4552     }
4553   }
4554
4555   assert(NumBytesActuallyUsed == ArgOffset);
4556   (void)NumBytesActuallyUsed;
4557
4558   if (!MemOpChains.empty())
4559     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4560
4561   // Check if this is an indirect call (MTCTR/BCTRL).
4562   // See PrepareCall() for more information about calls through function
4563   // pointers in the 64-bit SVR4 ABI.
4564   if (!isTailCall &&
4565       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4566       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4567     // Load r2 into a virtual register and store it to the TOC save area.
4568     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4569     // TOC save area offset.
4570     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4571     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4572     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4573     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4574                          false, false, 0);
4575     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4576     // This does not mean the MTCTR instruction must use R12; it's easier
4577     // to model this as an extra parameter, so do that.
4578     if (isELFv2ABI)
4579       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4580   }
4581
4582   // Build a sequence of copy-to-reg nodes chained together with token chain
4583   // and flag operands which copy the outgoing args into the appropriate regs.
4584   SDValue InFlag;
4585   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4586     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4587                              RegsToPass[i].second, InFlag);
4588     InFlag = Chain.getValue(1);
4589   }
4590
4591   if (isTailCall)
4592     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4593                     FPOp, true, TailCallArguments);
4594
4595   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4596                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4597                     Ins, InVals);
4598 }
4599
4600 SDValue
4601 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4602                                     CallingConv::ID CallConv, bool isVarArg,
4603                                     bool isTailCall,
4604                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4605                                     const SmallVectorImpl<SDValue> &OutVals,
4606                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4607                                     SDLoc dl, SelectionDAG &DAG,
4608                                     SmallVectorImpl<SDValue> &InVals) const {
4609
4610   unsigned NumOps = Outs.size();
4611
4612   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4613   bool isPPC64 = PtrVT == MVT::i64;
4614   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4615
4616   MachineFunction &MF = DAG.getMachineFunction();
4617
4618   // Mark this function as potentially containing a function that contains a
4619   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4620   // and restoring the callers stack pointer in this functions epilog. This is
4621   // done because by tail calling the called function might overwrite the value
4622   // in this function's (MF) stack pointer stack slot 0(SP).
4623   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4624       CallConv == CallingConv::Fast)
4625     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4626
4627   // Count how many bytes are to be pushed on the stack, including the linkage
4628   // area, and parameter passing area.  We start with 24/48 bytes, which is
4629   // prereserved space for [SP][CR][LR][3 x unused].
4630   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4631                                                           false);
4632   unsigned NumBytes = LinkageSize;
4633
4634   // Add up all the space actually used.
4635   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4636   // they all go in registers, but we must reserve stack space for them for
4637   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4638   // assigned stack space in order, with padding so Altivec parameters are
4639   // 16-byte aligned.
4640   unsigned nAltivecParamsAtEnd = 0;
4641   for (unsigned i = 0; i != NumOps; ++i) {
4642     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4643     EVT ArgVT = Outs[i].VT;
4644     // Varargs Altivec parameters are padded to a 16 byte boundary.
4645     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4646         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4647         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4648       if (!isVarArg && !isPPC64) {
4649         // Non-varargs Altivec parameters go after all the non-Altivec
4650         // parameters; handle those later so we know how much padding we need.
4651         nAltivecParamsAtEnd++;
4652         continue;
4653       }
4654       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4655       NumBytes = ((NumBytes+15)/16)*16;
4656     }
4657     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4658   }
4659
4660   // Allow for Altivec parameters at the end, if needed.
4661   if (nAltivecParamsAtEnd) {
4662     NumBytes = ((NumBytes+15)/16)*16;
4663     NumBytes += 16*nAltivecParamsAtEnd;
4664   }
4665
4666   // The prolog code of the callee may store up to 8 GPR argument registers to
4667   // the stack, allowing va_start to index over them in memory if its varargs.
4668   // Because we cannot tell if this is needed on the caller side, we have to
4669   // conservatively assume that it is needed.  As such, make sure we have at
4670   // least enough stack space for the caller to store the 8 GPRs.
4671   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4672
4673   // Tail call needs the stack to be aligned.
4674   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4675       CallConv == CallingConv::Fast)
4676     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4677
4678   // Calculate by how many bytes the stack has to be adjusted in case of tail
4679   // call optimization.
4680   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4681
4682   // To protect arguments on the stack from being clobbered in a tail call,
4683   // force all the loads to happen before doing any other lowering.
4684   if (isTailCall)
4685     Chain = DAG.getStackArgumentTokenFactor(Chain);
4686
4687   // Adjust the stack pointer for the new arguments...
4688   // These operations are automatically eliminated by the prolog/epilog pass
4689   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4690                                dl);
4691   SDValue CallSeqStart = Chain;
4692
4693   // Load the return address and frame pointer so it can be move somewhere else
4694   // later.
4695   SDValue LROp, FPOp;
4696   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4697                                        dl);
4698
4699   // Set up a copy of the stack pointer for use loading and storing any
4700   // arguments that may not fit in the registers available for argument
4701   // passing.
4702   SDValue StackPtr;
4703   if (isPPC64)
4704     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4705   else
4706     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4707
4708   // Figure out which arguments are going to go in registers, and which in
4709   // memory.  Also, if this is a vararg function, floating point operations
4710   // must be stored to our stack, and loaded into integer regs as well, if
4711   // any integer regs are available for argument passing.
4712   unsigned ArgOffset = LinkageSize;
4713   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4714
4715   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4716     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4717     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4718   };
4719   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4720     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4721     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4722   };
4723   static const MCPhysReg *FPR = GetFPR();
4724
4725   static const MCPhysReg VR[] = {
4726     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4727     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4728   };
4729   const unsigned NumGPRs = array_lengthof(GPR_32);
4730   const unsigned NumFPRs = 13;
4731   const unsigned NumVRs  = array_lengthof(VR);
4732
4733   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4734
4735   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4736   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4737
4738   SmallVector<SDValue, 8> MemOpChains;
4739   for (unsigned i = 0; i != NumOps; ++i) {
4740     SDValue Arg = OutVals[i];
4741     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4742
4743     // PtrOff will be used to store the current argument to the stack if a
4744     // register cannot be found for it.
4745     SDValue PtrOff;
4746
4747     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4748
4749     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4750
4751     // On PPC64, promote integers to 64-bit values.
4752     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4753       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4754       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4755       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4756     }
4757
4758     // FIXME memcpy is used way more than necessary.  Correctness first.
4759     // Note: "by value" is code for passing a structure by value, not
4760     // basic types.
4761     if (Flags.isByVal()) {
4762       unsigned Size = Flags.getByValSize();
4763       // Very small objects are passed right-justified.  Everything else is
4764       // passed left-justified.
4765       if (Size==1 || Size==2) {
4766         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4767         if (GPR_idx != NumGPRs) {
4768           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4769                                         MachinePointerInfo(), VT,
4770                                         false, false, 0);
4771           MemOpChains.push_back(Load.getValue(1));
4772           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4773
4774           ArgOffset += PtrByteSize;
4775         } else {
4776           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4777                                           PtrOff.getValueType());
4778           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4779           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4780                                                             CallSeqStart,
4781                                                             Flags, DAG, dl);
4782           ArgOffset += PtrByteSize;
4783         }
4784         continue;
4785       }
4786       // Copy entire object into memory.  There are cases where gcc-generated
4787       // code assumes it is there, even if it could be put entirely into
4788       // registers.  (This is not what the doc says.)
4789       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4790                                                         CallSeqStart,
4791                                                         Flags, DAG, dl);
4792
4793       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4794       // copy the pieces of the object that fit into registers from the
4795       // parameter save area.
4796       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4797         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4798         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4799         if (GPR_idx != NumGPRs) {
4800           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4801                                      MachinePointerInfo(),
4802                                      false, false, false, 0);
4803           MemOpChains.push_back(Load.getValue(1));
4804           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4805           ArgOffset += PtrByteSize;
4806         } else {
4807           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4808           break;
4809         }
4810       }
4811       continue;
4812     }
4813
4814     switch (Arg.getSimpleValueType().SimpleTy) {
4815     default: llvm_unreachable("Unexpected ValueType for argument!");
4816     case MVT::i1:
4817     case MVT::i32:
4818     case MVT::i64:
4819       if (GPR_idx != NumGPRs) {
4820         if (Arg.getValueType() == MVT::i1)
4821           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4822
4823         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4824       } else {
4825         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4826                          isPPC64, isTailCall, false, MemOpChains,
4827                          TailCallArguments, dl);
4828       }
4829       ArgOffset += PtrByteSize;
4830       break;
4831     case MVT::f32:
4832     case MVT::f64:
4833       if (FPR_idx != NumFPRs) {
4834         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4835
4836         if (isVarArg) {
4837           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4838                                        MachinePointerInfo(), false, false, 0);
4839           MemOpChains.push_back(Store);
4840
4841           // Float varargs are always shadowed in available integer registers
4842           if (GPR_idx != NumGPRs) {
4843             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4844                                        MachinePointerInfo(), false, false,
4845                                        false, 0);
4846             MemOpChains.push_back(Load.getValue(1));
4847             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4848           }
4849           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4850             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4851             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4852             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4853                                        MachinePointerInfo(),
4854                                        false, false, false, 0);
4855             MemOpChains.push_back(Load.getValue(1));
4856             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4857           }
4858         } else {
4859           // If we have any FPRs remaining, we may also have GPRs remaining.
4860           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4861           // GPRs.
4862           if (GPR_idx != NumGPRs)
4863             ++GPR_idx;
4864           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4865               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4866             ++GPR_idx;
4867         }
4868       } else
4869         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4870                          isPPC64, isTailCall, false, MemOpChains,
4871                          TailCallArguments, dl);
4872       if (isPPC64)
4873         ArgOffset += 8;
4874       else
4875         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4876       break;
4877     case MVT::v4f32:
4878     case MVT::v4i32:
4879     case MVT::v8i16:
4880     case MVT::v16i8:
4881       if (isVarArg) {
4882         // These go aligned on the stack, or in the corresponding R registers
4883         // when within range.  The Darwin PPC ABI doc claims they also go in
4884         // V registers; in fact gcc does this only for arguments that are
4885         // prototyped, not for those that match the ...  We do it for all
4886         // arguments, seems to work.
4887         while (ArgOffset % 16 !=0) {
4888           ArgOffset += PtrByteSize;
4889           if (GPR_idx != NumGPRs)
4890             GPR_idx++;
4891         }
4892         // We could elide this store in the case where the object fits
4893         // entirely in R registers.  Maybe later.
4894         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4895                             DAG.getConstant(ArgOffset, PtrVT));
4896         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4897                                      MachinePointerInfo(), false, false, 0);
4898         MemOpChains.push_back(Store);
4899         if (VR_idx != NumVRs) {
4900           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4901                                      MachinePointerInfo(),
4902                                      false, false, false, 0);
4903           MemOpChains.push_back(Load.getValue(1));
4904           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4905         }
4906         ArgOffset += 16;
4907         for (unsigned i=0; i<16; i+=PtrByteSize) {
4908           if (GPR_idx == NumGPRs)
4909             break;
4910           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4911                                   DAG.getConstant(i, PtrVT));
4912           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4913                                      false, false, false, 0);
4914           MemOpChains.push_back(Load.getValue(1));
4915           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4916         }
4917         break;
4918       }
4919
4920       // Non-varargs Altivec params generally go in registers, but have
4921       // stack space allocated at the end.
4922       if (VR_idx != NumVRs) {
4923         // Doesn't have GPR space allocated.
4924         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4925       } else if (nAltivecParamsAtEnd==0) {
4926         // We are emitting Altivec params in order.
4927         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4928                          isPPC64, isTailCall, true, MemOpChains,
4929                          TailCallArguments, dl);
4930         ArgOffset += 16;
4931       }
4932       break;
4933     }
4934   }
4935   // If all Altivec parameters fit in registers, as they usually do,
4936   // they get stack space following the non-Altivec parameters.  We
4937   // don't track this here because nobody below needs it.
4938   // If there are more Altivec parameters than fit in registers emit
4939   // the stores here.
4940   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4941     unsigned j = 0;
4942     // Offset is aligned; skip 1st 12 params which go in V registers.
4943     ArgOffset = ((ArgOffset+15)/16)*16;
4944     ArgOffset += 12*16;
4945     for (unsigned i = 0; i != NumOps; ++i) {
4946       SDValue Arg = OutVals[i];
4947       EVT ArgType = Outs[i].VT;
4948       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4949           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4950         if (++j > NumVRs) {
4951           SDValue PtrOff;
4952           // We are emitting Altivec params in order.
4953           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4954                            isPPC64, isTailCall, true, MemOpChains,
4955                            TailCallArguments, dl);
4956           ArgOffset += 16;
4957         }
4958       }
4959     }
4960   }
4961
4962   if (!MemOpChains.empty())
4963     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4964
4965   // On Darwin, R12 must contain the address of an indirect callee.  This does
4966   // not mean the MTCTR instruction must use R12; it's easier to model this as
4967   // an extra parameter, so do that.
4968   if (!isTailCall &&
4969       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4970       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4971       !isBLACompatibleAddress(Callee, DAG))
4972     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4973                                                    PPC::R12), Callee));
4974
4975   // Build a sequence of copy-to-reg nodes chained together with token chain
4976   // and flag operands which copy the outgoing args into the appropriate regs.
4977   SDValue InFlag;
4978   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4979     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4980                              RegsToPass[i].second, InFlag);
4981     InFlag = Chain.getValue(1);
4982   }
4983
4984   if (isTailCall)
4985     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4986                     FPOp, true, TailCallArguments);
4987
4988   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4989                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4990                     Ins, InVals);
4991 }
4992
4993 bool
4994 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4995                                   MachineFunction &MF, bool isVarArg,
4996                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
4997                                   LLVMContext &Context) const {
4998   SmallVector<CCValAssign, 16> RVLocs;
4999   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
5000                  RVLocs, Context);
5001   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5002 }
5003
5004 SDValue
5005 PPCTargetLowering::LowerReturn(SDValue Chain,
5006                                CallingConv::ID CallConv, bool isVarArg,
5007                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5008                                const SmallVectorImpl<SDValue> &OutVals,
5009                                SDLoc dl, SelectionDAG &DAG) const {
5010
5011   SmallVector<CCValAssign, 16> RVLocs;
5012   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
5013                  getTargetMachine(), RVLocs, *DAG.getContext());
5014   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5015
5016   SDValue Flag;
5017   SmallVector<SDValue, 4> RetOps(1, Chain);
5018
5019   // Copy the result values into the output registers.
5020   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5021     CCValAssign &VA = RVLocs[i];
5022     assert(VA.isRegLoc() && "Can only return in registers!");
5023
5024     SDValue Arg = OutVals[i];
5025
5026     switch (VA.getLocInfo()) {
5027     default: llvm_unreachable("Unknown loc info!");
5028     case CCValAssign::Full: break;
5029     case CCValAssign::AExt:
5030       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5031       break;
5032     case CCValAssign::ZExt:
5033       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5034       break;
5035     case CCValAssign::SExt:
5036       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5037       break;
5038     }
5039
5040     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5041     Flag = Chain.getValue(1);
5042     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5043   }
5044
5045   RetOps[0] = Chain;  // Update chain.
5046
5047   // Add the flag if we have it.
5048   if (Flag.getNode())
5049     RetOps.push_back(Flag);
5050
5051   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5052 }
5053
5054 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5055                                    const PPCSubtarget &Subtarget) const {
5056   // When we pop the dynamic allocation we need to restore the SP link.
5057   SDLoc dl(Op);
5058
5059   // Get the corect type for pointers.
5060   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5061
5062   // Construct the stack pointer operand.
5063   bool isPPC64 = Subtarget.isPPC64();
5064   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5065   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5066
5067   // Get the operands for the STACKRESTORE.
5068   SDValue Chain = Op.getOperand(0);
5069   SDValue SaveSP = Op.getOperand(1);
5070
5071   // Load the old link SP.
5072   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5073                                    MachinePointerInfo(),
5074                                    false, false, false, 0);
5075
5076   // Restore the stack pointer.
5077   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5078
5079   // Store the old link SP.
5080   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5081                       false, false, 0);
5082 }
5083
5084
5085
5086 SDValue
5087 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5088   MachineFunction &MF = DAG.getMachineFunction();
5089   bool isPPC64 = Subtarget.isPPC64();
5090   bool isDarwinABI = Subtarget.isDarwinABI();
5091   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5092
5093   // Get current frame pointer save index.  The users of this index will be
5094   // primarily DYNALLOC instructions.
5095   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5096   int RASI = FI->getReturnAddrSaveIndex();
5097
5098   // If the frame pointer save index hasn't been defined yet.
5099   if (!RASI) {
5100     // Find out what the fix offset of the frame pointer save area.
5101     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5102     // Allocate the frame index for frame pointer save area.
5103     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
5104     // Save the result.
5105     FI->setReturnAddrSaveIndex(RASI);
5106   }
5107   return DAG.getFrameIndex(RASI, PtrVT);
5108 }
5109
5110 SDValue
5111 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5112   MachineFunction &MF = DAG.getMachineFunction();
5113   bool isPPC64 = Subtarget.isPPC64();
5114   bool isDarwinABI = Subtarget.isDarwinABI();
5115   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5116
5117   // Get current frame pointer save index.  The users of this index will be
5118   // primarily DYNALLOC instructions.
5119   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5120   int FPSI = FI->getFramePointerSaveIndex();
5121
5122   // If the frame pointer save index hasn't been defined yet.
5123   if (!FPSI) {
5124     // Find out what the fix offset of the frame pointer save area.
5125     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5126                                                            isDarwinABI);
5127
5128     // Allocate the frame index for frame pointer save area.
5129     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5130     // Save the result.
5131     FI->setFramePointerSaveIndex(FPSI);
5132   }
5133   return DAG.getFrameIndex(FPSI, PtrVT);
5134 }
5135
5136 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5137                                          SelectionDAG &DAG,
5138                                          const PPCSubtarget &Subtarget) const {
5139   // Get the inputs.
5140   SDValue Chain = Op.getOperand(0);
5141   SDValue Size  = Op.getOperand(1);
5142   SDLoc dl(Op);
5143
5144   // Get the corect type for pointers.
5145   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5146   // Negate the size.
5147   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5148                                   DAG.getConstant(0, PtrVT), Size);
5149   // Construct a node for the frame pointer save index.
5150   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5151   // Build a DYNALLOC node.
5152   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5153   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5154   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5155 }
5156
5157 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5158                                                SelectionDAG &DAG) const {
5159   SDLoc DL(Op);
5160   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5161                      DAG.getVTList(MVT::i32, MVT::Other),
5162                      Op.getOperand(0), Op.getOperand(1));
5163 }
5164
5165 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5166                                                 SelectionDAG &DAG) const {
5167   SDLoc DL(Op);
5168   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5169                      Op.getOperand(0), Op.getOperand(1));
5170 }
5171
5172 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5173   assert(Op.getValueType() == MVT::i1 &&
5174          "Custom lowering only for i1 loads");
5175
5176   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5177
5178   SDLoc dl(Op);
5179   LoadSDNode *LD = cast<LoadSDNode>(Op);
5180
5181   SDValue Chain = LD->getChain();
5182   SDValue BasePtr = LD->getBasePtr();
5183   MachineMemOperand *MMO = LD->getMemOperand();
5184
5185   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5186                                  BasePtr, MVT::i8, MMO);
5187   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5188
5189   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5190   return DAG.getMergeValues(Ops, dl);
5191 }
5192
5193 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5194   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5195          "Custom lowering only for i1 stores");
5196
5197   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5198
5199   SDLoc dl(Op);
5200   StoreSDNode *ST = cast<StoreSDNode>(Op);
5201
5202   SDValue Chain = ST->getChain();
5203   SDValue BasePtr = ST->getBasePtr();
5204   SDValue Value = ST->getValue();
5205   MachineMemOperand *MMO = ST->getMemOperand();
5206
5207   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5208   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5209 }
5210
5211 // FIXME: Remove this once the ANDI glue bug is fixed:
5212 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5213   assert(Op.getValueType() == MVT::i1 &&
5214          "Custom lowering only for i1 results");
5215
5216   SDLoc DL(Op);
5217   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5218                      Op.getOperand(0));
5219 }
5220
5221 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5222 /// possible.
5223 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5224   // Not FP? Not a fsel.
5225   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5226       !Op.getOperand(2).getValueType().isFloatingPoint())
5227     return Op;
5228
5229   // We might be able to do better than this under some circumstances, but in
5230   // general, fsel-based lowering of select is a finite-math-only optimization.
5231   // For more information, see section F.3 of the 2.06 ISA specification.
5232   if (!DAG.getTarget().Options.NoInfsFPMath ||
5233       !DAG.getTarget().Options.NoNaNsFPMath)
5234     return Op;
5235
5236   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5237
5238   EVT ResVT = Op.getValueType();
5239   EVT CmpVT = Op.getOperand(0).getValueType();
5240   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5241   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5242   SDLoc dl(Op);
5243
5244   // If the RHS of the comparison is a 0.0, we don't need to do the
5245   // subtraction at all.
5246   SDValue Sel1;
5247   if (isFloatingPointZero(RHS))
5248     switch (CC) {
5249     default: break;       // SETUO etc aren't handled by fsel.
5250     case ISD::SETNE:
5251       std::swap(TV, FV);
5252     case ISD::SETEQ:
5253       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5254         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5255       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5256       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5257         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5258       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5259                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5260     case ISD::SETULT:
5261     case ISD::SETLT:
5262       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5263     case ISD::SETOGE:
5264     case ISD::SETGE:
5265       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5266         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5267       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5268     case ISD::SETUGT:
5269     case ISD::SETGT:
5270       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5271     case ISD::SETOLE:
5272     case ISD::SETLE:
5273       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5274         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5275       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5276                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5277     }
5278
5279   SDValue Cmp;
5280   switch (CC) {
5281   default: break;       // SETUO etc aren't handled by fsel.
5282   case ISD::SETNE:
5283     std::swap(TV, FV);
5284   case ISD::SETEQ:
5285     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5286     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5287       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5288     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5289     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5290       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5291     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5292                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5293   case ISD::SETULT:
5294   case ISD::SETLT:
5295     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5296     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5297       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5298     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5299   case ISD::SETOGE:
5300   case ISD::SETGE:
5301     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5302     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5303       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5304     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5305   case ISD::SETUGT:
5306   case ISD::SETGT:
5307     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5308     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5309       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5310     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5311   case ISD::SETOLE:
5312   case ISD::SETLE:
5313     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5314     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5315       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5316     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5317   }
5318   return Op;
5319 }
5320
5321 // FIXME: Split this code up when LegalizeDAGTypes lands.
5322 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5323                                            SDLoc dl) const {
5324   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5325   SDValue Src = Op.getOperand(0);
5326   if (Src.getValueType() == MVT::f32)
5327     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5328
5329   SDValue Tmp;
5330   switch (Op.getSimpleValueType().SimpleTy) {
5331   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5332   case MVT::i32:
5333     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5334                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5335                                                    PPCISD::FCTIDZ),
5336                       dl, MVT::f64, Src);
5337     break;
5338   case MVT::i64:
5339     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5340            "i64 FP_TO_UINT is supported only with FPCVT");
5341     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5342                                                         PPCISD::FCTIDUZ,
5343                       dl, MVT::f64, Src);
5344     break;
5345   }
5346
5347   // Convert the FP value to an int value through memory.
5348   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5349     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5350   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5351   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5352   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5353
5354   // Emit a store to the stack slot.
5355   SDValue Chain;
5356   if (i32Stack) {
5357     MachineFunction &MF = DAG.getMachineFunction();
5358     MachineMemOperand *MMO =
5359       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5360     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5361     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5362               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5363   } else
5364     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5365                          MPI, false, false, 0);
5366
5367   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5368   // add in a bias.
5369   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5370     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5371                         DAG.getConstant(4, FIPtr.getValueType()));
5372     MPI = MachinePointerInfo();
5373   }
5374
5375   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5376                      false, false, false, 0);
5377 }
5378
5379 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5380                                            SelectionDAG &DAG) const {
5381   SDLoc dl(Op);
5382   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5383   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5384     return SDValue();
5385
5386   if (Op.getOperand(0).getValueType() == MVT::i1)
5387     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5388                        DAG.getConstantFP(1.0, Op.getValueType()),
5389                        DAG.getConstantFP(0.0, Op.getValueType()));
5390
5391   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5392          "UINT_TO_FP is supported only with FPCVT");
5393
5394   // If we have FCFIDS, then use it when converting to single-precision.
5395   // Otherwise, convert to double-precision and then round.
5396   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5397                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5398                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5399                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5400                     PPCISD::FCFIDU : PPCISD::FCFID);
5401   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5402                    MVT::f32 : MVT::f64;
5403
5404   if (Op.getOperand(0).getValueType() == MVT::i64) {
5405     SDValue SINT = Op.getOperand(0);
5406     // When converting to single-precision, we actually need to convert
5407     // to double-precision first and then round to single-precision.
5408     // To avoid double-rounding effects during that operation, we have
5409     // to prepare the input operand.  Bits that might be truncated when
5410     // converting to double-precision are replaced by a bit that won't
5411     // be lost at this stage, but is below the single-precision rounding
5412     // position.
5413     //
5414     // However, if -enable-unsafe-fp-math is in effect, accept double
5415     // rounding to avoid the extra overhead.
5416     if (Op.getValueType() == MVT::f32 &&
5417         !Subtarget.hasFPCVT() &&
5418         !DAG.getTarget().Options.UnsafeFPMath) {
5419
5420       // Twiddle input to make sure the low 11 bits are zero.  (If this
5421       // is the case, we are guaranteed the value will fit into the 53 bit
5422       // mantissa of an IEEE double-precision value without rounding.)
5423       // If any of those low 11 bits were not zero originally, make sure
5424       // bit 12 (value 2048) is set instead, so that the final rounding
5425       // to single-precision gets the correct result.
5426       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5427                                   SINT, DAG.getConstant(2047, MVT::i64));
5428       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5429                           Round, DAG.getConstant(2047, MVT::i64));
5430       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5431       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5432                           Round, DAG.getConstant(-2048, MVT::i64));
5433
5434       // However, we cannot use that value unconditionally: if the magnitude
5435       // of the input value is small, the bit-twiddling we did above might
5436       // end up visibly changing the output.  Fortunately, in that case, we
5437       // don't need to twiddle bits since the original input will convert
5438       // exactly to double-precision floating-point already.  Therefore,
5439       // construct a conditional to use the original value if the top 11
5440       // bits are all sign-bit copies, and use the rounded value computed
5441       // above otherwise.
5442       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5443                                  SINT, DAG.getConstant(53, MVT::i32));
5444       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5445                          Cond, DAG.getConstant(1, MVT::i64));
5446       Cond = DAG.getSetCC(dl, MVT::i32,
5447                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5448
5449       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5450     }
5451
5452     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5453     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5454
5455     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5456       FP = DAG.getNode(ISD::FP_ROUND, dl,
5457                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5458     return FP;
5459   }
5460
5461   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5462          "Unhandled INT_TO_FP type in custom expander!");
5463   // Since we only generate this in 64-bit mode, we can take advantage of
5464   // 64-bit registers.  In particular, sign extend the input value into the
5465   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5466   // then lfd it and fcfid it.
5467   MachineFunction &MF = DAG.getMachineFunction();
5468   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5469   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5470
5471   SDValue Ld;
5472   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5473     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5474     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5475
5476     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5477                                  MachinePointerInfo::getFixedStack(FrameIdx),
5478                                  false, false, 0);
5479
5480     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5481            "Expected an i32 store");
5482     MachineMemOperand *MMO =
5483       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5484                               MachineMemOperand::MOLoad, 4, 4);
5485     SDValue Ops[] = { Store, FIdx };
5486     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5487                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5488                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5489                                  Ops, MVT::i32, MMO);
5490   } else {
5491     assert(Subtarget.isPPC64() &&
5492            "i32->FP without LFIWAX supported only on PPC64");
5493
5494     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5495     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5496
5497     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5498                                 Op.getOperand(0));
5499
5500     // STD the extended value into the stack slot.
5501     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5502                                  MachinePointerInfo::getFixedStack(FrameIdx),
5503                                  false, false, 0);
5504
5505     // Load the value as a double.
5506     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5507                      MachinePointerInfo::getFixedStack(FrameIdx),
5508                      false, false, false, 0);
5509   }
5510
5511   // FCFID it and return it.
5512   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5513   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5514     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5515   return FP;
5516 }
5517
5518 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5519                                             SelectionDAG &DAG) const {
5520   SDLoc dl(Op);
5521   /*
5522    The rounding mode is in bits 30:31 of FPSR, and has the following
5523    settings:
5524      00 Round to nearest
5525      01 Round to 0
5526      10 Round to +inf
5527      11 Round to -inf
5528
5529   FLT_ROUNDS, on the other hand, expects the following:
5530     -1 Undefined
5531      0 Round to 0
5532      1 Round to nearest
5533      2 Round to +inf
5534      3 Round to -inf
5535
5536   To perform the conversion, we do:
5537     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5538   */
5539
5540   MachineFunction &MF = DAG.getMachineFunction();
5541   EVT VT = Op.getValueType();
5542   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5543
5544   // Save FP Control Word to register
5545   EVT NodeTys[] = {
5546     MVT::f64,    // return register
5547     MVT::Glue    // unused in this context
5548   };
5549   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5550
5551   // Save FP register to stack slot
5552   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5553   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5554   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5555                                StackSlot, MachinePointerInfo(), false, false,0);
5556
5557   // Load FP Control Word from low 32 bits of stack slot.
5558   SDValue Four = DAG.getConstant(4, PtrVT);
5559   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5560   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5561                             false, false, false, 0);
5562
5563   // Transform as necessary
5564   SDValue CWD1 =
5565     DAG.getNode(ISD::AND, dl, MVT::i32,
5566                 CWD, DAG.getConstant(3, MVT::i32));
5567   SDValue CWD2 =
5568     DAG.getNode(ISD::SRL, dl, MVT::i32,
5569                 DAG.getNode(ISD::AND, dl, MVT::i32,
5570                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5571                                         CWD, DAG.getConstant(3, MVT::i32)),
5572                             DAG.getConstant(3, MVT::i32)),
5573                 DAG.getConstant(1, MVT::i32));
5574
5575   SDValue RetVal =
5576     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5577
5578   return DAG.getNode((VT.getSizeInBits() < 16 ?
5579                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5580 }
5581
5582 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5583   EVT VT = Op.getValueType();
5584   unsigned BitWidth = VT.getSizeInBits();
5585   SDLoc dl(Op);
5586   assert(Op.getNumOperands() == 3 &&
5587          VT == Op.getOperand(1).getValueType() &&
5588          "Unexpected SHL!");
5589
5590   // Expand into a bunch of logical ops.  Note that these ops
5591   // depend on the PPC behavior for oversized shift amounts.
5592   SDValue Lo = Op.getOperand(0);
5593   SDValue Hi = Op.getOperand(1);
5594   SDValue Amt = Op.getOperand(2);
5595   EVT AmtVT = Amt.getValueType();
5596
5597   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5598                              DAG.getConstant(BitWidth, AmtVT), Amt);
5599   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5600   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5601   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5602   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5603                              DAG.getConstant(-BitWidth, AmtVT));
5604   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5605   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5606   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5607   SDValue OutOps[] = { OutLo, OutHi };
5608   return DAG.getMergeValues(OutOps, dl);
5609 }
5610
5611 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5612   EVT VT = Op.getValueType();
5613   SDLoc dl(Op);
5614   unsigned BitWidth = VT.getSizeInBits();
5615   assert(Op.getNumOperands() == 3 &&
5616          VT == Op.getOperand(1).getValueType() &&
5617          "Unexpected SRL!");
5618
5619   // Expand into a bunch of logical ops.  Note that these ops
5620   // depend on the PPC behavior for oversized shift amounts.
5621   SDValue Lo = Op.getOperand(0);
5622   SDValue Hi = Op.getOperand(1);
5623   SDValue Amt = Op.getOperand(2);
5624   EVT AmtVT = Amt.getValueType();
5625
5626   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5627                              DAG.getConstant(BitWidth, AmtVT), Amt);
5628   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5629   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5630   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5631   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5632                              DAG.getConstant(-BitWidth, AmtVT));
5633   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5634   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5635   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5636   SDValue OutOps[] = { OutLo, OutHi };
5637   return DAG.getMergeValues(OutOps, dl);
5638 }
5639
5640 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5641   SDLoc dl(Op);
5642   EVT VT = Op.getValueType();
5643   unsigned BitWidth = VT.getSizeInBits();
5644   assert(Op.getNumOperands() == 3 &&
5645          VT == Op.getOperand(1).getValueType() &&
5646          "Unexpected SRA!");
5647
5648   // Expand into a bunch of logical ops, followed by a select_cc.
5649   SDValue Lo = Op.getOperand(0);
5650   SDValue Hi = Op.getOperand(1);
5651   SDValue Amt = Op.getOperand(2);
5652   EVT AmtVT = Amt.getValueType();
5653
5654   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5655                              DAG.getConstant(BitWidth, AmtVT), Amt);
5656   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5657   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5658   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5659   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5660                              DAG.getConstant(-BitWidth, AmtVT));
5661   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5662   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5663   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5664                                   Tmp4, Tmp6, ISD::SETLE);
5665   SDValue OutOps[] = { OutLo, OutHi };
5666   return DAG.getMergeValues(OutOps, dl);
5667 }
5668
5669 //===----------------------------------------------------------------------===//
5670 // Vector related lowering.
5671 //
5672
5673 /// BuildSplatI - Build a canonical splati of Val with an element size of
5674 /// SplatSize.  Cast the result to VT.
5675 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5676                              SelectionDAG &DAG, SDLoc dl) {
5677   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5678
5679   static const EVT VTys[] = { // canonical VT to use for each size.
5680     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5681   };
5682
5683   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5684
5685   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5686   if (Val == -1)
5687     SplatSize = 1;
5688
5689   EVT CanonicalVT = VTys[SplatSize-1];
5690
5691   // Build a canonical splat for this value.
5692   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5693   SmallVector<SDValue, 8> Ops;
5694   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5695   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5696   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5697 }
5698
5699 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5700 /// specified intrinsic ID.
5701 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5702                                 SelectionDAG &DAG, SDLoc dl,
5703                                 EVT DestVT = MVT::Other) {
5704   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5705   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5706                      DAG.getConstant(IID, MVT::i32), Op);
5707 }
5708
5709 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5710 /// specified intrinsic ID.
5711 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5712                                 SelectionDAG &DAG, SDLoc dl,
5713                                 EVT DestVT = MVT::Other) {
5714   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5715   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5716                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5717 }
5718
5719 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5720 /// specified intrinsic ID.
5721 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5722                                 SDValue Op2, SelectionDAG &DAG,
5723                                 SDLoc dl, EVT DestVT = MVT::Other) {
5724   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5725   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5726                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5727 }
5728
5729
5730 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5731 /// amount.  The result has the specified value type.
5732 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5733                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5734   // Force LHS/RHS to be the right type.
5735   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5736   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5737
5738   int Ops[16];
5739   for (unsigned i = 0; i != 16; ++i)
5740     Ops[i] = i + Amt;
5741   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5742   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5743 }
5744
5745 // If this is a case we can't handle, return null and let the default
5746 // expansion code take care of it.  If we CAN select this case, and if it
5747 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5748 // this case more efficiently than a constant pool load, lower it to the
5749 // sequence of ops that should be used.
5750 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5751                                              SelectionDAG &DAG) const {
5752   SDLoc dl(Op);
5753   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5754   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5755
5756   // Check if this is a splat of a constant value.
5757   APInt APSplatBits, APSplatUndef;
5758   unsigned SplatBitSize;
5759   bool HasAnyUndefs;
5760   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5761                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5762     return SDValue();
5763
5764   unsigned SplatBits = APSplatBits.getZExtValue();
5765   unsigned SplatUndef = APSplatUndef.getZExtValue();
5766   unsigned SplatSize = SplatBitSize / 8;
5767
5768   // First, handle single instruction cases.
5769
5770   // All zeros?
5771   if (SplatBits == 0) {
5772     // Canonicalize all zero vectors to be v4i32.
5773     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5774       SDValue Z = DAG.getConstant(0, MVT::i32);
5775       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5776       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5777     }
5778     return Op;
5779   }
5780
5781   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5782   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5783                     (32-SplatBitSize));
5784   if (SextVal >= -16 && SextVal <= 15)
5785     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5786
5787
5788   // Two instruction sequences.
5789
5790   // If this value is in the range [-32,30] and is even, use:
5791   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5792   // If this value is in the range [17,31] and is odd, use:
5793   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5794   // If this value is in the range [-31,-17] and is odd, use:
5795   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5796   // Note the last two are three-instruction sequences.
5797   if (SextVal >= -32 && SextVal <= 31) {
5798     // To avoid having these optimizations undone by constant folding,
5799     // we convert to a pseudo that will be expanded later into one of
5800     // the above forms.
5801     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5802     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5803               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5804     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5805     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5806     if (VT == Op.getValueType())
5807       return RetVal;
5808     else
5809       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5810   }
5811
5812   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5813   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5814   // for fneg/fabs.
5815   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5816     // Make -1 and vspltisw -1:
5817     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5818
5819     // Make the VSLW intrinsic, computing 0x8000_0000.
5820     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5821                                    OnesV, DAG, dl);
5822
5823     // xor by OnesV to invert it.
5824     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5825     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5826   }
5827
5828   // The remaining cases assume either big endian element order or
5829   // a splat-size that equates to the element size of the vector
5830   // to be built.  An example that doesn't work for little endian is
5831   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5832   // and a vector element size of 16 bits.  The code below will
5833   // produce the vector in big endian element order, which for little
5834   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5835
5836   // For now, just avoid these optimizations in that case.
5837   // FIXME: Develop correct optimizations for LE with mismatched
5838   // splat and element sizes.
5839
5840   if (Subtarget.isLittleEndian() &&
5841       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5842     return SDValue();
5843
5844   // Check to see if this is a wide variety of vsplti*, binop self cases.
5845   static const signed char SplatCsts[] = {
5846     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5847     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5848   };
5849
5850   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5851     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5852     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5853     int i = SplatCsts[idx];
5854
5855     // Figure out what shift amount will be used by altivec if shifted by i in
5856     // this splat size.
5857     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5858
5859     // vsplti + shl self.
5860     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5861       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5862       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5863         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5864         Intrinsic::ppc_altivec_vslw
5865       };
5866       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5867       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5868     }
5869
5870     // vsplti + srl self.
5871     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5872       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5873       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5874         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5875         Intrinsic::ppc_altivec_vsrw
5876       };
5877       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5878       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5879     }
5880
5881     // vsplti + sra self.
5882     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5883       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5884       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5885         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5886         Intrinsic::ppc_altivec_vsraw
5887       };
5888       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5889       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5890     }
5891
5892     // vsplti + rol self.
5893     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5894                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5895       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5896       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5897         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5898         Intrinsic::ppc_altivec_vrlw
5899       };
5900       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5901       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5902     }
5903
5904     // t = vsplti c, result = vsldoi t, t, 1
5905     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5906       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5907       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5908     }
5909     // t = vsplti c, result = vsldoi t, t, 2
5910     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5911       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5912       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5913     }
5914     // t = vsplti c, result = vsldoi t, t, 3
5915     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5916       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5917       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5918     }
5919   }
5920
5921   return SDValue();
5922 }
5923
5924 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5925 /// the specified operations to build the shuffle.
5926 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5927                                       SDValue RHS, SelectionDAG &DAG,
5928                                       SDLoc dl) {
5929   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5930   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5931   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5932
5933   enum {
5934     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5935     OP_VMRGHW,
5936     OP_VMRGLW,
5937     OP_VSPLTISW0,
5938     OP_VSPLTISW1,
5939     OP_VSPLTISW2,
5940     OP_VSPLTISW3,
5941     OP_VSLDOI4,
5942     OP_VSLDOI8,
5943     OP_VSLDOI12
5944   };
5945
5946   if (OpNum == OP_COPY) {
5947     if (LHSID == (1*9+2)*9+3) return LHS;
5948     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5949     return RHS;
5950   }
5951
5952   SDValue OpLHS, OpRHS;
5953   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5954   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5955
5956   int ShufIdxs[16];
5957   switch (OpNum) {
5958   default: llvm_unreachable("Unknown i32 permute!");
5959   case OP_VMRGHW:
5960     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
5961     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5962     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
5963     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5964     break;
5965   case OP_VMRGLW:
5966     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5967     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5968     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5969     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5970     break;
5971   case OP_VSPLTISW0:
5972     for (unsigned i = 0; i != 16; ++i)
5973       ShufIdxs[i] = (i&3)+0;
5974     break;
5975   case OP_VSPLTISW1:
5976     for (unsigned i = 0; i != 16; ++i)
5977       ShufIdxs[i] = (i&3)+4;
5978     break;
5979   case OP_VSPLTISW2:
5980     for (unsigned i = 0; i != 16; ++i)
5981       ShufIdxs[i] = (i&3)+8;
5982     break;
5983   case OP_VSPLTISW3:
5984     for (unsigned i = 0; i != 16; ++i)
5985       ShufIdxs[i] = (i&3)+12;
5986     break;
5987   case OP_VSLDOI4:
5988     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5989   case OP_VSLDOI8:
5990     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5991   case OP_VSLDOI12:
5992     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5993   }
5994   EVT VT = OpLHS.getValueType();
5995   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5996   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5997   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5998   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5999 }
6000
6001 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6002 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6003 /// return the code it can be lowered into.  Worst case, it can always be
6004 /// lowered into a vperm.
6005 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6006                                                SelectionDAG &DAG) const {
6007   SDLoc dl(Op);
6008   SDValue V1 = Op.getOperand(0);
6009   SDValue V2 = Op.getOperand(1);
6010   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6011   EVT VT = Op.getValueType();
6012   bool isLittleEndian = Subtarget.isLittleEndian();
6013
6014   // Cases that are handled by instructions that take permute immediates
6015   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6016   // selected by the instruction selector.
6017   if (V2.getOpcode() == ISD::UNDEF) {
6018     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6019         PPC::isSplatShuffleMask(SVOp, 2) ||
6020         PPC::isSplatShuffleMask(SVOp, 4) ||
6021         PPC::isVPKUWUMShuffleMask(SVOp, true, DAG) ||
6022         PPC::isVPKUHUMShuffleMask(SVOp, true, DAG) ||
6023         PPC::isVSLDOIShuffleMask(SVOp, true, DAG) != -1 ||
6024         PPC::isVMRGLShuffleMask(SVOp, 1, true, DAG) ||
6025         PPC::isVMRGLShuffleMask(SVOp, 2, true, DAG) ||
6026         PPC::isVMRGLShuffleMask(SVOp, 4, true, DAG) ||
6027         PPC::isVMRGHShuffleMask(SVOp, 1, true, DAG) ||
6028         PPC::isVMRGHShuffleMask(SVOp, 2, true, DAG) ||
6029         PPC::isVMRGHShuffleMask(SVOp, 4, true, DAG)) {
6030       return Op;
6031     }
6032   }
6033
6034   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6035   // and produce a fixed permutation.  If any of these match, do not lower to
6036   // VPERM.
6037   if (PPC::isVPKUWUMShuffleMask(SVOp, false, DAG) ||
6038       PPC::isVPKUHUMShuffleMask(SVOp, false, DAG) ||
6039       PPC::isVSLDOIShuffleMask(SVOp, false, DAG) != -1 ||
6040       PPC::isVMRGLShuffleMask(SVOp, 1, false, DAG) ||
6041       PPC::isVMRGLShuffleMask(SVOp, 2, false, DAG) ||
6042       PPC::isVMRGLShuffleMask(SVOp, 4, false, DAG) ||
6043       PPC::isVMRGHShuffleMask(SVOp, 1, false, DAG) ||
6044       PPC::isVMRGHShuffleMask(SVOp, 2, false, DAG) ||
6045       PPC::isVMRGHShuffleMask(SVOp, 4, false, DAG))
6046     return Op;
6047
6048   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6049   // perfect shuffle table to emit an optimal matching sequence.
6050   ArrayRef<int> PermMask = SVOp->getMask();
6051
6052   unsigned PFIndexes[4];
6053   bool isFourElementShuffle = true;
6054   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6055     unsigned EltNo = 8;   // Start out undef.
6056     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6057       if (PermMask[i*4+j] < 0)
6058         continue;   // Undef, ignore it.
6059
6060       unsigned ByteSource = PermMask[i*4+j];
6061       if ((ByteSource & 3) != j) {
6062         isFourElementShuffle = false;
6063         break;
6064       }
6065
6066       if (EltNo == 8) {
6067         EltNo = ByteSource/4;
6068       } else if (EltNo != ByteSource/4) {
6069         isFourElementShuffle = false;
6070         break;
6071       }
6072     }
6073     PFIndexes[i] = EltNo;
6074   }
6075
6076   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6077   // perfect shuffle vector to determine if it is cost effective to do this as
6078   // discrete instructions, or whether we should use a vperm.
6079   // For now, we skip this for little endian until such time as we have a
6080   // little-endian perfect shuffle table.
6081   if (isFourElementShuffle && !isLittleEndian) {
6082     // Compute the index in the perfect shuffle table.
6083     unsigned PFTableIndex =
6084       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6085
6086     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6087     unsigned Cost  = (PFEntry >> 30);
6088
6089     // Determining when to avoid vperm is tricky.  Many things affect the cost
6090     // of vperm, particularly how many times the perm mask needs to be computed.
6091     // For example, if the perm mask can be hoisted out of a loop or is already
6092     // used (perhaps because there are multiple permutes with the same shuffle
6093     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6094     // the loop requires an extra register.
6095     //
6096     // As a compromise, we only emit discrete instructions if the shuffle can be
6097     // generated in 3 or fewer operations.  When we have loop information
6098     // available, if this block is within a loop, we should avoid using vperm
6099     // for 3-operation perms and use a constant pool load instead.
6100     if (Cost < 3)
6101       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6102   }
6103
6104   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6105   // vector that will get spilled to the constant pool.
6106   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6107
6108   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6109   // that it is in input element units, not in bytes.  Convert now.
6110
6111   // For little endian, the order of the input vectors is reversed, and
6112   // the permutation mask is complemented with respect to 31.  This is
6113   // necessary to produce proper semantics with the big-endian-biased vperm
6114   // instruction.
6115   EVT EltVT = V1.getValueType().getVectorElementType();
6116   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6117
6118   SmallVector<SDValue, 16> ResultMask;
6119   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6120     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6121
6122     for (unsigned j = 0; j != BytesPerElement; ++j)
6123       if (isLittleEndian)
6124         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6125                                              MVT::i32));
6126       else
6127         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6128                                              MVT::i32));
6129   }
6130
6131   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6132                                   ResultMask);
6133   if (isLittleEndian)
6134     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6135                        V2, V1, VPermMask);
6136   else
6137     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6138                        V1, V2, VPermMask);
6139 }
6140
6141 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6142 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6143 /// information about the intrinsic.
6144 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6145                                   bool &isDot) {
6146   unsigned IntrinsicID =
6147     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6148   CompareOpc = -1;
6149   isDot = false;
6150   switch (IntrinsicID) {
6151   default: return false;
6152     // Comparison predicates.
6153   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6154   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6155   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6156   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6157   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6158   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6159   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6160   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6161   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6162   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6163   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6164   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6165   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6166
6167     // Normal Comparisons.
6168   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6169   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6170   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6171   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6172   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6173   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6174   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6175   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6176   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6177   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6178   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6179   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6180   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6181   }
6182   return true;
6183 }
6184
6185 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6186 /// lower, do it, otherwise return null.
6187 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6188                                                    SelectionDAG &DAG) const {
6189   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6190   // opcode number of the comparison.
6191   SDLoc dl(Op);
6192   int CompareOpc;
6193   bool isDot;
6194   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6195     return SDValue();    // Don't custom lower most intrinsics.
6196
6197   // If this is a non-dot comparison, make the VCMP node and we are done.
6198   if (!isDot) {
6199     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6200                               Op.getOperand(1), Op.getOperand(2),
6201                               DAG.getConstant(CompareOpc, MVT::i32));
6202     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6203   }
6204
6205   // Create the PPCISD altivec 'dot' comparison node.
6206   SDValue Ops[] = {
6207     Op.getOperand(2),  // LHS
6208     Op.getOperand(3),  // RHS
6209     DAG.getConstant(CompareOpc, MVT::i32)
6210   };
6211   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6212   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6213
6214   // Now that we have the comparison, emit a copy from the CR to a GPR.
6215   // This is flagged to the above dot comparison.
6216   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6217                                 DAG.getRegister(PPC::CR6, MVT::i32),
6218                                 CompNode.getValue(1));
6219
6220   // Unpack the result based on how the target uses it.
6221   unsigned BitNo;   // Bit # of CR6.
6222   bool InvertBit;   // Invert result?
6223   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6224   default:  // Can't happen, don't crash on invalid number though.
6225   case 0:   // Return the value of the EQ bit of CR6.
6226     BitNo = 0; InvertBit = false;
6227     break;
6228   case 1:   // Return the inverted value of the EQ bit of CR6.
6229     BitNo = 0; InvertBit = true;
6230     break;
6231   case 2:   // Return the value of the LT bit of CR6.
6232     BitNo = 2; InvertBit = false;
6233     break;
6234   case 3:   // Return the inverted value of the LT bit of CR6.
6235     BitNo = 2; InvertBit = true;
6236     break;
6237   }
6238
6239   // Shift the bit into the low position.
6240   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6241                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6242   // Isolate the bit.
6243   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6244                       DAG.getConstant(1, MVT::i32));
6245
6246   // If we are supposed to, toggle the bit.
6247   if (InvertBit)
6248     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6249                         DAG.getConstant(1, MVT::i32));
6250   return Flags;
6251 }
6252
6253 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6254                                                   SelectionDAG &DAG) const {
6255   SDLoc dl(Op);
6256   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6257   // instructions), but for smaller types, we need to first extend up to v2i32
6258   // before doing going farther.
6259   if (Op.getValueType() == MVT::v2i64) {
6260     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6261     if (ExtVT != MVT::v2i32) {
6262       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6263       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6264                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6265                                         ExtVT.getVectorElementType(), 4)));
6266       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6267       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6268                        DAG.getValueType(MVT::v2i32));
6269     }
6270
6271     return Op;
6272   }
6273
6274   return SDValue();
6275 }
6276
6277 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6278                                                    SelectionDAG &DAG) const {
6279   SDLoc dl(Op);
6280   // Create a stack slot that is 16-byte aligned.
6281   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6282   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6283   EVT PtrVT = getPointerTy();
6284   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6285
6286   // Store the input value into Value#0 of the stack slot.
6287   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6288                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6289                                false, false, 0);
6290   // Load it out.
6291   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6292                      false, false, false, 0);
6293 }
6294
6295 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6296   SDLoc dl(Op);
6297   if (Op.getValueType() == MVT::v4i32) {
6298     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6299
6300     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6301     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6302
6303     SDValue RHSSwap =   // = vrlw RHS, 16
6304       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6305
6306     // Shrinkify inputs to v8i16.
6307     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6308     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6309     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6310
6311     // Low parts multiplied together, generating 32-bit results (we ignore the
6312     // top parts).
6313     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6314                                         LHS, RHS, DAG, dl, MVT::v4i32);
6315
6316     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6317                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6318     // Shift the high parts up 16 bits.
6319     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6320                               Neg16, DAG, dl);
6321     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6322   } else if (Op.getValueType() == MVT::v8i16) {
6323     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6324
6325     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6326
6327     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6328                             LHS, RHS, Zero, DAG, dl);
6329   } else if (Op.getValueType() == MVT::v16i8) {
6330     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6331     bool isLittleEndian = Subtarget.isLittleEndian();
6332
6333     // Multiply the even 8-bit parts, producing 16-bit sums.
6334     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6335                                            LHS, RHS, DAG, dl, MVT::v8i16);
6336     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6337
6338     // Multiply the odd 8-bit parts, producing 16-bit sums.
6339     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6340                                           LHS, RHS, DAG, dl, MVT::v8i16);
6341     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6342
6343     // Merge the results together.  Because vmuleub and vmuloub are
6344     // instructions with a big-endian bias, we must reverse the
6345     // element numbering and reverse the meaning of "odd" and "even"
6346     // when generating little endian code.
6347     int Ops[16];
6348     for (unsigned i = 0; i != 8; ++i) {
6349       if (isLittleEndian) {
6350         Ops[i*2  ] = 2*i;
6351         Ops[i*2+1] = 2*i+16;
6352       } else {
6353         Ops[i*2  ] = 2*i+1;
6354         Ops[i*2+1] = 2*i+1+16;
6355       }
6356     }
6357     if (isLittleEndian)
6358       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6359     else
6360       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6361   } else {
6362     llvm_unreachable("Unknown mul to lower!");
6363   }
6364 }
6365
6366 /// LowerOperation - Provide custom lowering hooks for some operations.
6367 ///
6368 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6369   switch (Op.getOpcode()) {
6370   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6371   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6372   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6373   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6374   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6375   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6376   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6377   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6378   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6379   case ISD::VASTART:
6380     return LowerVASTART(Op, DAG, Subtarget);
6381
6382   case ISD::VAARG:
6383     return LowerVAARG(Op, DAG, Subtarget);
6384
6385   case ISD::VACOPY:
6386     return LowerVACOPY(Op, DAG, Subtarget);
6387
6388   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6389   case ISD::DYNAMIC_STACKALLOC:
6390     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6391
6392   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6393   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6394
6395   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6396   case ISD::STORE:              return LowerSTORE(Op, DAG);
6397   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6398   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6399   case ISD::FP_TO_UINT:
6400   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6401                                                        SDLoc(Op));
6402   case ISD::UINT_TO_FP:
6403   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6404   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6405
6406   // Lower 64-bit shifts.
6407   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6408   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6409   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6410
6411   // Vector-related lowering.
6412   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6413   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6414   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6415   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6416   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6417   case ISD::MUL:                return LowerMUL(Op, DAG);
6418
6419   // For counter-based loop handling.
6420   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6421
6422   // Frame & Return address.
6423   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6424   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6425   }
6426 }
6427
6428 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6429                                            SmallVectorImpl<SDValue>&Results,
6430                                            SelectionDAG &DAG) const {
6431   const TargetMachine &TM = getTargetMachine();
6432   SDLoc dl(N);
6433   switch (N->getOpcode()) {
6434   default:
6435     llvm_unreachable("Do not know how to custom type legalize this operation!");
6436   case ISD::INTRINSIC_W_CHAIN: {
6437     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6438         Intrinsic::ppc_is_decremented_ctr_nonzero)
6439       break;
6440
6441     assert(N->getValueType(0) == MVT::i1 &&
6442            "Unexpected result type for CTR decrement intrinsic");
6443     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6444     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6445     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6446                                  N->getOperand(1)); 
6447
6448     Results.push_back(NewInt);
6449     Results.push_back(NewInt.getValue(1));
6450     break;
6451   }
6452   case ISD::VAARG: {
6453     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6454         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6455       return;
6456
6457     EVT VT = N->getValueType(0);
6458
6459     if (VT == MVT::i64) {
6460       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6461
6462       Results.push_back(NewNode);
6463       Results.push_back(NewNode.getValue(1));
6464     }
6465     return;
6466   }
6467   case ISD::FP_ROUND_INREG: {
6468     assert(N->getValueType(0) == MVT::ppcf128);
6469     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6470     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6471                              MVT::f64, N->getOperand(0),
6472                              DAG.getIntPtrConstant(0));
6473     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6474                              MVT::f64, N->getOperand(0),
6475                              DAG.getIntPtrConstant(1));
6476
6477     // Add the two halves of the long double in round-to-zero mode.
6478     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6479
6480     // We know the low half is about to be thrown away, so just use something
6481     // convenient.
6482     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6483                                 FPreg, FPreg));
6484     return;
6485   }
6486   case ISD::FP_TO_SINT:
6487     // LowerFP_TO_INT() can only handle f32 and f64.
6488     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6489       return;
6490     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6491     return;
6492   }
6493 }
6494
6495
6496 //===----------------------------------------------------------------------===//
6497 //  Other Lowering Code
6498 //===----------------------------------------------------------------------===//
6499
6500 MachineBasicBlock *
6501 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6502                                     bool is64bit, unsigned BinOpcode) const {
6503   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6504   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6505
6506   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6507   MachineFunction *F = BB->getParent();
6508   MachineFunction::iterator It = BB;
6509   ++It;
6510
6511   unsigned dest = MI->getOperand(0).getReg();
6512   unsigned ptrA = MI->getOperand(1).getReg();
6513   unsigned ptrB = MI->getOperand(2).getReg();
6514   unsigned incr = MI->getOperand(3).getReg();
6515   DebugLoc dl = MI->getDebugLoc();
6516
6517   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6518   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6519   F->insert(It, loopMBB);
6520   F->insert(It, exitMBB);
6521   exitMBB->splice(exitMBB->begin(), BB,
6522                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6523   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6524
6525   MachineRegisterInfo &RegInfo = F->getRegInfo();
6526   unsigned TmpReg = (!BinOpcode) ? incr :
6527     RegInfo.createVirtualRegister(
6528        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6529                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
6530
6531   //  thisMBB:
6532   //   ...
6533   //   fallthrough --> loopMBB
6534   BB->addSuccessor(loopMBB);
6535
6536   //  loopMBB:
6537   //   l[wd]arx dest, ptr
6538   //   add r0, dest, incr
6539   //   st[wd]cx. r0, ptr
6540   //   bne- loopMBB
6541   //   fallthrough --> exitMBB
6542   BB = loopMBB;
6543   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6544     .addReg(ptrA).addReg(ptrB);
6545   if (BinOpcode)
6546     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6547   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6548     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6549   BuildMI(BB, dl, TII->get(PPC::BCC))
6550     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6551   BB->addSuccessor(loopMBB);
6552   BB->addSuccessor(exitMBB);
6553
6554   //  exitMBB:
6555   //   ...
6556   BB = exitMBB;
6557   return BB;
6558 }
6559
6560 MachineBasicBlock *
6561 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6562                                             MachineBasicBlock *BB,
6563                                             bool is8bit,    // operation
6564                                             unsigned BinOpcode) const {
6565   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6566   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6567   // In 64 bit mode we have to use 64 bits for addresses, even though the
6568   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6569   // registers without caring whether they're 32 or 64, but here we're
6570   // doing actual arithmetic on the addresses.
6571   bool is64bit = Subtarget.isPPC64();
6572   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6573
6574   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6575   MachineFunction *F = BB->getParent();
6576   MachineFunction::iterator It = BB;
6577   ++It;
6578
6579   unsigned dest = MI->getOperand(0).getReg();
6580   unsigned ptrA = MI->getOperand(1).getReg();
6581   unsigned ptrB = MI->getOperand(2).getReg();
6582   unsigned incr = MI->getOperand(3).getReg();
6583   DebugLoc dl = MI->getDebugLoc();
6584
6585   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6586   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6587   F->insert(It, loopMBB);
6588   F->insert(It, exitMBB);
6589   exitMBB->splice(exitMBB->begin(), BB,
6590                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6591   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6592
6593   MachineRegisterInfo &RegInfo = F->getRegInfo();
6594   const TargetRegisterClass *RC =
6595     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6596               (const TargetRegisterClass *) &PPC::GPRCRegClass;
6597   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6598   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6599   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6600   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6601   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6602   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6603   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6604   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6605   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6606   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6607   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6608   unsigned Ptr1Reg;
6609   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6610
6611   //  thisMBB:
6612   //   ...
6613   //   fallthrough --> loopMBB
6614   BB->addSuccessor(loopMBB);
6615
6616   // The 4-byte load must be aligned, while a char or short may be
6617   // anywhere in the word.  Hence all this nasty bookkeeping code.
6618   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6619   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6620   //   xori shift, shift1, 24 [16]
6621   //   rlwinm ptr, ptr1, 0, 0, 29
6622   //   slw incr2, incr, shift
6623   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6624   //   slw mask, mask2, shift
6625   //  loopMBB:
6626   //   lwarx tmpDest, ptr
6627   //   add tmp, tmpDest, incr2
6628   //   andc tmp2, tmpDest, mask
6629   //   and tmp3, tmp, mask
6630   //   or tmp4, tmp3, tmp2
6631   //   stwcx. tmp4, ptr
6632   //   bne- loopMBB
6633   //   fallthrough --> exitMBB
6634   //   srw dest, tmpDest, shift
6635   if (ptrA != ZeroReg) {
6636     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6637     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6638       .addReg(ptrA).addReg(ptrB);
6639   } else {
6640     Ptr1Reg = ptrB;
6641   }
6642   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6643       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6644   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6645       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6646   if (is64bit)
6647     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6648       .addReg(Ptr1Reg).addImm(0).addImm(61);
6649   else
6650     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6651       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6652   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6653       .addReg(incr).addReg(ShiftReg);
6654   if (is8bit)
6655     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6656   else {
6657     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6658     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6659   }
6660   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6661       .addReg(Mask2Reg).addReg(ShiftReg);
6662
6663   BB = loopMBB;
6664   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6665     .addReg(ZeroReg).addReg(PtrReg);
6666   if (BinOpcode)
6667     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6668       .addReg(Incr2Reg).addReg(TmpDestReg);
6669   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6670     .addReg(TmpDestReg).addReg(MaskReg);
6671   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6672     .addReg(TmpReg).addReg(MaskReg);
6673   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6674     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6675   BuildMI(BB, dl, TII->get(PPC::STWCX))
6676     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6677   BuildMI(BB, dl, TII->get(PPC::BCC))
6678     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6679   BB->addSuccessor(loopMBB);
6680   BB->addSuccessor(exitMBB);
6681
6682   //  exitMBB:
6683   //   ...
6684   BB = exitMBB;
6685   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6686     .addReg(ShiftReg);
6687   return BB;
6688 }
6689
6690 llvm::MachineBasicBlock*
6691 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6692                                     MachineBasicBlock *MBB) const {
6693   DebugLoc DL = MI->getDebugLoc();
6694   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6695
6696   MachineFunction *MF = MBB->getParent();
6697   MachineRegisterInfo &MRI = MF->getRegInfo();
6698
6699   const BasicBlock *BB = MBB->getBasicBlock();
6700   MachineFunction::iterator I = MBB;
6701   ++I;
6702
6703   // Memory Reference
6704   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6705   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6706
6707   unsigned DstReg = MI->getOperand(0).getReg();
6708   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6709   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6710   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6711   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6712
6713   MVT PVT = getPointerTy();
6714   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6715          "Invalid Pointer Size!");
6716   // For v = setjmp(buf), we generate
6717   //
6718   // thisMBB:
6719   //  SjLjSetup mainMBB
6720   //  bl mainMBB
6721   //  v_restore = 1
6722   //  b sinkMBB
6723   //
6724   // mainMBB:
6725   //  buf[LabelOffset] = LR
6726   //  v_main = 0
6727   //
6728   // sinkMBB:
6729   //  v = phi(main, restore)
6730   //
6731
6732   MachineBasicBlock *thisMBB = MBB;
6733   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6734   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6735   MF->insert(I, mainMBB);
6736   MF->insert(I, sinkMBB);
6737
6738   MachineInstrBuilder MIB;
6739
6740   // Transfer the remainder of BB and its successor edges to sinkMBB.
6741   sinkMBB->splice(sinkMBB->begin(), MBB,
6742                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6743   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6744
6745   // Note that the structure of the jmp_buf used here is not compatible
6746   // with that used by libc, and is not designed to be. Specifically, it
6747   // stores only those 'reserved' registers that LLVM does not otherwise
6748   // understand how to spill. Also, by convention, by the time this
6749   // intrinsic is called, Clang has already stored the frame address in the
6750   // first slot of the buffer and stack address in the third. Following the
6751   // X86 target code, we'll store the jump address in the second slot. We also
6752   // need to save the TOC pointer (R2) to handle jumps between shared
6753   // libraries, and that will be stored in the fourth slot. The thread
6754   // identifier (R13) is not affected.
6755
6756   // thisMBB:
6757   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6758   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6759   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6760
6761   // Prepare IP either in reg.
6762   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6763   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6764   unsigned BufReg = MI->getOperand(1).getReg();
6765
6766   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6767     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6768             .addReg(PPC::X2)
6769             .addImm(TOCOffset)
6770             .addReg(BufReg);
6771     MIB.setMemRefs(MMOBegin, MMOEnd);
6772   }
6773
6774   // Naked functions never have a base pointer, and so we use r1. For all
6775   // other functions, this decision must be delayed until during PEI.
6776   unsigned BaseReg;
6777   if (MF->getFunction()->getAttributes().hasAttribute(
6778           AttributeSet::FunctionIndex, Attribute::Naked))
6779     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6780   else
6781     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6782
6783   MIB = BuildMI(*thisMBB, MI, DL,
6784                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6785           .addReg(BaseReg)
6786           .addImm(BPOffset)
6787           .addReg(BufReg);
6788   MIB.setMemRefs(MMOBegin, MMOEnd);
6789
6790   // Setup
6791   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6792   const PPCRegisterInfo *TRI =
6793     static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6794   MIB.addRegMask(TRI->getNoPreservedMask());
6795
6796   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6797
6798   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6799           .addMBB(mainMBB);
6800   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6801
6802   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6803   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6804
6805   // mainMBB:
6806   //  mainDstReg = 0
6807   MIB = BuildMI(mainMBB, DL,
6808     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6809
6810   // Store IP
6811   if (Subtarget.isPPC64()) {
6812     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6813             .addReg(LabelReg)
6814             .addImm(LabelOffset)
6815             .addReg(BufReg);
6816   } else {
6817     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6818             .addReg(LabelReg)
6819             .addImm(LabelOffset)
6820             .addReg(BufReg);
6821   }
6822
6823   MIB.setMemRefs(MMOBegin, MMOEnd);
6824
6825   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6826   mainMBB->addSuccessor(sinkMBB);
6827
6828   // sinkMBB:
6829   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6830           TII->get(PPC::PHI), DstReg)
6831     .addReg(mainDstReg).addMBB(mainMBB)
6832     .addReg(restoreDstReg).addMBB(thisMBB);
6833
6834   MI->eraseFromParent();
6835   return sinkMBB;
6836 }
6837
6838 MachineBasicBlock *
6839 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6840                                      MachineBasicBlock *MBB) const {
6841   DebugLoc DL = MI->getDebugLoc();
6842   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6843
6844   MachineFunction *MF = MBB->getParent();
6845   MachineRegisterInfo &MRI = MF->getRegInfo();
6846
6847   // Memory Reference
6848   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6849   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6850
6851   MVT PVT = getPointerTy();
6852   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6853          "Invalid Pointer Size!");
6854
6855   const TargetRegisterClass *RC =
6856     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6857   unsigned Tmp = MRI.createVirtualRegister(RC);
6858   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6859   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6860   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6861   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
6862                   (Subtarget.isSVR4ABI() &&
6863                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6864                      PPC::R29 : PPC::R30);
6865
6866   MachineInstrBuilder MIB;
6867
6868   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6869   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6870   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6871   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6872
6873   unsigned BufReg = MI->getOperand(0).getReg();
6874
6875   // Reload FP (the jumped-to function may not have had a
6876   // frame pointer, and if so, then its r31 will be restored
6877   // as necessary).
6878   if (PVT == MVT::i64) {
6879     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6880             .addImm(0)
6881             .addReg(BufReg);
6882   } else {
6883     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6884             .addImm(0)
6885             .addReg(BufReg);
6886   }
6887   MIB.setMemRefs(MMOBegin, MMOEnd);
6888
6889   // Reload IP
6890   if (PVT == MVT::i64) {
6891     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6892             .addImm(LabelOffset)
6893             .addReg(BufReg);
6894   } else {
6895     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6896             .addImm(LabelOffset)
6897             .addReg(BufReg);
6898   }
6899   MIB.setMemRefs(MMOBegin, MMOEnd);
6900
6901   // Reload SP
6902   if (PVT == MVT::i64) {
6903     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6904             .addImm(SPOffset)
6905             .addReg(BufReg);
6906   } else {
6907     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6908             .addImm(SPOffset)
6909             .addReg(BufReg);
6910   }
6911   MIB.setMemRefs(MMOBegin, MMOEnd);
6912
6913   // Reload BP
6914   if (PVT == MVT::i64) {
6915     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6916             .addImm(BPOffset)
6917             .addReg(BufReg);
6918   } else {
6919     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6920             .addImm(BPOffset)
6921             .addReg(BufReg);
6922   }
6923   MIB.setMemRefs(MMOBegin, MMOEnd);
6924
6925   // Reload TOC
6926   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
6927     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6928             .addImm(TOCOffset)
6929             .addReg(BufReg);
6930
6931     MIB.setMemRefs(MMOBegin, MMOEnd);
6932   }
6933
6934   // Jump
6935   BuildMI(*MBB, MI, DL,
6936           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6937   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6938
6939   MI->eraseFromParent();
6940   return MBB;
6941 }
6942
6943 MachineBasicBlock *
6944 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6945                                                MachineBasicBlock *BB) const {
6946   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6947       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6948     return emitEHSjLjSetJmp(MI, BB);
6949   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6950              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6951     return emitEHSjLjLongJmp(MI, BB);
6952   }
6953
6954   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6955
6956   // To "insert" these instructions we actually have to insert their
6957   // control-flow patterns.
6958   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6959   MachineFunction::iterator It = BB;
6960   ++It;
6961
6962   MachineFunction *F = BB->getParent();
6963
6964   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6965                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
6966                                  MI->getOpcode() == PPC::SELECT_I4 ||
6967                                  MI->getOpcode() == PPC::SELECT_I8)) {
6968     SmallVector<MachineOperand, 2> Cond;
6969     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6970         MI->getOpcode() == PPC::SELECT_CC_I8)
6971       Cond.push_back(MI->getOperand(4));
6972     else
6973       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6974     Cond.push_back(MI->getOperand(1));
6975
6976     DebugLoc dl = MI->getDebugLoc();
6977     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6978     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6979                       Cond, MI->getOperand(2).getReg(),
6980                       MI->getOperand(3).getReg());
6981   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6982              MI->getOpcode() == PPC::SELECT_CC_I8 ||
6983              MI->getOpcode() == PPC::SELECT_CC_F4 ||
6984              MI->getOpcode() == PPC::SELECT_CC_F8 ||
6985              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6986              MI->getOpcode() == PPC::SELECT_I4 ||
6987              MI->getOpcode() == PPC::SELECT_I8 ||
6988              MI->getOpcode() == PPC::SELECT_F4 ||
6989              MI->getOpcode() == PPC::SELECT_F8 ||
6990              MI->getOpcode() == PPC::SELECT_VRRC) {
6991     // The incoming instruction knows the destination vreg to set, the
6992     // condition code register to branch on, the true/false values to
6993     // select between, and a branch opcode to use.
6994
6995     //  thisMBB:
6996     //  ...
6997     //   TrueVal = ...
6998     //   cmpTY ccX, r1, r2
6999     //   bCC copy1MBB
7000     //   fallthrough --> copy0MBB
7001     MachineBasicBlock *thisMBB = BB;
7002     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7003     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7004     DebugLoc dl = MI->getDebugLoc();
7005     F->insert(It, copy0MBB);
7006     F->insert(It, sinkMBB);
7007
7008     // Transfer the remainder of BB and its successor edges to sinkMBB.
7009     sinkMBB->splice(sinkMBB->begin(), BB,
7010                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7011     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7012
7013     // Next, add the true and fallthrough blocks as its successors.
7014     BB->addSuccessor(copy0MBB);
7015     BB->addSuccessor(sinkMBB);
7016
7017     if (MI->getOpcode() == PPC::SELECT_I4 ||
7018         MI->getOpcode() == PPC::SELECT_I8 ||
7019         MI->getOpcode() == PPC::SELECT_F4 ||
7020         MI->getOpcode() == PPC::SELECT_F8 ||
7021         MI->getOpcode() == PPC::SELECT_VRRC) {
7022       BuildMI(BB, dl, TII->get(PPC::BC))
7023         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7024     } else {
7025       unsigned SelectPred = MI->getOperand(4).getImm();
7026       BuildMI(BB, dl, TII->get(PPC::BCC))
7027         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7028     }
7029
7030     //  copy0MBB:
7031     //   %FalseValue = ...
7032     //   # fallthrough to sinkMBB
7033     BB = copy0MBB;
7034
7035     // Update machine-CFG edges
7036     BB->addSuccessor(sinkMBB);
7037
7038     //  sinkMBB:
7039     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7040     //  ...
7041     BB = sinkMBB;
7042     BuildMI(*BB, BB->begin(), dl,
7043             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7044       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7045       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7046   }
7047   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7048     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7049   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7050     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7051   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7052     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7053   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7054     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7055
7056   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7057     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7058   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7059     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7060   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7061     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7062   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7063     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7064
7065   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7066     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7067   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7068     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7069   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7070     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7071   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7072     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7073
7074   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7075     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7076   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7077     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7078   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7079     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7080   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7081     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7082
7083   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7084     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7085   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7086     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7087   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7088     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7089   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7090     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7091
7092   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7093     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7094   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7095     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7096   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7097     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7098   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7099     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7100
7101   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7102     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7103   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7104     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7105   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7106     BB = EmitAtomicBinary(MI, BB, false, 0);
7107   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7108     BB = EmitAtomicBinary(MI, BB, true, 0);
7109
7110   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7111            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7112     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7113
7114     unsigned dest   = MI->getOperand(0).getReg();
7115     unsigned ptrA   = MI->getOperand(1).getReg();
7116     unsigned ptrB   = MI->getOperand(2).getReg();
7117     unsigned oldval = MI->getOperand(3).getReg();
7118     unsigned newval = MI->getOperand(4).getReg();
7119     DebugLoc dl     = MI->getDebugLoc();
7120
7121     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7122     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7123     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7124     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7125     F->insert(It, loop1MBB);
7126     F->insert(It, loop2MBB);
7127     F->insert(It, midMBB);
7128     F->insert(It, exitMBB);
7129     exitMBB->splice(exitMBB->begin(), BB,
7130                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7131     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7132
7133     //  thisMBB:
7134     //   ...
7135     //   fallthrough --> loopMBB
7136     BB->addSuccessor(loop1MBB);
7137
7138     // loop1MBB:
7139     //   l[wd]arx dest, ptr
7140     //   cmp[wd] dest, oldval
7141     //   bne- midMBB
7142     // loop2MBB:
7143     //   st[wd]cx. newval, ptr
7144     //   bne- loopMBB
7145     //   b exitBB
7146     // midMBB:
7147     //   st[wd]cx. dest, ptr
7148     // exitBB:
7149     BB = loop1MBB;
7150     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7151       .addReg(ptrA).addReg(ptrB);
7152     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7153       .addReg(oldval).addReg(dest);
7154     BuildMI(BB, dl, TII->get(PPC::BCC))
7155       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7156     BB->addSuccessor(loop2MBB);
7157     BB->addSuccessor(midMBB);
7158
7159     BB = loop2MBB;
7160     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7161       .addReg(newval).addReg(ptrA).addReg(ptrB);
7162     BuildMI(BB, dl, TII->get(PPC::BCC))
7163       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7164     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7165     BB->addSuccessor(loop1MBB);
7166     BB->addSuccessor(exitMBB);
7167
7168     BB = midMBB;
7169     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7170       .addReg(dest).addReg(ptrA).addReg(ptrB);
7171     BB->addSuccessor(exitMBB);
7172
7173     //  exitMBB:
7174     //   ...
7175     BB = exitMBB;
7176   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7177              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7178     // We must use 64-bit registers for addresses when targeting 64-bit,
7179     // since we're actually doing arithmetic on them.  Other registers
7180     // can be 32-bit.
7181     bool is64bit = Subtarget.isPPC64();
7182     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7183
7184     unsigned dest   = MI->getOperand(0).getReg();
7185     unsigned ptrA   = MI->getOperand(1).getReg();
7186     unsigned ptrB   = MI->getOperand(2).getReg();
7187     unsigned oldval = MI->getOperand(3).getReg();
7188     unsigned newval = MI->getOperand(4).getReg();
7189     DebugLoc dl     = MI->getDebugLoc();
7190
7191     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7192     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7193     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7194     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7195     F->insert(It, loop1MBB);
7196     F->insert(It, loop2MBB);
7197     F->insert(It, midMBB);
7198     F->insert(It, exitMBB);
7199     exitMBB->splice(exitMBB->begin(), BB,
7200                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7201     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7202
7203     MachineRegisterInfo &RegInfo = F->getRegInfo();
7204     const TargetRegisterClass *RC =
7205       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
7206                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
7207     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7208     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7209     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7210     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7211     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7212     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7213     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7214     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7215     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7216     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7217     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7218     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7219     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7220     unsigned Ptr1Reg;
7221     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7222     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7223     //  thisMBB:
7224     //   ...
7225     //   fallthrough --> loopMBB
7226     BB->addSuccessor(loop1MBB);
7227
7228     // The 4-byte load must be aligned, while a char or short may be
7229     // anywhere in the word.  Hence all this nasty bookkeeping code.
7230     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7231     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7232     //   xori shift, shift1, 24 [16]
7233     //   rlwinm ptr, ptr1, 0, 0, 29
7234     //   slw newval2, newval, shift
7235     //   slw oldval2, oldval,shift
7236     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7237     //   slw mask, mask2, shift
7238     //   and newval3, newval2, mask
7239     //   and oldval3, oldval2, mask
7240     // loop1MBB:
7241     //   lwarx tmpDest, ptr
7242     //   and tmp, tmpDest, mask
7243     //   cmpw tmp, oldval3
7244     //   bne- midMBB
7245     // loop2MBB:
7246     //   andc tmp2, tmpDest, mask
7247     //   or tmp4, tmp2, newval3
7248     //   stwcx. tmp4, ptr
7249     //   bne- loop1MBB
7250     //   b exitBB
7251     // midMBB:
7252     //   stwcx. tmpDest, ptr
7253     // exitBB:
7254     //   srw dest, tmpDest, shift
7255     if (ptrA != ZeroReg) {
7256       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7257       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7258         .addReg(ptrA).addReg(ptrB);
7259     } else {
7260       Ptr1Reg = ptrB;
7261     }
7262     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7263         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7264     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7265         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7266     if (is64bit)
7267       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7268         .addReg(Ptr1Reg).addImm(0).addImm(61);
7269     else
7270       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7271         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7272     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7273         .addReg(newval).addReg(ShiftReg);
7274     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7275         .addReg(oldval).addReg(ShiftReg);
7276     if (is8bit)
7277       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7278     else {
7279       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7280       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7281         .addReg(Mask3Reg).addImm(65535);
7282     }
7283     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7284         .addReg(Mask2Reg).addReg(ShiftReg);
7285     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7286         .addReg(NewVal2Reg).addReg(MaskReg);
7287     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7288         .addReg(OldVal2Reg).addReg(MaskReg);
7289
7290     BB = loop1MBB;
7291     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7292         .addReg(ZeroReg).addReg(PtrReg);
7293     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7294         .addReg(TmpDestReg).addReg(MaskReg);
7295     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7296         .addReg(TmpReg).addReg(OldVal3Reg);
7297     BuildMI(BB, dl, TII->get(PPC::BCC))
7298         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7299     BB->addSuccessor(loop2MBB);
7300     BB->addSuccessor(midMBB);
7301
7302     BB = loop2MBB;
7303     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7304         .addReg(TmpDestReg).addReg(MaskReg);
7305     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7306         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7307     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7308         .addReg(ZeroReg).addReg(PtrReg);
7309     BuildMI(BB, dl, TII->get(PPC::BCC))
7310       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7311     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7312     BB->addSuccessor(loop1MBB);
7313     BB->addSuccessor(exitMBB);
7314
7315     BB = midMBB;
7316     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7317       .addReg(ZeroReg).addReg(PtrReg);
7318     BB->addSuccessor(exitMBB);
7319
7320     //  exitMBB:
7321     //   ...
7322     BB = exitMBB;
7323     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7324       .addReg(ShiftReg);
7325   } else if (MI->getOpcode() == PPC::FADDrtz) {
7326     // This pseudo performs an FADD with rounding mode temporarily forced
7327     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7328     // is not modeled at the SelectionDAG level.
7329     unsigned Dest = MI->getOperand(0).getReg();
7330     unsigned Src1 = MI->getOperand(1).getReg();
7331     unsigned Src2 = MI->getOperand(2).getReg();
7332     DebugLoc dl   = MI->getDebugLoc();
7333
7334     MachineRegisterInfo &RegInfo = F->getRegInfo();
7335     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7336
7337     // Save FPSCR value.
7338     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7339
7340     // Set rounding mode to round-to-zero.
7341     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7342     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7343
7344     // Perform addition.
7345     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7346
7347     // Restore FPSCR value.
7348     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7349   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7350              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7351              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7352              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7353     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7354                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7355                       PPC::ANDIo8 : PPC::ANDIo;
7356     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7357                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7358
7359     MachineRegisterInfo &RegInfo = F->getRegInfo();
7360     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7361                                                   &PPC::GPRCRegClass :
7362                                                   &PPC::G8RCRegClass);
7363
7364     DebugLoc dl   = MI->getDebugLoc();
7365     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7366       .addReg(MI->getOperand(1).getReg()).addImm(1);
7367     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7368             MI->getOperand(0).getReg())
7369       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7370   } else {
7371     llvm_unreachable("Unexpected instr type to insert");
7372   }
7373
7374   MI->eraseFromParent();   // The pseudo instruction is gone now.
7375   return BB;
7376 }
7377
7378 //===----------------------------------------------------------------------===//
7379 // Target Optimization Hooks
7380 //===----------------------------------------------------------------------===//
7381
7382 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7383                                                DAGCombinerInfo &DCI) const {
7384   if (DCI.isAfterLegalizeVectorOps())
7385     return SDValue();
7386
7387   EVT VT = Op.getValueType();
7388
7389   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7390       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7391       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7392       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7393
7394     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7395     // For the reciprocal, we need to find the zero of the function:
7396     //   F(X) = A X - 1 [which has a zero at X = 1/A]
7397     //     =>
7398     //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7399     //     does not require additional intermediate precision]
7400
7401     // Convergence is quadratic, so we essentially double the number of digits
7402     // correct after every iteration. The minimum architected relative
7403     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7404     // 23 digits and double has 52 digits.
7405     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7406     if (VT.getScalarType() == MVT::f64)
7407       ++Iterations;
7408
7409     SelectionDAG &DAG = DCI.DAG;
7410     SDLoc dl(Op);
7411
7412     SDValue FPOne =
7413       DAG.getConstantFP(1.0, VT.getScalarType());
7414     if (VT.isVector()) {
7415       assert(VT.getVectorNumElements() == 4 &&
7416              "Unknown vector type");
7417       FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7418                           FPOne, FPOne, FPOne, FPOne);
7419     }
7420
7421     SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7422     DCI.AddToWorklist(Est.getNode());
7423
7424     // Newton iterations: Est = Est + Est (1 - Arg * Est)
7425     for (int i = 0; i < Iterations; ++i) {
7426       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7427       DCI.AddToWorklist(NewEst.getNode());
7428
7429       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7430       DCI.AddToWorklist(NewEst.getNode());
7431
7432       NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7433       DCI.AddToWorklist(NewEst.getNode());
7434
7435       Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7436       DCI.AddToWorklist(Est.getNode());
7437     }
7438
7439     return Est;
7440   }
7441
7442   return SDValue();
7443 }
7444
7445 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7446                                              DAGCombinerInfo &DCI) const {
7447   if (DCI.isAfterLegalizeVectorOps())
7448     return SDValue();
7449
7450   EVT VT = Op.getValueType();
7451
7452   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7453       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7454       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7455       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7456
7457     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7458     // For the reciprocal sqrt, we need to find the zero of the function:
7459     //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7460     //     =>
7461     //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7462     // As a result, we precompute A/2 prior to the iteration loop.
7463
7464     // Convergence is quadratic, so we essentially double the number of digits
7465     // correct after every iteration. The minimum architected relative
7466     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7467     // 23 digits and double has 52 digits.
7468     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7469     if (VT.getScalarType() == MVT::f64)
7470       ++Iterations;
7471
7472     SelectionDAG &DAG = DCI.DAG;
7473     SDLoc dl(Op);
7474
7475     SDValue FPThreeHalves =
7476       DAG.getConstantFP(1.5, VT.getScalarType());
7477     if (VT.isVector()) {
7478       assert(VT.getVectorNumElements() == 4 &&
7479              "Unknown vector type");
7480       FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7481                                   FPThreeHalves, FPThreeHalves,
7482                                   FPThreeHalves, FPThreeHalves);
7483     }
7484
7485     SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7486     DCI.AddToWorklist(Est.getNode());
7487
7488     // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7489     // this entire sequence requires only one FP constant.
7490     SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7491     DCI.AddToWorklist(HalfArg.getNode());
7492
7493     HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7494     DCI.AddToWorklist(HalfArg.getNode());
7495
7496     // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7497     for (int i = 0; i < Iterations; ++i) {
7498       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7499       DCI.AddToWorklist(NewEst.getNode());
7500
7501       NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7502       DCI.AddToWorklist(NewEst.getNode());
7503
7504       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7505       DCI.AddToWorklist(NewEst.getNode());
7506
7507       Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7508       DCI.AddToWorklist(Est.getNode());
7509     }
7510
7511     return Est;
7512   }
7513
7514   return SDValue();
7515 }
7516
7517 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7518 // not enforce equality of the chain operands.
7519 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7520                             unsigned Bytes, int Dist,
7521                             SelectionDAG &DAG) {
7522   EVT VT = LS->getMemoryVT();
7523   if (VT.getSizeInBits() / 8 != Bytes)
7524     return false;
7525
7526   SDValue Loc = LS->getBasePtr();
7527   SDValue BaseLoc = Base->getBasePtr();
7528   if (Loc.getOpcode() == ISD::FrameIndex) {
7529     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7530       return false;
7531     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7532     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7533     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7534     int FS  = MFI->getObjectSize(FI);
7535     int BFS = MFI->getObjectSize(BFI);
7536     if (FS != BFS || FS != (int)Bytes) return false;
7537     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7538   }
7539
7540   // Handle X+C
7541   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7542       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7543     return true;
7544
7545   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7546   const GlobalValue *GV1 = nullptr;
7547   const GlobalValue *GV2 = nullptr;
7548   int64_t Offset1 = 0;
7549   int64_t Offset2 = 0;
7550   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7551   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7552   if (isGA1 && isGA2 && GV1 == GV2)
7553     return Offset1 == (Offset2 + Dist*Bytes);
7554   return false;
7555 }
7556
7557 // Return true is there is a nearyby consecutive load to the one provided
7558 // (regardless of alignment). We search up and down the chain, looking though
7559 // token factors and other loads (but nothing else). As a result, a true
7560 // results indicates that it is safe to create a new consecutive load adjacent
7561 // to the load provided.
7562 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7563   SDValue Chain = LD->getChain();
7564   EVT VT = LD->getMemoryVT();
7565
7566   SmallSet<SDNode *, 16> LoadRoots;
7567   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7568   SmallSet<SDNode *, 16> Visited;
7569
7570   // First, search up the chain, branching to follow all token-factor operands.
7571   // If we find a consecutive load, then we're done, otherwise, record all
7572   // nodes just above the top-level loads and token factors.
7573   while (!Queue.empty()) {
7574     SDNode *ChainNext = Queue.pop_back_val();
7575     if (!Visited.insert(ChainNext))
7576       continue;
7577
7578     if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7579       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7580         return true;
7581
7582       if (!Visited.count(ChainLD->getChain().getNode()))
7583         Queue.push_back(ChainLD->getChain().getNode());
7584     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7585       for (const SDUse &O : ChainNext->ops())
7586         if (!Visited.count(O.getNode()))
7587           Queue.push_back(O.getNode());
7588     } else
7589       LoadRoots.insert(ChainNext);
7590   }
7591
7592   // Second, search down the chain, starting from the top-level nodes recorded
7593   // in the first phase. These top-level nodes are the nodes just above all
7594   // loads and token factors. Starting with their uses, recursively look though
7595   // all loads (just the chain uses) and token factors to find a consecutive
7596   // load.
7597   Visited.clear();
7598   Queue.clear();
7599
7600   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7601        IE = LoadRoots.end(); I != IE; ++I) {
7602     Queue.push_back(*I);
7603        
7604     while (!Queue.empty()) {
7605       SDNode *LoadRoot = Queue.pop_back_val();
7606       if (!Visited.insert(LoadRoot))
7607         continue;
7608
7609       if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7610         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7611           return true;
7612
7613       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7614            UE = LoadRoot->use_end(); UI != UE; ++UI)
7615         if (((isa<LoadSDNode>(*UI) &&
7616             cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7617             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7618           Queue.push_back(*UI);
7619     }
7620   }
7621
7622   return false;
7623 }
7624
7625 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7626                                                   DAGCombinerInfo &DCI) const {
7627   SelectionDAG &DAG = DCI.DAG;
7628   SDLoc dl(N);
7629
7630   assert(Subtarget.useCRBits() &&
7631          "Expecting to be tracking CR bits");
7632   // If we're tracking CR bits, we need to be careful that we don't have:
7633   //   trunc(binary-ops(zext(x), zext(y)))
7634   // or
7635   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7636   // such that we're unnecessarily moving things into GPRs when it would be
7637   // better to keep them in CR bits.
7638
7639   // Note that trunc here can be an actual i1 trunc, or can be the effective
7640   // truncation that comes from a setcc or select_cc.
7641   if (N->getOpcode() == ISD::TRUNCATE &&
7642       N->getValueType(0) != MVT::i1)
7643     return SDValue();
7644
7645   if (N->getOperand(0).getValueType() != MVT::i32 &&
7646       N->getOperand(0).getValueType() != MVT::i64)
7647     return SDValue();
7648
7649   if (N->getOpcode() == ISD::SETCC ||
7650       N->getOpcode() == ISD::SELECT_CC) {
7651     // If we're looking at a comparison, then we need to make sure that the
7652     // high bits (all except for the first) don't matter the result.
7653     ISD::CondCode CC =
7654       cast<CondCodeSDNode>(N->getOperand(
7655         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7656     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7657
7658     if (ISD::isSignedIntSetCC(CC)) {
7659       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7660           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7661         return SDValue();
7662     } else if (ISD::isUnsignedIntSetCC(CC)) {
7663       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7664                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7665           !DAG.MaskedValueIsZero(N->getOperand(1),
7666                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7667         return SDValue();
7668     } else {
7669       // This is neither a signed nor an unsigned comparison, just make sure
7670       // that the high bits are equal.
7671       APInt Op1Zero, Op1One;
7672       APInt Op2Zero, Op2One;
7673       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7674       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7675
7676       // We don't really care about what is known about the first bit (if
7677       // anything), so clear it in all masks prior to comparing them.
7678       Op1Zero.clearBit(0); Op1One.clearBit(0);
7679       Op2Zero.clearBit(0); Op2One.clearBit(0);
7680
7681       if (Op1Zero != Op2Zero || Op1One != Op2One)
7682         return SDValue();
7683     }
7684   }
7685
7686   // We now know that the higher-order bits are irrelevant, we just need to
7687   // make sure that all of the intermediate operations are bit operations, and
7688   // all inputs are extensions.
7689   if (N->getOperand(0).getOpcode() != ISD::AND &&
7690       N->getOperand(0).getOpcode() != ISD::OR  &&
7691       N->getOperand(0).getOpcode() != ISD::XOR &&
7692       N->getOperand(0).getOpcode() != ISD::SELECT &&
7693       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7694       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7695       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7696       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7697       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7698     return SDValue();
7699
7700   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7701       N->getOperand(1).getOpcode() != ISD::AND &&
7702       N->getOperand(1).getOpcode() != ISD::OR  &&
7703       N->getOperand(1).getOpcode() != ISD::XOR &&
7704       N->getOperand(1).getOpcode() != ISD::SELECT &&
7705       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7706       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7707       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7708       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7709       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7710     return SDValue();
7711
7712   SmallVector<SDValue, 4> Inputs;
7713   SmallVector<SDValue, 8> BinOps, PromOps;
7714   SmallPtrSet<SDNode *, 16> Visited;
7715
7716   for (unsigned i = 0; i < 2; ++i) {
7717     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7718           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7719           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7720           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7721         isa<ConstantSDNode>(N->getOperand(i)))
7722       Inputs.push_back(N->getOperand(i));
7723     else
7724       BinOps.push_back(N->getOperand(i));
7725
7726     if (N->getOpcode() == ISD::TRUNCATE)
7727       break;
7728   }
7729
7730   // Visit all inputs, collect all binary operations (and, or, xor and
7731   // select) that are all fed by extensions. 
7732   while (!BinOps.empty()) {
7733     SDValue BinOp = BinOps.back();
7734     BinOps.pop_back();
7735
7736     if (!Visited.insert(BinOp.getNode()))
7737       continue;
7738
7739     PromOps.push_back(BinOp);
7740
7741     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7742       // The condition of the select is not promoted.
7743       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7744         continue;
7745       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7746         continue;
7747
7748       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7749             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7750             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7751            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7752           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7753         Inputs.push_back(BinOp.getOperand(i)); 
7754       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7755                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7756                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7757                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7758                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7759                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7760                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7761                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7762                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7763         BinOps.push_back(BinOp.getOperand(i));
7764       } else {
7765         // We have an input that is not an extension or another binary
7766         // operation; we'll abort this transformation.
7767         return SDValue();
7768       }
7769     }
7770   }
7771
7772   // Make sure that this is a self-contained cluster of operations (which
7773   // is not quite the same thing as saying that everything has only one
7774   // use).
7775   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7776     if (isa<ConstantSDNode>(Inputs[i]))
7777       continue;
7778
7779     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7780                               UE = Inputs[i].getNode()->use_end();
7781          UI != UE; ++UI) {
7782       SDNode *User = *UI;
7783       if (User != N && !Visited.count(User))
7784         return SDValue();
7785
7786       // Make sure that we're not going to promote the non-output-value
7787       // operand(s) or SELECT or SELECT_CC.
7788       // FIXME: Although we could sometimes handle this, and it does occur in
7789       // practice that one of the condition inputs to the select is also one of
7790       // the outputs, we currently can't deal with this.
7791       if (User->getOpcode() == ISD::SELECT) {
7792         if (User->getOperand(0) == Inputs[i])
7793           return SDValue();
7794       } else if (User->getOpcode() == ISD::SELECT_CC) {
7795         if (User->getOperand(0) == Inputs[i] ||
7796             User->getOperand(1) == Inputs[i])
7797           return SDValue();
7798       }
7799     }
7800   }
7801
7802   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7803     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7804                               UE = PromOps[i].getNode()->use_end();
7805          UI != UE; ++UI) {
7806       SDNode *User = *UI;
7807       if (User != N && !Visited.count(User))
7808         return SDValue();
7809
7810       // Make sure that we're not going to promote the non-output-value
7811       // operand(s) or SELECT or SELECT_CC.
7812       // FIXME: Although we could sometimes handle this, and it does occur in
7813       // practice that one of the condition inputs to the select is also one of
7814       // the outputs, we currently can't deal with this.
7815       if (User->getOpcode() == ISD::SELECT) {
7816         if (User->getOperand(0) == PromOps[i])
7817           return SDValue();
7818       } else if (User->getOpcode() == ISD::SELECT_CC) {
7819         if (User->getOperand(0) == PromOps[i] ||
7820             User->getOperand(1) == PromOps[i])
7821           return SDValue();
7822       }
7823     }
7824   }
7825
7826   // Replace all inputs with the extension operand.
7827   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7828     // Constants may have users outside the cluster of to-be-promoted nodes,
7829     // and so we need to replace those as we do the promotions.
7830     if (isa<ConstantSDNode>(Inputs[i]))
7831       continue;
7832     else
7833       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
7834   }
7835
7836   // Replace all operations (these are all the same, but have a different
7837   // (i1) return type). DAG.getNode will validate that the types of
7838   // a binary operator match, so go through the list in reverse so that
7839   // we've likely promoted both operands first. Any intermediate truncations or
7840   // extensions disappear.
7841   while (!PromOps.empty()) {
7842     SDValue PromOp = PromOps.back();
7843     PromOps.pop_back();
7844
7845     if (PromOp.getOpcode() == ISD::TRUNCATE ||
7846         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7847         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7848         PromOp.getOpcode() == ISD::ANY_EXTEND) {
7849       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7850           PromOp.getOperand(0).getValueType() != MVT::i1) {
7851         // The operand is not yet ready (see comment below).
7852         PromOps.insert(PromOps.begin(), PromOp);
7853         continue;
7854       }
7855
7856       SDValue RepValue = PromOp.getOperand(0);
7857       if (isa<ConstantSDNode>(RepValue))
7858         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7859
7860       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7861       continue;
7862     }
7863
7864     unsigned C;
7865     switch (PromOp.getOpcode()) {
7866     default:             C = 0; break;
7867     case ISD::SELECT:    C = 1; break;
7868     case ISD::SELECT_CC: C = 2; break;
7869     }
7870
7871     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7872          PromOp.getOperand(C).getValueType() != MVT::i1) ||
7873         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7874          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7875       // The to-be-promoted operands of this node have not yet been
7876       // promoted (this should be rare because we're going through the
7877       // list backward, but if one of the operands has several users in
7878       // this cluster of to-be-promoted nodes, it is possible).
7879       PromOps.insert(PromOps.begin(), PromOp);
7880       continue;
7881     }
7882
7883     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7884                                 PromOp.getNode()->op_end());
7885
7886     // If there are any constant inputs, make sure they're replaced now.
7887     for (unsigned i = 0; i < 2; ++i)
7888       if (isa<ConstantSDNode>(Ops[C+i]))
7889         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7890
7891     DAG.ReplaceAllUsesOfValueWith(PromOp,
7892       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7893   }
7894
7895   // Now we're left with the initial truncation itself.
7896   if (N->getOpcode() == ISD::TRUNCATE)
7897     return N->getOperand(0);
7898
7899   // Otherwise, this is a comparison. The operands to be compared have just
7900   // changed type (to i1), but everything else is the same.
7901   return SDValue(N, 0);
7902 }
7903
7904 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7905                                                   DAGCombinerInfo &DCI) const {
7906   SelectionDAG &DAG = DCI.DAG;
7907   SDLoc dl(N);
7908
7909   // If we're tracking CR bits, we need to be careful that we don't have:
7910   //   zext(binary-ops(trunc(x), trunc(y)))
7911   // or
7912   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7913   // such that we're unnecessarily moving things into CR bits that can more
7914   // efficiently stay in GPRs. Note that if we're not certain that the high
7915   // bits are set as required by the final extension, we still may need to do
7916   // some masking to get the proper behavior.
7917
7918   // This same functionality is important on PPC64 when dealing with
7919   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7920   // the return values of functions. Because it is so similar, it is handled
7921   // here as well.
7922
7923   if (N->getValueType(0) != MVT::i32 &&
7924       N->getValueType(0) != MVT::i64)
7925     return SDValue();
7926
7927   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7928         Subtarget.useCRBits()) ||
7929        (N->getOperand(0).getValueType() == MVT::i32 &&
7930         Subtarget.isPPC64())))
7931     return SDValue();
7932
7933   if (N->getOperand(0).getOpcode() != ISD::AND &&
7934       N->getOperand(0).getOpcode() != ISD::OR  &&
7935       N->getOperand(0).getOpcode() != ISD::XOR &&
7936       N->getOperand(0).getOpcode() != ISD::SELECT &&
7937       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7938     return SDValue();
7939
7940   SmallVector<SDValue, 4> Inputs;
7941   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7942   SmallPtrSet<SDNode *, 16> Visited;
7943
7944   // Visit all inputs, collect all binary operations (and, or, xor and
7945   // select) that are all fed by truncations. 
7946   while (!BinOps.empty()) {
7947     SDValue BinOp = BinOps.back();
7948     BinOps.pop_back();
7949
7950     if (!Visited.insert(BinOp.getNode()))
7951       continue;
7952
7953     PromOps.push_back(BinOp);
7954
7955     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7956       // The condition of the select is not promoted.
7957       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7958         continue;
7959       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7960         continue;
7961
7962       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7963           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7964         Inputs.push_back(BinOp.getOperand(i)); 
7965       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7966                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7967                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7968                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7969                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7970         BinOps.push_back(BinOp.getOperand(i));
7971       } else {
7972         // We have an input that is not a truncation or another binary
7973         // operation; we'll abort this transformation.
7974         return SDValue();
7975       }
7976     }
7977   }
7978
7979   // Make sure that this is a self-contained cluster of operations (which
7980   // is not quite the same thing as saying that everything has only one
7981   // use).
7982   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7983     if (isa<ConstantSDNode>(Inputs[i]))
7984       continue;
7985
7986     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7987                               UE = Inputs[i].getNode()->use_end();
7988          UI != UE; ++UI) {
7989       SDNode *User = *UI;
7990       if (User != N && !Visited.count(User))
7991         return SDValue();
7992
7993       // Make sure that we're not going to promote the non-output-value
7994       // operand(s) or SELECT or SELECT_CC.
7995       // FIXME: Although we could sometimes handle this, and it does occur in
7996       // practice that one of the condition inputs to the select is also one of
7997       // the outputs, we currently can't deal with this.
7998       if (User->getOpcode() == ISD::SELECT) {
7999         if (User->getOperand(0) == Inputs[i])
8000           return SDValue();
8001       } else if (User->getOpcode() == ISD::SELECT_CC) {
8002         if (User->getOperand(0) == Inputs[i] ||
8003             User->getOperand(1) == Inputs[i])
8004           return SDValue();
8005       }
8006     }
8007   }
8008
8009   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8010     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8011                               UE = PromOps[i].getNode()->use_end();
8012          UI != UE; ++UI) {
8013       SDNode *User = *UI;
8014       if (User != N && !Visited.count(User))
8015         return SDValue();
8016
8017       // Make sure that we're not going to promote the non-output-value
8018       // operand(s) or SELECT or SELECT_CC.
8019       // FIXME: Although we could sometimes handle this, and it does occur in
8020       // practice that one of the condition inputs to the select is also one of
8021       // the outputs, we currently can't deal with this.
8022       if (User->getOpcode() == ISD::SELECT) {
8023         if (User->getOperand(0) == PromOps[i])
8024           return SDValue();
8025       } else if (User->getOpcode() == ISD::SELECT_CC) {
8026         if (User->getOperand(0) == PromOps[i] ||
8027             User->getOperand(1) == PromOps[i])
8028           return SDValue();
8029       }
8030     }
8031   }
8032
8033   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8034   bool ReallyNeedsExt = false;
8035   if (N->getOpcode() != ISD::ANY_EXTEND) {
8036     // If all of the inputs are not already sign/zero extended, then
8037     // we'll still need to do that at the end.
8038     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8039       if (isa<ConstantSDNode>(Inputs[i]))
8040         continue;
8041
8042       unsigned OpBits =
8043         Inputs[i].getOperand(0).getValueSizeInBits();
8044       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8045
8046       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8047            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8048                                   APInt::getHighBitsSet(OpBits,
8049                                                         OpBits-PromBits))) ||
8050           (N->getOpcode() == ISD::SIGN_EXTEND &&
8051            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8052              (OpBits-(PromBits-1)))) {
8053         ReallyNeedsExt = true;
8054         break;
8055       }
8056     }
8057   }
8058
8059   // Replace all inputs, either with the truncation operand, or a
8060   // truncation or extension to the final output type.
8061   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8062     // Constant inputs need to be replaced with the to-be-promoted nodes that
8063     // use them because they might have users outside of the cluster of
8064     // promoted nodes.
8065     if (isa<ConstantSDNode>(Inputs[i]))
8066       continue;
8067
8068     SDValue InSrc = Inputs[i].getOperand(0);
8069     if (Inputs[i].getValueType() == N->getValueType(0))
8070       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8071     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8072       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8073         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8074     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8075       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8076         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8077     else
8078       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8079         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8080   }
8081
8082   // Replace all operations (these are all the same, but have a different
8083   // (promoted) return type). DAG.getNode will validate that the types of
8084   // a binary operator match, so go through the list in reverse so that
8085   // we've likely promoted both operands first.
8086   while (!PromOps.empty()) {
8087     SDValue PromOp = PromOps.back();
8088     PromOps.pop_back();
8089
8090     unsigned C;
8091     switch (PromOp.getOpcode()) {
8092     default:             C = 0; break;
8093     case ISD::SELECT:    C = 1; break;
8094     case ISD::SELECT_CC: C = 2; break;
8095     }
8096
8097     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8098          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8099         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8100          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8101       // The to-be-promoted operands of this node have not yet been
8102       // promoted (this should be rare because we're going through the
8103       // list backward, but if one of the operands has several users in
8104       // this cluster of to-be-promoted nodes, it is possible).
8105       PromOps.insert(PromOps.begin(), PromOp);
8106       continue;
8107     }
8108
8109     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8110                                 PromOp.getNode()->op_end());
8111
8112     // If this node has constant inputs, then they'll need to be promoted here.
8113     for (unsigned i = 0; i < 2; ++i) {
8114       if (!isa<ConstantSDNode>(Ops[C+i]))
8115         continue;
8116       if (Ops[C+i].getValueType() == N->getValueType(0))
8117         continue;
8118
8119       if (N->getOpcode() == ISD::SIGN_EXTEND)
8120         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8121       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8122         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8123       else
8124         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8125     }
8126
8127     DAG.ReplaceAllUsesOfValueWith(PromOp,
8128       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8129   }
8130
8131   // Now we're left with the initial extension itself.
8132   if (!ReallyNeedsExt)
8133     return N->getOperand(0);
8134
8135   // To zero extend, just mask off everything except for the first bit (in the
8136   // i1 case).
8137   if (N->getOpcode() == ISD::ZERO_EXTEND)
8138     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8139                        DAG.getConstant(APInt::getLowBitsSet(
8140                                          N->getValueSizeInBits(0), PromBits),
8141                                        N->getValueType(0)));
8142
8143   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8144          "Invalid extension type");
8145   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8146   SDValue ShiftCst =
8147     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8148   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8149                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8150                                  N->getOperand(0), ShiftCst), ShiftCst);
8151 }
8152
8153 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8154                                              DAGCombinerInfo &DCI) const {
8155   const TargetMachine &TM = getTargetMachine();
8156   SelectionDAG &DAG = DCI.DAG;
8157   SDLoc dl(N);
8158   switch (N->getOpcode()) {
8159   default: break;
8160   case PPCISD::SHL:
8161     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8162       if (C->isNullValue())   // 0 << V -> 0.
8163         return N->getOperand(0);
8164     }
8165     break;
8166   case PPCISD::SRL:
8167     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8168       if (C->isNullValue())   // 0 >>u V -> 0.
8169         return N->getOperand(0);
8170     }
8171     break;
8172   case PPCISD::SRA:
8173     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8174       if (C->isNullValue() ||   //  0 >>s V -> 0.
8175           C->isAllOnesValue())    // -1 >>s V -> -1.
8176         return N->getOperand(0);
8177     }
8178     break;
8179   case ISD::SIGN_EXTEND:
8180   case ISD::ZERO_EXTEND:
8181   case ISD::ANY_EXTEND: 
8182     return DAGCombineExtBoolTrunc(N, DCI);
8183   case ISD::TRUNCATE:
8184   case ISD::SETCC:
8185   case ISD::SELECT_CC:
8186     return DAGCombineTruncBoolExt(N, DCI);
8187   case ISD::FDIV: {
8188     assert(TM.Options.UnsafeFPMath &&
8189            "Reciprocal estimates require UnsafeFPMath");
8190
8191     if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
8192       SDValue RV =
8193         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
8194       if (RV.getNode()) {
8195         DCI.AddToWorklist(RV.getNode());
8196         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8197                            N->getOperand(0), RV);
8198       }
8199     } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
8200                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8201       SDValue RV =
8202         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8203                                  DCI);
8204       if (RV.getNode()) {
8205         DCI.AddToWorklist(RV.getNode());
8206         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
8207                          N->getValueType(0), RV);
8208         DCI.AddToWorklist(RV.getNode());
8209         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8210                            N->getOperand(0), RV);
8211       }
8212     } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
8213                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8214       SDValue RV =
8215         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8216                                  DCI);
8217       if (RV.getNode()) {
8218         DCI.AddToWorklist(RV.getNode());
8219         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
8220                          N->getValueType(0), RV,
8221                          N->getOperand(1).getOperand(1));
8222         DCI.AddToWorklist(RV.getNode());
8223         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8224                            N->getOperand(0), RV);
8225       }
8226     }
8227
8228     SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
8229     if (RV.getNode()) {
8230       DCI.AddToWorklist(RV.getNode());
8231       return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8232                          N->getOperand(0), RV);
8233     }
8234
8235     }
8236     break;
8237   case ISD::FSQRT: {
8238     assert(TM.Options.UnsafeFPMath &&
8239            "Reciprocal estimates require UnsafeFPMath");
8240
8241     // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
8242     // reciprocal sqrt.
8243     SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
8244     if (RV.getNode()) {
8245       DCI.AddToWorklist(RV.getNode());
8246       RV = DAGCombineFastRecip(RV, DCI);
8247       if (RV.getNode()) {
8248         // Unfortunately, RV is now NaN if the input was exactly 0. Select out
8249         // this case and force the answer to 0.
8250
8251         EVT VT = RV.getValueType();
8252
8253         SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
8254         if (VT.isVector()) {
8255           assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
8256           Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
8257         }
8258
8259         SDValue ZeroCmp =
8260           DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
8261                        N->getOperand(0), Zero, ISD::SETEQ);
8262         DCI.AddToWorklist(ZeroCmp.getNode());
8263         DCI.AddToWorklist(RV.getNode());
8264
8265         RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
8266                          ZeroCmp, Zero, RV);
8267         return RV;
8268       }
8269     }
8270
8271     }
8272     break;
8273   case ISD::SINT_TO_FP:
8274     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8275       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8276         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8277         // We allow the src/dst to be either f32/f64, but the intermediate
8278         // type must be i64.
8279         if (N->getOperand(0).getValueType() == MVT::i64 &&
8280             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8281           SDValue Val = N->getOperand(0).getOperand(0);
8282           if (Val.getValueType() == MVT::f32) {
8283             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8284             DCI.AddToWorklist(Val.getNode());
8285           }
8286
8287           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8288           DCI.AddToWorklist(Val.getNode());
8289           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8290           DCI.AddToWorklist(Val.getNode());
8291           if (N->getValueType(0) == MVT::f32) {
8292             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8293                               DAG.getIntPtrConstant(0));
8294             DCI.AddToWorklist(Val.getNode());
8295           }
8296           return Val;
8297         } else if (N->getOperand(0).getValueType() == MVT::i32) {
8298           // If the intermediate type is i32, we can avoid the load/store here
8299           // too.
8300         }
8301       }
8302     }
8303     break;
8304   case ISD::STORE:
8305     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8306     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8307         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8308         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8309         N->getOperand(1).getValueType() == MVT::i32 &&
8310         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8311       SDValue Val = N->getOperand(1).getOperand(0);
8312       if (Val.getValueType() == MVT::f32) {
8313         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8314         DCI.AddToWorklist(Val.getNode());
8315       }
8316       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8317       DCI.AddToWorklist(Val.getNode());
8318
8319       SDValue Ops[] = {
8320         N->getOperand(0), Val, N->getOperand(2),
8321         DAG.getValueType(N->getOperand(1).getValueType())
8322       };
8323
8324       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8325               DAG.getVTList(MVT::Other), Ops,
8326               cast<StoreSDNode>(N)->getMemoryVT(),
8327               cast<StoreSDNode>(N)->getMemOperand());
8328       DCI.AddToWorklist(Val.getNode());
8329       return Val;
8330     }
8331
8332     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8333     if (cast<StoreSDNode>(N)->isUnindexed() &&
8334         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8335         N->getOperand(1).getNode()->hasOneUse() &&
8336         (N->getOperand(1).getValueType() == MVT::i32 ||
8337          N->getOperand(1).getValueType() == MVT::i16 ||
8338          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8339           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8340           N->getOperand(1).getValueType() == MVT::i64))) {
8341       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8342       // Do an any-extend to 32-bits if this is a half-word input.
8343       if (BSwapOp.getValueType() == MVT::i16)
8344         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8345
8346       SDValue Ops[] = {
8347         N->getOperand(0), BSwapOp, N->getOperand(2),
8348         DAG.getValueType(N->getOperand(1).getValueType())
8349       };
8350       return
8351         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8352                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8353                                 cast<StoreSDNode>(N)->getMemOperand());
8354     }
8355     break;
8356   case ISD::LOAD: {
8357     LoadSDNode *LD = cast<LoadSDNode>(N);
8358     EVT VT = LD->getValueType(0);
8359     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8360     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8361     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8362         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8363         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8364          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8365         LD->getAlignment() < ABIAlignment) {
8366       // This is a type-legal unaligned Altivec load.
8367       SDValue Chain = LD->getChain();
8368       SDValue Ptr = LD->getBasePtr();
8369       bool isLittleEndian = Subtarget.isLittleEndian();
8370
8371       // This implements the loading of unaligned vectors as described in
8372       // the venerable Apple Velocity Engine overview. Specifically:
8373       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8374       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8375       //
8376       // The general idea is to expand a sequence of one or more unaligned
8377       // loads into an alignment-based permutation-control instruction (lvsl
8378       // or lvsr), a series of regular vector loads (which always truncate
8379       // their input address to an aligned address), and a series of
8380       // permutations.  The results of these permutations are the requested
8381       // loaded values.  The trick is that the last "extra" load is not taken
8382       // from the address you might suspect (sizeof(vector) bytes after the
8383       // last requested load), but rather sizeof(vector) - 1 bytes after the
8384       // last requested vector. The point of this is to avoid a page fault if
8385       // the base address happened to be aligned. This works because if the
8386       // base address is aligned, then adding less than a full vector length
8387       // will cause the last vector in the sequence to be (re)loaded.
8388       // Otherwise, the next vector will be fetched as you might suspect was
8389       // necessary.
8390
8391       // We might be able to reuse the permutation generation from
8392       // a different base address offset from this one by an aligned amount.
8393       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8394       // optimization later.
8395       Intrinsic::ID Intr = (isLittleEndian ?
8396                             Intrinsic::ppc_altivec_lvsr :
8397                             Intrinsic::ppc_altivec_lvsl);
8398       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8399
8400       // Refine the alignment of the original load (a "new" load created here
8401       // which was identical to the first except for the alignment would be
8402       // merged with the existing node regardless).
8403       MachineFunction &MF = DAG.getMachineFunction();
8404       MachineMemOperand *MMO =
8405         MF.getMachineMemOperand(LD->getPointerInfo(),
8406                                 LD->getMemOperand()->getFlags(),
8407                                 LD->getMemoryVT().getStoreSize(),
8408                                 ABIAlignment);
8409       LD->refineAlignment(MMO);
8410       SDValue BaseLoad = SDValue(LD, 0);
8411
8412       // Note that the value of IncOffset (which is provided to the next
8413       // load's pointer info offset value, and thus used to calculate the
8414       // alignment), and the value of IncValue (which is actually used to
8415       // increment the pointer value) are different! This is because we
8416       // require the next load to appear to be aligned, even though it
8417       // is actually offset from the base pointer by a lesser amount.
8418       int IncOffset = VT.getSizeInBits() / 8;
8419       int IncValue = IncOffset;
8420
8421       // Walk (both up and down) the chain looking for another load at the real
8422       // (aligned) offset (the alignment of the other load does not matter in
8423       // this case). If found, then do not use the offset reduction trick, as
8424       // that will prevent the loads from being later combined (as they would
8425       // otherwise be duplicates).
8426       if (!findConsecutiveLoad(LD, DAG))
8427         --IncValue;
8428
8429       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8430       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8431
8432       SDValue ExtraLoad =
8433         DAG.getLoad(VT, dl, Chain, Ptr,
8434                     LD->getPointerInfo().getWithOffset(IncOffset),
8435                     LD->isVolatile(), LD->isNonTemporal(),
8436                     LD->isInvariant(), ABIAlignment);
8437
8438       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8439         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8440
8441       if (BaseLoad.getValueType() != MVT::v4i32)
8442         BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8443
8444       if (ExtraLoad.getValueType() != MVT::v4i32)
8445         ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8446
8447       // Because vperm has a big-endian bias, we must reverse the order
8448       // of the input vectors and complement the permute control vector
8449       // when generating little endian code.  We have already handled the
8450       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8451       // and ExtraLoad here.
8452       SDValue Perm;
8453       if (isLittleEndian)
8454         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8455                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8456       else
8457         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8458                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8459
8460       if (VT != MVT::v4i32)
8461         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8462
8463       // Now we need to be really careful about how we update the users of the
8464       // original load. We cannot just call DCI.CombineTo (or
8465       // DAG.ReplaceAllUsesWith for that matter), because the load still has
8466       // uses created here (the permutation for example) that need to stay.
8467       SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8468       while (UI != UE) {
8469         SDUse &Use = UI.getUse();
8470         SDNode *User = *UI;
8471         // Note: BaseLoad is checked here because it might not be N, but a
8472         // bitcast of N.
8473         if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8474             User == TF.getNode() || Use.getResNo() > 1) {
8475           ++UI;
8476           continue;
8477         }
8478
8479         SDValue To = Use.getResNo() ? TF : Perm;
8480         ++UI;
8481
8482         SmallVector<SDValue, 8> Ops;
8483         for (const SDUse &O : User->ops()) {
8484           if (O == Use)
8485             Ops.push_back(To);
8486           else
8487             Ops.push_back(O);
8488         }
8489
8490         DAG.UpdateNodeOperands(User, Ops);
8491       }
8492
8493       return SDValue(N, 0);
8494     }
8495     }
8496     break;
8497   case ISD::INTRINSIC_WO_CHAIN: {
8498     bool isLittleEndian = Subtarget.isLittleEndian();
8499     Intrinsic::ID Intr = (isLittleEndian ?
8500                           Intrinsic::ppc_altivec_lvsr :
8501                           Intrinsic::ppc_altivec_lvsl);
8502     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8503         N->getOperand(1)->getOpcode() == ISD::ADD) {
8504       SDValue Add = N->getOperand(1);
8505
8506       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8507             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8508               Add.getValueType().getScalarType().getSizeInBits()))) {
8509         SDNode *BasePtr = Add->getOperand(0).getNode();
8510         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8511              UE = BasePtr->use_end(); UI != UE; ++UI) {
8512           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8513               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8514                 Intr) {
8515             // We've found another LVSL/LVSR, and this address is an aligned
8516             // multiple of that one. The results will be the same, so use the
8517             // one we've just found instead.
8518
8519             return SDValue(*UI, 0);
8520           }
8521         }
8522       }
8523     }
8524     }
8525
8526     break;
8527   case ISD::BSWAP:
8528     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8529     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8530         N->getOperand(0).hasOneUse() &&
8531         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8532          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8533           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8534           N->getValueType(0) == MVT::i64))) {
8535       SDValue Load = N->getOperand(0);
8536       LoadSDNode *LD = cast<LoadSDNode>(Load);
8537       // Create the byte-swapping load.
8538       SDValue Ops[] = {
8539         LD->getChain(),    // Chain
8540         LD->getBasePtr(),  // Ptr
8541         DAG.getValueType(N->getValueType(0)) // VT
8542       };
8543       SDValue BSLoad =
8544         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8545                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8546                                               MVT::i64 : MVT::i32, MVT::Other),
8547                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8548
8549       // If this is an i16 load, insert the truncate.
8550       SDValue ResVal = BSLoad;
8551       if (N->getValueType(0) == MVT::i16)
8552         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8553
8554       // First, combine the bswap away.  This makes the value produced by the
8555       // load dead.
8556       DCI.CombineTo(N, ResVal);
8557
8558       // Next, combine the load away, we give it a bogus result value but a real
8559       // chain result.  The result value is dead because the bswap is dead.
8560       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8561
8562       // Return N so it doesn't get rechecked!
8563       return SDValue(N, 0);
8564     }
8565
8566     break;
8567   case PPCISD::VCMP: {
8568     // If a VCMPo node already exists with exactly the same operands as this
8569     // node, use its result instead of this node (VCMPo computes both a CR6 and
8570     // a normal output).
8571     //
8572     if (!N->getOperand(0).hasOneUse() &&
8573         !N->getOperand(1).hasOneUse() &&
8574         !N->getOperand(2).hasOneUse()) {
8575
8576       // Scan all of the users of the LHS, looking for VCMPo's that match.
8577       SDNode *VCMPoNode = nullptr;
8578
8579       SDNode *LHSN = N->getOperand(0).getNode();
8580       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8581            UI != E; ++UI)
8582         if (UI->getOpcode() == PPCISD::VCMPo &&
8583             UI->getOperand(1) == N->getOperand(1) &&
8584             UI->getOperand(2) == N->getOperand(2) &&
8585             UI->getOperand(0) == N->getOperand(0)) {
8586           VCMPoNode = *UI;
8587           break;
8588         }
8589
8590       // If there is no VCMPo node, or if the flag value has a single use, don't
8591       // transform this.
8592       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8593         break;
8594
8595       // Look at the (necessarily single) use of the flag value.  If it has a
8596       // chain, this transformation is more complex.  Note that multiple things
8597       // could use the value result, which we should ignore.
8598       SDNode *FlagUser = nullptr;
8599       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8600            FlagUser == nullptr; ++UI) {
8601         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8602         SDNode *User = *UI;
8603         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8604           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8605             FlagUser = User;
8606             break;
8607           }
8608         }
8609       }
8610
8611       // If the user is a MFOCRF instruction, we know this is safe.
8612       // Otherwise we give up for right now.
8613       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8614         return SDValue(VCMPoNode, 0);
8615     }
8616     break;
8617   }
8618   case ISD::BRCOND: {
8619     SDValue Cond = N->getOperand(1);
8620     SDValue Target = N->getOperand(2);
8621  
8622     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8623         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8624           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8625
8626       // We now need to make the intrinsic dead (it cannot be instruction
8627       // selected).
8628       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8629       assert(Cond.getNode()->hasOneUse() &&
8630              "Counter decrement has more than one use");
8631
8632       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8633                          N->getOperand(0), Target);
8634     }
8635   }
8636   break;
8637   case ISD::BR_CC: {
8638     // If this is a branch on an altivec predicate comparison, lower this so
8639     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8640     // lowering is done pre-legalize, because the legalizer lowers the predicate
8641     // compare down to code that is difficult to reassemble.
8642     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8643     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8644
8645     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8646     // value. If so, pass-through the AND to get to the intrinsic.
8647     if (LHS.getOpcode() == ISD::AND &&
8648         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8649         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8650           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8651         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8652         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8653           isZero())
8654       LHS = LHS.getOperand(0);
8655
8656     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8657         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8658           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8659         isa<ConstantSDNode>(RHS)) {
8660       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8661              "Counter decrement comparison is not EQ or NE");
8662
8663       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8664       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8665                     (CC == ISD::SETNE && !Val);
8666
8667       // We now need to make the intrinsic dead (it cannot be instruction
8668       // selected).
8669       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8670       assert(LHS.getNode()->hasOneUse() &&
8671              "Counter decrement has more than one use");
8672
8673       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8674                          N->getOperand(0), N->getOperand(4));
8675     }
8676
8677     int CompareOpc;
8678     bool isDot;
8679
8680     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8681         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8682         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8683       assert(isDot && "Can't compare against a vector result!");
8684
8685       // If this is a comparison against something other than 0/1, then we know
8686       // that the condition is never/always true.
8687       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8688       if (Val != 0 && Val != 1) {
8689         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8690           return N->getOperand(0);
8691         // Always !=, turn it into an unconditional branch.
8692         return DAG.getNode(ISD::BR, dl, MVT::Other,
8693                            N->getOperand(0), N->getOperand(4));
8694       }
8695
8696       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8697
8698       // Create the PPCISD altivec 'dot' comparison node.
8699       SDValue Ops[] = {
8700         LHS.getOperand(2),  // LHS of compare
8701         LHS.getOperand(3),  // RHS of compare
8702         DAG.getConstant(CompareOpc, MVT::i32)
8703       };
8704       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8705       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8706
8707       // Unpack the result based on how the target uses it.
8708       PPC::Predicate CompOpc;
8709       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8710       default:  // Can't happen, don't crash on invalid number though.
8711       case 0:   // Branch on the value of the EQ bit of CR6.
8712         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8713         break;
8714       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8715         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8716         break;
8717       case 2:   // Branch on the value of the LT bit of CR6.
8718         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8719         break;
8720       case 3:   // Branch on the inverted value of the LT bit of CR6.
8721         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8722         break;
8723       }
8724
8725       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8726                          DAG.getConstant(CompOpc, MVT::i32),
8727                          DAG.getRegister(PPC::CR6, MVT::i32),
8728                          N->getOperand(4), CompNode.getValue(1));
8729     }
8730     break;
8731   }
8732   }
8733
8734   return SDValue();
8735 }
8736
8737 //===----------------------------------------------------------------------===//
8738 // Inline Assembly Support
8739 //===----------------------------------------------------------------------===//
8740
8741 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8742                                                       APInt &KnownZero,
8743                                                       APInt &KnownOne,
8744                                                       const SelectionDAG &DAG,
8745                                                       unsigned Depth) const {
8746   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8747   switch (Op.getOpcode()) {
8748   default: break;
8749   case PPCISD::LBRX: {
8750     // lhbrx is known to have the top bits cleared out.
8751     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8752       KnownZero = 0xFFFF0000;
8753     break;
8754   }
8755   case ISD::INTRINSIC_WO_CHAIN: {
8756     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8757     default: break;
8758     case Intrinsic::ppc_altivec_vcmpbfp_p:
8759     case Intrinsic::ppc_altivec_vcmpeqfp_p:
8760     case Intrinsic::ppc_altivec_vcmpequb_p:
8761     case Intrinsic::ppc_altivec_vcmpequh_p:
8762     case Intrinsic::ppc_altivec_vcmpequw_p:
8763     case Intrinsic::ppc_altivec_vcmpgefp_p:
8764     case Intrinsic::ppc_altivec_vcmpgtfp_p:
8765     case Intrinsic::ppc_altivec_vcmpgtsb_p:
8766     case Intrinsic::ppc_altivec_vcmpgtsh_p:
8767     case Intrinsic::ppc_altivec_vcmpgtsw_p:
8768     case Intrinsic::ppc_altivec_vcmpgtub_p:
8769     case Intrinsic::ppc_altivec_vcmpgtuh_p:
8770     case Intrinsic::ppc_altivec_vcmpgtuw_p:
8771       KnownZero = ~1U;  // All bits but the low one are known to be zero.
8772       break;
8773     }
8774   }
8775   }
8776 }
8777
8778
8779 /// getConstraintType - Given a constraint, return the type of
8780 /// constraint it is for this target.
8781 PPCTargetLowering::ConstraintType
8782 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8783   if (Constraint.size() == 1) {
8784     switch (Constraint[0]) {
8785     default: break;
8786     case 'b':
8787     case 'r':
8788     case 'f':
8789     case 'v':
8790     case 'y':
8791       return C_RegisterClass;
8792     case 'Z':
8793       // FIXME: While Z does indicate a memory constraint, it specifically
8794       // indicates an r+r address (used in conjunction with the 'y' modifier
8795       // in the replacement string). Currently, we're forcing the base
8796       // register to be r0 in the asm printer (which is interpreted as zero)
8797       // and forming the complete address in the second register. This is
8798       // suboptimal.
8799       return C_Memory;
8800     }
8801   } else if (Constraint == "wc") { // individual CR bits.
8802     return C_RegisterClass;
8803   } else if (Constraint == "wa" || Constraint == "wd" ||
8804              Constraint == "wf" || Constraint == "ws") {
8805     return C_RegisterClass; // VSX registers.
8806   }
8807   return TargetLowering::getConstraintType(Constraint);
8808 }
8809
8810 /// Examine constraint type and operand type and determine a weight value.
8811 /// This object must already have been set up with the operand type
8812 /// and the current alternative constraint selected.
8813 TargetLowering::ConstraintWeight
8814 PPCTargetLowering::getSingleConstraintMatchWeight(
8815     AsmOperandInfo &info, const char *constraint) const {
8816   ConstraintWeight weight = CW_Invalid;
8817   Value *CallOperandVal = info.CallOperandVal;
8818     // If we don't have a value, we can't do a match,
8819     // but allow it at the lowest weight.
8820   if (!CallOperandVal)
8821     return CW_Default;
8822   Type *type = CallOperandVal->getType();
8823
8824   // Look at the constraint type.
8825   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8826     return CW_Register; // an individual CR bit.
8827   else if ((StringRef(constraint) == "wa" ||
8828             StringRef(constraint) == "wd" ||
8829             StringRef(constraint) == "wf") &&
8830            type->isVectorTy())
8831     return CW_Register;
8832   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8833     return CW_Register;
8834
8835   switch (*constraint) {
8836   default:
8837     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8838     break;
8839   case 'b':
8840     if (type->isIntegerTy())
8841       weight = CW_Register;
8842     break;
8843   case 'f':
8844     if (type->isFloatTy())
8845       weight = CW_Register;
8846     break;
8847   case 'd':
8848     if (type->isDoubleTy())
8849       weight = CW_Register;
8850     break;
8851   case 'v':
8852     if (type->isVectorTy())
8853       weight = CW_Register;
8854     break;
8855   case 'y':
8856     weight = CW_Register;
8857     break;
8858   case 'Z':
8859     weight = CW_Memory;
8860     break;
8861   }
8862   return weight;
8863 }
8864
8865 std::pair<unsigned, const TargetRegisterClass*>
8866 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8867                                                 MVT VT) const {
8868   if (Constraint.size() == 1) {
8869     // GCC RS6000 Constraint Letters
8870     switch (Constraint[0]) {
8871     case 'b':   // R1-R31
8872       if (VT == MVT::i64 && Subtarget.isPPC64())
8873         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8874       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8875     case 'r':   // R0-R31
8876       if (VT == MVT::i64 && Subtarget.isPPC64())
8877         return std::make_pair(0U, &PPC::G8RCRegClass);
8878       return std::make_pair(0U, &PPC::GPRCRegClass);
8879     case 'f':
8880       if (VT == MVT::f32 || VT == MVT::i32)
8881         return std::make_pair(0U, &PPC::F4RCRegClass);
8882       if (VT == MVT::f64 || VT == MVT::i64)
8883         return std::make_pair(0U, &PPC::F8RCRegClass);
8884       break;
8885     case 'v':
8886       return std::make_pair(0U, &PPC::VRRCRegClass);
8887     case 'y':   // crrc
8888       return std::make_pair(0U, &PPC::CRRCRegClass);
8889     }
8890   } else if (Constraint == "wc") { // an individual CR bit.
8891     return std::make_pair(0U, &PPC::CRBITRCRegClass);
8892   } else if (Constraint == "wa" || Constraint == "wd" ||
8893              Constraint == "wf") {
8894     return std::make_pair(0U, &PPC::VSRCRegClass);
8895   } else if (Constraint == "ws") {
8896     return std::make_pair(0U, &PPC::VSFRCRegClass);
8897   }
8898
8899   std::pair<unsigned, const TargetRegisterClass*> R =
8900     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8901
8902   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8903   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8904   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8905   // register.
8906   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8907   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8908   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8909       PPC::GPRCRegClass.contains(R.first)) {
8910     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8911     return std::make_pair(TRI->getMatchingSuperReg(R.first,
8912                             PPC::sub_32, &PPC::G8RCRegClass),
8913                           &PPC::G8RCRegClass);
8914   }
8915
8916   return R;
8917 }
8918
8919
8920 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8921 /// vector.  If it is invalid, don't add anything to Ops.
8922 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8923                                                      std::string &Constraint,
8924                                                      std::vector<SDValue>&Ops,
8925                                                      SelectionDAG &DAG) const {
8926   SDValue Result;
8927
8928   // Only support length 1 constraints.
8929   if (Constraint.length() > 1) return;
8930
8931   char Letter = Constraint[0];
8932   switch (Letter) {
8933   default: break;
8934   case 'I':
8935   case 'J':
8936   case 'K':
8937   case 'L':
8938   case 'M':
8939   case 'N':
8940   case 'O':
8941   case 'P': {
8942     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8943     if (!CST) return; // Must be an immediate to match.
8944     unsigned Value = CST->getZExtValue();
8945     switch (Letter) {
8946     default: llvm_unreachable("Unknown constraint letter!");
8947     case 'I':  // "I" is a signed 16-bit constant.
8948       if ((short)Value == (int)Value)
8949         Result = DAG.getTargetConstant(Value, Op.getValueType());
8950       break;
8951     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
8952     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
8953       if ((short)Value == 0)
8954         Result = DAG.getTargetConstant(Value, Op.getValueType());
8955       break;
8956     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
8957       if ((Value >> 16) == 0)
8958         Result = DAG.getTargetConstant(Value, Op.getValueType());
8959       break;
8960     case 'M':  // "M" is a constant that is greater than 31.
8961       if (Value > 31)
8962         Result = DAG.getTargetConstant(Value, Op.getValueType());
8963       break;
8964     case 'N':  // "N" is a positive constant that is an exact power of two.
8965       if ((int)Value > 0 && isPowerOf2_32(Value))
8966         Result = DAG.getTargetConstant(Value, Op.getValueType());
8967       break;
8968     case 'O':  // "O" is the constant zero.
8969       if (Value == 0)
8970         Result = DAG.getTargetConstant(Value, Op.getValueType());
8971       break;
8972     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
8973       if ((short)-Value == (int)-Value)
8974         Result = DAG.getTargetConstant(Value, Op.getValueType());
8975       break;
8976     }
8977     break;
8978   }
8979   }
8980
8981   if (Result.getNode()) {
8982     Ops.push_back(Result);
8983     return;
8984   }
8985
8986   // Handle standard constraint letters.
8987   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8988 }
8989
8990 // isLegalAddressingMode - Return true if the addressing mode represented
8991 // by AM is legal for this target, for a load/store of the specified type.
8992 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8993                                               Type *Ty) const {
8994   // FIXME: PPC does not allow r+i addressing modes for vectors!
8995
8996   // PPC allows a sign-extended 16-bit immediate field.
8997   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8998     return false;
8999
9000   // No global is ever allowed as a base.
9001   if (AM.BaseGV)
9002     return false;
9003
9004   // PPC only support r+r,
9005   switch (AM.Scale) {
9006   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9007     break;
9008   case 1:
9009     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9010       return false;
9011     // Otherwise we have r+r or r+i.
9012     break;
9013   case 2:
9014     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9015       return false;
9016     // Allow 2*r as r+r.
9017     break;
9018   default:
9019     // No other scales are supported.
9020     return false;
9021   }
9022
9023   return true;
9024 }
9025
9026 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9027                                            SelectionDAG &DAG) const {
9028   MachineFunction &MF = DAG.getMachineFunction();
9029   MachineFrameInfo *MFI = MF.getFrameInfo();
9030   MFI->setReturnAddressIsTaken(true);
9031
9032   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9033     return SDValue();
9034
9035   SDLoc dl(Op);
9036   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9037
9038   // Make sure the function does not optimize away the store of the RA to
9039   // the stack.
9040   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9041   FuncInfo->setLRStoreRequired();
9042   bool isPPC64 = Subtarget.isPPC64();
9043   bool isDarwinABI = Subtarget.isDarwinABI();
9044
9045   if (Depth > 0) {
9046     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9047     SDValue Offset =
9048
9049       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9050                       isPPC64? MVT::i64 : MVT::i32);
9051     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9052                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9053                                    FrameAddr, Offset),
9054                        MachinePointerInfo(), false, false, false, 0);
9055   }
9056
9057   // Just load the return address off the stack.
9058   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9059   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9060                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9061 }
9062
9063 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9064                                           SelectionDAG &DAG) const {
9065   SDLoc dl(Op);
9066   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9067
9068   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9069   bool isPPC64 = PtrVT == MVT::i64;
9070
9071   MachineFunction &MF = DAG.getMachineFunction();
9072   MachineFrameInfo *MFI = MF.getFrameInfo();
9073   MFI->setFrameAddressIsTaken(true);
9074
9075   // Naked functions never have a frame pointer, and so we use r1. For all
9076   // other functions, this decision must be delayed until during PEI.
9077   unsigned FrameReg;
9078   if (MF.getFunction()->getAttributes().hasAttribute(
9079         AttributeSet::FunctionIndex, Attribute::Naked))
9080     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9081   else
9082     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9083
9084   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9085                                          PtrVT);
9086   while (Depth--)
9087     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9088                             FrameAddr, MachinePointerInfo(), false, false,
9089                             false, 0);
9090   return FrameAddr;
9091 }
9092
9093 // FIXME? Maybe this could be a TableGen attribute on some registers and
9094 // this table could be generated automatically from RegInfo.
9095 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9096                                               EVT VT) const {
9097   bool isPPC64 = Subtarget.isPPC64();
9098   bool isDarwinABI = Subtarget.isDarwinABI();
9099
9100   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9101       (!isPPC64 && VT != MVT::i32))
9102     report_fatal_error("Invalid register global variable type");
9103
9104   bool is64Bit = isPPC64 && VT == MVT::i64;
9105   unsigned Reg = StringSwitch<unsigned>(RegName)
9106                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9107                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9108                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9109                                   (is64Bit ? PPC::X13 : PPC::R13))
9110                    .Default(0);
9111
9112   if (Reg)
9113     return Reg;
9114   report_fatal_error("Invalid register name global variable");
9115 }
9116
9117 bool
9118 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9119   // The PowerPC target isn't yet aware of offsets.
9120   return false;
9121 }
9122
9123 /// getOptimalMemOpType - Returns the target specific optimal type for load
9124 /// and store operations as a result of memset, memcpy, and memmove
9125 /// lowering. If DstAlign is zero that means it's safe to destination
9126 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9127 /// means there isn't a need to check it against alignment requirement,
9128 /// probably because the source does not need to be loaded. If 'IsMemset' is
9129 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9130 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9131 /// source is constant so it does not need to be loaded.
9132 /// It returns EVT::Other if the type should be determined using generic
9133 /// target-independent logic.
9134 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9135                                            unsigned DstAlign, unsigned SrcAlign,
9136                                            bool IsMemset, bool ZeroMemset,
9137                                            bool MemcpyStrSrc,
9138                                            MachineFunction &MF) const {
9139   if (Subtarget.isPPC64()) {
9140     return MVT::i64;
9141   } else {
9142     return MVT::i32;
9143   }
9144 }
9145
9146 /// \brief Returns true if it is beneficial to convert a load of a constant
9147 /// to just the constant itself.
9148 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9149                                                           Type *Ty) const {
9150   assert(Ty->isIntegerTy());
9151
9152   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9153   if (BitSize == 0 || BitSize > 64)
9154     return false;
9155   return true;
9156 }
9157
9158 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9159   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9160     return false;
9161   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9162   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9163   return NumBits1 == 64 && NumBits2 == 32;
9164 }
9165
9166 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9167   if (!VT1.isInteger() || !VT2.isInteger())
9168     return false;
9169   unsigned NumBits1 = VT1.getSizeInBits();
9170   unsigned NumBits2 = VT2.getSizeInBits();
9171   return NumBits1 == 64 && NumBits2 == 32;
9172 }
9173
9174 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9175   return isInt<16>(Imm) || isUInt<16>(Imm);
9176 }
9177
9178 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9179   return isInt<16>(Imm) || isUInt<16>(Imm);
9180 }
9181
9182 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
9183                                                       unsigned,
9184                                                       bool *Fast) const {
9185   if (DisablePPCUnaligned)
9186     return false;
9187
9188   // PowerPC supports unaligned memory access for simple non-vector types.
9189   // Although accessing unaligned addresses is not as efficient as accessing
9190   // aligned addresses, it is generally more efficient than manual expansion,
9191   // and generally only traps for software emulation when crossing page
9192   // boundaries.
9193
9194   if (!VT.isSimple())
9195     return false;
9196
9197   if (VT.getSimpleVT().isVector()) {
9198     if (Subtarget.hasVSX()) {
9199       if (VT != MVT::v2f64 && VT != MVT::v2i64)
9200         return false;
9201     } else {
9202       return false;
9203     }
9204   }
9205
9206   if (VT == MVT::ppcf128)
9207     return false;
9208
9209   if (Fast)
9210     *Fast = true;
9211
9212   return true;
9213 }
9214
9215 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9216   VT = VT.getScalarType();
9217
9218   if (!VT.isSimple())
9219     return false;
9220
9221   switch (VT.getSimpleVT().SimpleTy) {
9222   case MVT::f32:
9223   case MVT::f64:
9224     return true;
9225   default:
9226     break;
9227   }
9228
9229   return false;
9230 }
9231
9232 bool
9233 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9234                      EVT VT , unsigned DefinedValues) const {
9235   if (VT == MVT::v2i64)
9236     return false;
9237
9238   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9239 }
9240
9241 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9242   if (DisableILPPref || Subtarget.enableMachineScheduler())
9243     return TargetLowering::getSchedulingPreference(N);
9244
9245   return Sched::ILP;
9246 }
9247
9248 // Create a fast isel object.
9249 FastISel *
9250 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9251                                   const TargetLibraryInfo *LibInfo) const {
9252   return PPC::createFastISel(FuncInfo, LibInfo);
9253 }